on ee3da18 help sign in
Idris-dev/src/Util/DynamicLinker.hs
63 lines 2.2 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#endif
26data ForeignFun = forall a. Fun { fun_name :: String
27 , fun_handle :: FunPtr a
28 }
30data DynamicLib = Lib { lib_name :: String
31 , lib_handle :: DL
32 }
34#ifndef WINDOWS
35tryLoadLib :: String -> IO (Maybe DynamicLib)
36tryLoadLib lib = do exactName <- doesFileExist lib
37 let filename = if exactName then lib else lib ++ "." ++ hostDynamicLibExt
38 handle <- dlopen filename [RTLD_NOW, RTLD_GLOBAL]
39 if undl handle == nullPtr
40 then return Nothing
41 else return . Just $ Lib lib handle
44tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun)
45tryLoadFn fn (Lib _ h) = do cFn <- dlsym h fn
46 if cFn == nullFunPtr
47 then return Nothing
48 else return . Just $ Fun fn cFn
49#else
50tryLoadLib :: String -> IO (Maybe DynamicLib)
51tryLoadLib lib = do exactName <- doesFileExist lib
52 let filename = if exactName then lib else lib ++ "." ++ hostDynamicLibExt
53 handle <- loadLibrary filename
54 if handle == nullPtr
55 then return Nothing
56 else return . Just $ Lib lib handle
58tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun)
59tryLoadFn fn (Lib _ h) = do cFn <- getProcAddress h fn
60 if cFn == nullPtr
61 then return Nothing
62 else return . Just $ Fun fn (castPtrToFunPtr cFn)
63#endif