on ef93607 help sign in
Idris-dev/src/Util/DynamicLinker.hs
68 lines 2.4 kB history raw
1-- | Platform-specific dynamic linking support. Add new platforms to this file
2-- through conditional compilation.
3{-# LANGUAGE ExistentialQuantification, CPP #-}
4module Util.DynamicLinker where
6import Foreign.LibFFI
7import Foreign.Ptr (nullPtr, FunPtr, nullFunPtr,castPtrToFunPtr)
8import System.Directory
9#ifndef WINDOWS
10import System.Posix.DynamicLinker
11#else
12import System.Win32.DLL
13import System.Win32.Types
14type DL = HMODULE
15#endif
17hostDynamicLibExt :: String
18#ifdef LINUX
19hostDynamicLibExt = "so"
20#elif MACOSX
21hostDynamicLibExt = "dylib"
22#elif WINDOWS
23hostDynamicLibExt = "dll"
24#else
25hostDynamicLibExt = error $ unwords
26 [ "Undefined file extension for dynamic libraries"
27 , "in Idris' Util.DynamicLinker."
28 ]
29#endif
31data ForeignFun = forall a. Fun { fun_name :: String
32 , fun_handle :: FunPtr a
33 }
35data DynamicLib = Lib { lib_name :: String
36 , lib_handle :: DL
37 }
39#ifndef WINDOWS
40tryLoadLib :: String -> IO (Maybe DynamicLib)
41tryLoadLib lib = do exactName <- doesFileExist lib
42 let filename = if exactName then lib else lib ++ "." ++ hostDynamicLibExt
43 handle <- dlopen filename [RTLD_NOW, RTLD_GLOBAL]
44 if undl handle == nullPtr
45 then return Nothing
46 else return . Just $ Lib lib handle
49tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun)
50tryLoadFn fn (Lib _ h) = do cFn <- dlsym h fn
51 if cFn == nullFunPtr
52 then return Nothing
53 else return . Just $ Fun fn cFn
54#else
55tryLoadLib :: String -> IO (Maybe DynamicLib)
56tryLoadLib lib = do exactName <- doesFileExist lib
57 let filename = if exactName then lib else lib ++ "." ++ hostDynamicLibExt
58 handle <- loadLibrary filename
59 if handle == nullPtr
60 then return Nothing
61 else return . Just $ Lib lib handle
63tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun)
64tryLoadFn fn (Lib _ h) = do cFn <- getProcAddress h fn
65 if cFn == nullPtr
66 then return Nothing
67 else return . Just $ Fun fn (castPtrToFunPtr cFn)
68#endif