PageRenderTime 72ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/ghci/Linker.lhs

https://bitbucket.org/carter/ghc
Haskell | 1272 lines | 807 code | 198 blank | 267 comment | 61 complexity | 4fe3f0f40a086d7154fa049ac5f0109f MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. %
  2. % (c) The University of Glasgow 2005-2006
  3. %
  4. \begin{code}
  5. -- | The dynamic linker for GHCi.
  6. --
  7. -- This module deals with the top-level issues of dynamic linking,
  8. -- calling the object-code linker and the byte-code linker where
  9. -- necessary.
  10. {-# OPTIONS -fno-cse #-}
  11. -- -fno-cse is needed for GLOBAL_VAR's to behave properly
  12. module Linker ( HValue, getHValue, showLinkerState,
  13. linkExpr, linkDecls, unload, withExtendedLinkEnv,
  14. extendLinkEnv, deleteFromLinkEnv,
  15. extendLoadedPkgs,
  16. linkPackages,initDynLinker,linkModule,
  17. -- Saving/restoring globals
  18. PersistentLinkerState, saveLinkerGlobals, restoreLinkerGlobals
  19. ) where
  20. #include "HsVersions.h"
  21. import LoadIface
  22. import ObjLink
  23. import ByteCodeLink
  24. import ByteCodeItbls
  25. import ByteCodeAsm
  26. import TcRnMonad
  27. import Packages
  28. import DriverPhases
  29. import Finder
  30. import HscTypes
  31. import Name
  32. import NameEnv
  33. import NameSet
  34. import UniqFM
  35. import Module
  36. import ListSetOps
  37. import DynFlags
  38. import BasicTypes
  39. import Outputable
  40. import Panic
  41. import Util
  42. import ErrUtils
  43. import SrcLoc
  44. import qualified Maybes
  45. import UniqSet
  46. import FastString
  47. import Config
  48. import Platform
  49. import SysTools
  50. import PrelNames
  51. -- Standard libraries
  52. import Control.Monad
  53. import Data.IORef
  54. import Data.List
  55. import qualified Data.Map as Map
  56. import Control.Concurrent.MVar
  57. import System.FilePath
  58. import System.IO
  59. #if __GLASGOW_HASKELL__ > 704
  60. import System.Directory hiding (findFile)
  61. #else
  62. import System.Directory
  63. #endif
  64. import Distribution.Package hiding (depends, PackageId)
  65. import Exception
  66. \end{code}
  67. %************************************************************************
  68. %* *
  69. The Linker's state
  70. %* *
  71. %************************************************************************
  72. The persistent linker state *must* match the actual state of the
  73. C dynamic linker at all times, so we keep it in a private global variable.
  74. The global IORef used for PersistentLinkerState actually contains another MVar.
  75. The reason for this is that we want to allow another loaded copy of the GHC
  76. library to side-effect the PLS and for those changes to be reflected here.
  77. The PersistentLinkerState maps Names to actual closures (for
  78. interpreted code only), for use during linking.
  79. \begin{code}
  80. GLOBAL_VAR_M(v_PersistentLinkerState, newMVar (panic "Dynamic linker not initialised"), MVar PersistentLinkerState)
  81. GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
  82. modifyPLS_ :: (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
  83. modifyPLS_ f = readIORef v_PersistentLinkerState >>= flip modifyMVar_ f
  84. modifyPLS :: (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
  85. modifyPLS f = readIORef v_PersistentLinkerState >>= flip modifyMVar f
  86. data PersistentLinkerState
  87. = PersistentLinkerState {
  88. -- Current global mapping from Names to their true values
  89. closure_env :: ClosureEnv,
  90. -- The current global mapping from RdrNames of DataCons to
  91. -- info table addresses.
  92. -- When a new Unlinked is linked into the running image, or an existing
  93. -- module in the image is replaced, the itbl_env must be updated
  94. -- appropriately.
  95. itbl_env :: !ItblEnv,
  96. -- The currently loaded interpreted modules (home package)
  97. bcos_loaded :: ![Linkable],
  98. -- And the currently-loaded compiled modules (home package)
  99. objs_loaded :: ![Linkable],
  100. -- The currently-loaded packages; always object code
  101. -- Held, as usual, in dependency order; though I am not sure if
  102. -- that is really important
  103. pkgs_loaded :: ![PackageId]
  104. }
  105. emptyPLS :: DynFlags -> PersistentLinkerState
  106. emptyPLS _ = PersistentLinkerState {
  107. closure_env = emptyNameEnv,
  108. itbl_env = emptyNameEnv,
  109. pkgs_loaded = init_pkgs,
  110. bcos_loaded = [],
  111. objs_loaded = [] }
  112. -- Packages that don't need loading, because the compiler
  113. -- shares them with the interpreted program.
  114. --
  115. -- The linker's symbol table is populated with RTS symbols using an
  116. -- explicit list. See rts/Linker.c for details.
  117. where init_pkgs = [rtsPackageId]
  118. extendLoadedPkgs :: [PackageId] -> IO ()
  119. extendLoadedPkgs pkgs =
  120. modifyPLS_ $ \s ->
  121. return s{ pkgs_loaded = pkgs ++ pkgs_loaded s }
  122. extendLinkEnv :: [(Name,HValue)] -> IO ()
  123. -- Automatically discards shadowed bindings
  124. extendLinkEnv new_bindings =
  125. modifyPLS_ $ \pls ->
  126. let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
  127. in return pls{ closure_env = new_closure_env }
  128. deleteFromLinkEnv :: [Name] -> IO ()
  129. deleteFromLinkEnv to_remove =
  130. modifyPLS_ $ \pls ->
  131. let new_closure_env = delListFromNameEnv (closure_env pls) to_remove
  132. in return pls{ closure_env = new_closure_env }
  133. -- | Get the 'HValue' associated with the given name.
  134. --
  135. -- May cause loading the module that contains the name.
  136. --
  137. -- Throws a 'ProgramError' if loading fails or the name cannot be found.
  138. getHValue :: HscEnv -> Name -> IO HValue
  139. getHValue hsc_env name = do
  140. initDynLinker (hsc_dflags hsc_env)
  141. pls <- modifyPLS $ \pls -> do
  142. if (isExternalName name) then do
  143. (pls', ok) <- linkDependencies hsc_env pls noSrcSpan [nameModule name]
  144. if (failed ok) then ghcError (ProgramError "")
  145. else return (pls', pls')
  146. else
  147. return (pls, pls)
  148. lookupName (closure_env pls) name
  149. linkDependencies :: HscEnv -> PersistentLinkerState
  150. -> SrcSpan -> [Module]
  151. -> IO (PersistentLinkerState, SuccessFlag)
  152. linkDependencies hsc_env pls span needed_mods = do
  153. -- initDynLinker (hsc_dflags hsc_env)
  154. let hpt = hsc_HPT hsc_env
  155. dflags = hsc_dflags hsc_env
  156. -- The interpreter and dynamic linker can only handle object code built
  157. -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
  158. -- So here we check the build tag: if we're building a non-standard way
  159. -- then we need to find & link object files built the "normal" way.
  160. maybe_normal_osuf <- checkNonStdWay dflags span
  161. -- Find what packages and linkables are required
  162. (lnks, pkgs) <- getLinkDeps hsc_env hpt pls
  163. maybe_normal_osuf span needed_mods
  164. -- Link the packages and modules required
  165. pls1 <- linkPackages' dflags pkgs pls
  166. linkModules dflags pls1 lnks
  167. -- | Temporarily extend the linker state.
  168. withExtendedLinkEnv :: (MonadIO m, ExceptionMonad m) =>
  169. [(Name,HValue)] -> m a -> m a
  170. withExtendedLinkEnv new_env action
  171. = gbracket (liftIO $ extendLinkEnv new_env)
  172. (\_ -> reset_old_env)
  173. (\_ -> action)
  174. where
  175. -- Remember that the linker state might be side-effected
  176. -- during the execution of the IO action, and we don't want to
  177. -- lose those changes (we might have linked a new module or
  178. -- package), so the reset action only removes the names we
  179. -- added earlier.
  180. reset_old_env = liftIO $ do
  181. modifyPLS_ $ \pls ->
  182. let cur = closure_env pls
  183. new = delListFromNameEnv cur (map fst new_env)
  184. in return pls{ closure_env = new }
  185. -- filterNameMap removes from the environment all entries except
  186. -- those for a given set of modules;
  187. -- Note that this removes all *local* (i.e. non-isExternal) names too
  188. -- (these are the temporary bindings from the command line).
  189. -- Used to filter both the ClosureEnv and ItblEnv
  190. filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
  191. filterNameMap mods env
  192. = filterNameEnv keep_elt env
  193. where
  194. keep_elt (n,_) = isExternalName n
  195. && (nameModule n `elem` mods)
  196. -- | Display the persistent linker state.
  197. showLinkerState :: DynFlags -> IO ()
  198. showLinkerState dflags
  199. = do pls <- readIORef v_PersistentLinkerState >>= readMVar
  200. log_action dflags dflags SevDump noSrcSpan defaultDumpStyle
  201. (vcat [text "----- Linker state -----",
  202. text "Pkgs:" <+> ppr (pkgs_loaded pls),
  203. text "Objs:" <+> ppr (objs_loaded pls),
  204. text "BCOs:" <+> ppr (bcos_loaded pls)])
  205. \end{code}
  206. %************************************************************************
  207. %* *
  208. \subsection{Initialisation}
  209. %* *
  210. %************************************************************************
  211. \begin{code}
  212. -- | Initialise the dynamic linker. This entails
  213. --
  214. -- a) Calling the C initialisation procedure,
  215. --
  216. -- b) Loading any packages specified on the command line,
  217. --
  218. -- c) Loading any packages specified on the command line, now held in the
  219. -- @-l@ options in @v_Opt_l@,
  220. --
  221. -- d) Loading any @.o\/.dll@ files specified on the command line, now held
  222. -- in @ldInputs@,
  223. --
  224. -- e) Loading any MacOS frameworks.
  225. --
  226. -- NOTE: This function is idempotent; if called more than once, it does
  227. -- nothing. This is useful in Template Haskell, where we call it before
  228. -- trying to link.
  229. --
  230. initDynLinker :: DynFlags -> IO ()
  231. initDynLinker dflags =
  232. modifyPLS_ $ \pls0 -> do
  233. done <- readIORef v_InitLinkerDone
  234. if done then return pls0
  235. else do writeIORef v_InitLinkerDone True
  236. reallyInitDynLinker dflags
  237. reallyInitDynLinker :: DynFlags -> IO PersistentLinkerState
  238. reallyInitDynLinker dflags =
  239. do { -- Initialise the linker state
  240. let pls0 = emptyPLS dflags
  241. -- (a) initialise the C dynamic linker
  242. ; initObjLinker
  243. -- (b) Load packages from the command-line (Note [preload packages])
  244. ; pls <- linkPackages' dflags (preloadPackages (pkgState dflags)) pls0
  245. -- (c) Link libraries from the command-line
  246. ; let optl = getOpts dflags opt_l
  247. ; let minus_ls = [ lib | '-':'l':lib <- optl ]
  248. ; let lib_paths = libraryPaths dflags
  249. ; libspecs <- mapM (locateLib dflags False lib_paths) minus_ls
  250. -- (d) Link .o files from the command-line
  251. ; let cmdline_ld_inputs = ldInputs dflags
  252. ; classified_ld_inputs <- mapM (classifyLdInput dflags) cmdline_ld_inputs
  253. -- (e) Link any MacOS frameworks
  254. ; let platform = targetPlatform dflags
  255. ; let framework_paths = case platformOS platform of
  256. OSDarwin -> frameworkPaths dflags
  257. _ -> []
  258. ; let frameworks = case platformOS platform of
  259. OSDarwin -> cmdlineFrameworks dflags
  260. _ -> []
  261. -- Finally do (c),(d),(e)
  262. ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
  263. ++ libspecs
  264. ++ map Framework frameworks
  265. ; if null cmdline_lib_specs then return pls
  266. else do
  267. { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
  268. ; maybePutStr dflags "final link ... "
  269. ; ok <- resolveObjs
  270. ; if succeeded ok then maybePutStrLn dflags "done"
  271. else ghcError (ProgramError "linking extra libraries/objects failed")
  272. ; return pls
  273. }}
  274. {- Note [preload packages]
  275. Why do we need to preload packages from the command line? This is an
  276. explanation copied from #2437:
  277. I tried to implement the suggestion from #3560, thinking it would be
  278. easy, but there are two reasons we link in packages eagerly when they
  279. are mentioned on the command line:
  280. * So that you can link in extra object files or libraries that
  281. depend on the packages. e.g. ghc -package foo -lbar where bar is a
  282. C library that depends on something in foo. So we could link in
  283. foo eagerly if and only if there are extra C libs or objects to
  284. link in, but....
  285. * Haskell code can depend on a C function exported by a package, and
  286. the normal dependency tracking that TH uses can't know about these
  287. dependencies. The test ghcilink004 relies on this, for example.
  288. I conclude that we need two -package flags: one that says "this is a
  289. package I want to make available", and one that says "this is a
  290. package I want to link in eagerly". Would that be too complicated for
  291. users?
  292. -}
  293. classifyLdInput :: DynFlags -> FilePath -> IO (Maybe LibrarySpec)
  294. classifyLdInput dflags f
  295. | isObjectFilename platform f = return (Just (Object f))
  296. | isDynLibFilename platform f = return (Just (DLLPath f))
  297. | otherwise = do
  298. log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
  299. (text ("Warning: ignoring unrecognised input `" ++ f ++ "'"))
  300. return Nothing
  301. where platform = targetPlatform dflags
  302. preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
  303. preloadLib dflags lib_paths framework_paths lib_spec
  304. = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
  305. case lib_spec of
  306. Object static_ish
  307. -> do b <- preload_static lib_paths static_ish
  308. maybePutStrLn dflags (if b then "done"
  309. else "not found")
  310. Archive static_ish
  311. -> do b <- preload_static_archive lib_paths static_ish
  312. maybePutStrLn dflags (if b then "done"
  313. else "not found")
  314. DLL dll_unadorned
  315. -> do maybe_errstr <- loadDLL (mkSOName platform dll_unadorned)
  316. case maybe_errstr of
  317. Nothing -> maybePutStrLn dflags "done"
  318. Just mm -> preloadFailed mm lib_paths lib_spec
  319. DLLPath dll_path
  320. -> do maybe_errstr <- loadDLL dll_path
  321. case maybe_errstr of
  322. Nothing -> maybePutStrLn dflags "done"
  323. Just mm -> preloadFailed mm lib_paths lib_spec
  324. Framework framework ->
  325. case platformOS (targetPlatform dflags) of
  326. OSDarwin ->
  327. do maybe_errstr <- loadFramework framework_paths framework
  328. case maybe_errstr of
  329. Nothing -> maybePutStrLn dflags "done"
  330. Just mm -> preloadFailed mm framework_paths lib_spec
  331. _ -> panic "preloadLib Framework"
  332. where
  333. platform = targetPlatform dflags
  334. preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
  335. preloadFailed sys_errmsg paths spec
  336. = do maybePutStr dflags "failed.\n"
  337. ghcError $
  338. CmdLineError (
  339. "user specified .o/.so/.DLL could not be loaded ("
  340. ++ sys_errmsg ++ ")\nWhilst trying to load: "
  341. ++ showLS spec ++ "\nAdditional directories searched:"
  342. ++ (if null paths then " (none)" else
  343. (concat (intersperse "\n" (map (" "++) paths)))))
  344. -- Not interested in the paths in the static case.
  345. preload_static _paths name
  346. = do b <- doesFileExist name
  347. if not b then return False
  348. else loadObj name >> return True
  349. preload_static_archive _paths name
  350. = do b <- doesFileExist name
  351. if not b then return False
  352. else loadArchive name >> return True
  353. \end{code}
  354. %************************************************************************
  355. %* *
  356. Link a byte-code expression
  357. %* *
  358. %************************************************************************
  359. \begin{code}
  360. -- | Link a single expression, /including/ first linking packages and
  361. -- modules that this expression depends on.
  362. --
  363. -- Raises an IO exception ('ProgramError') if it can't find a compiled
  364. -- version of the dependents to link.
  365. --
  366. linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO HValue
  367. linkExpr hsc_env span root_ul_bco
  368. = do {
  369. -- Initialise the linker (if it's not been done already)
  370. let dflags = hsc_dflags hsc_env
  371. ; initDynLinker dflags
  372. -- Take lock for the actual work.
  373. ; modifyPLS $ \pls0 -> do {
  374. -- Link the packages and modules required
  375. ; (pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
  376. ; if failed ok then
  377. ghcError (ProgramError "")
  378. else do {
  379. -- Link the expression itself
  380. let ie = itbl_env pls
  381. ce = closure_env pls
  382. -- Link the necessary packages and linkables
  383. ; (_, (root_hval:_)) <- linkSomeBCOs dflags False ie ce [root_ul_bco]
  384. ; return (pls, root_hval)
  385. }}}
  386. where
  387. free_names = nameSetToList (bcoFreeNames root_ul_bco)
  388. needed_mods :: [Module]
  389. needed_mods = [ nameModule n | n <- free_names,
  390. isExternalName n, -- Names from other modules
  391. not (isWiredInName n) -- Exclude wired-in names
  392. ] -- (see note below)
  393. -- Exclude wired-in names because we may not have read
  394. -- their interface files, so getLinkDeps will fail
  395. -- All wired-in names are in the base package, which we link
  396. -- by default, so we can safely ignore them here.
  397. dieWith :: DynFlags -> SrcSpan -> MsgDoc -> IO a
  398. dieWith dflags span msg = ghcError (ProgramError (showSDoc dflags (mkLocMessage SevFatal span msg)))
  399. checkNonStdWay :: DynFlags -> SrcSpan -> IO Bool
  400. checkNonStdWay dflags srcspan = do
  401. let tag = buildTag dflags
  402. dynamicByDefault = dYNAMIC_BY_DEFAULT dflags
  403. if (null tag && not dynamicByDefault) ||
  404. (tag == "dyn" && dynamicByDefault)
  405. then return False
  406. -- see #3604: object files compiled for way "dyn" need to link to the
  407. -- dynamic packages, so we can't load them into a statically-linked GHCi.
  408. -- we have to treat "dyn" in the same way as "prof".
  409. --
  410. -- In the future when GHCi is dynamically linked we should be able to relax
  411. -- this, but they we may have to make it possible to load either ordinary
  412. -- .o files or -dynamic .o files into GHCi (currently that's not possible
  413. -- because the dynamic objects contain refs to e.g. __stginit_base_Prelude_dyn
  414. -- whereas we have __stginit_base_Prelude_.
  415. else if (objectSuf dflags == normalObjectSuffix) && not (null tag)
  416. then failNonStd dflags srcspan
  417. else return True
  418. normalObjectSuffix :: String
  419. normalObjectSuffix = phaseInputExt StopLn
  420. failNonStd :: DynFlags -> SrcSpan -> IO Bool
  421. failNonStd dflags srcspan = dieWith dflags srcspan $
  422. ptext (sLit "Dynamic linking required, but this is a non-standard build (eg. prof).") $$
  423. ptext (sLit "You need to build the program twice: once the normal way, and then") $$
  424. ptext (sLit "in the desired way using -osuf to set the object file suffix.")
  425. getLinkDeps :: HscEnv -> HomePackageTable
  426. -> PersistentLinkerState
  427. -> Bool -- replace object suffices?
  428. -> SrcSpan -- for error messages
  429. -> [Module] -- If you need these
  430. -> IO ([Linkable], [PackageId]) -- ... then link these first
  431. -- Fails with an IO exception if it can't find enough files
  432. getLinkDeps hsc_env hpt pls replace_osuf span mods
  433. -- Find all the packages and linkables that a set of modules depends on
  434. = do {
  435. -- 1. Find the dependent home-pkg-modules/packages from each iface
  436. -- (omitting iINTERACTIVE, which is already linked)
  437. (mods_s, pkgs_s) <- follow_deps (filter ((/=) iNTERACTIVE) mods)
  438. emptyUniqSet emptyUniqSet;
  439. let {
  440. -- 2. Exclude ones already linked
  441. -- Main reason: avoid findModule calls in get_linkable
  442. mods_needed = mods_s `minusList` linked_mods ;
  443. pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
  444. linked_mods = map (moduleName.linkableModule)
  445. (objs_loaded pls ++ bcos_loaded pls)
  446. } ;
  447. -- 3. For each dependent module, find its linkable
  448. -- This will either be in the HPT or (in the case of one-shot
  449. -- compilation) we may need to use maybe_getFileLinkable
  450. let { osuf = objectSuf dflags } ;
  451. lnks_needed <- mapM (get_linkable osuf replace_osuf) mods_needed ;
  452. return (lnks_needed, pkgs_needed) }
  453. where
  454. dflags = hsc_dflags hsc_env
  455. this_pkg = thisPackage dflags
  456. -- The ModIface contains the transitive closure of the module dependencies
  457. -- within the current package, *except* for boot modules: if we encounter
  458. -- a boot module, we have to find its real interface and discover the
  459. -- dependencies of that. Hence we need to traverse the dependency
  460. -- tree recursively. See bug #936, testcase ghci/prog007.
  461. follow_deps :: [Module] -- modules to follow
  462. -> UniqSet ModuleName -- accum. module dependencies
  463. -> UniqSet PackageId -- accum. package dependencies
  464. -> IO ([ModuleName], [PackageId]) -- result
  465. follow_deps [] acc_mods acc_pkgs
  466. = return (uniqSetToList acc_mods, uniqSetToList acc_pkgs)
  467. follow_deps (mod:mods) acc_mods acc_pkgs
  468. = do
  469. mb_iface <- initIfaceCheck hsc_env $
  470. loadInterface msg mod (ImportByUser False)
  471. iface <- case mb_iface of
  472. Maybes.Failed err -> ghcError (ProgramError (showSDoc dflags err))
  473. Maybes.Succeeded iface -> return iface
  474. when (mi_boot iface) $ link_boot_mod_error mod
  475. let
  476. pkg = modulePackageId mod
  477. deps = mi_deps iface
  478. pkg_deps = dep_pkgs deps
  479. (boot_deps, mod_deps) = partitionWith is_boot (dep_mods deps)
  480. where is_boot (m,True) = Left m
  481. is_boot (m,False) = Right m
  482. boot_deps' = filter (not . (`elementOfUniqSet` acc_mods)) boot_deps
  483. acc_mods' = addListToUniqSet acc_mods (moduleName mod : mod_deps)
  484. acc_pkgs' = addListToUniqSet acc_pkgs $ map fst pkg_deps
  485. --
  486. if pkg /= this_pkg
  487. then follow_deps mods acc_mods (addOneToUniqSet acc_pkgs' pkg)
  488. else follow_deps (map (mkModule this_pkg) boot_deps' ++ mods)
  489. acc_mods' acc_pkgs'
  490. where
  491. msg = text "need to link module" <+> ppr mod <+>
  492. text "due to use of Template Haskell"
  493. link_boot_mod_error mod =
  494. ghcError (ProgramError (showSDoc dflags (
  495. text "module" <+> ppr mod <+>
  496. text "cannot be linked; it is only available as a boot module")))
  497. no_obj :: Outputable a => a -> IO b
  498. no_obj mod = dieWith dflags span $
  499. ptext (sLit "cannot find object file for module ") <>
  500. quotes (ppr mod) $$
  501. while_linking_expr
  502. while_linking_expr = ptext (sLit "while linking an interpreted expression")
  503. -- This one is a build-system bug
  504. get_linkable osuf replace_osuf mod_name -- A home-package module
  505. | Just mod_info <- lookupUFM hpt mod_name
  506. = adjust_linkable (Maybes.expectJust "getLinkDeps" (hm_linkable mod_info))
  507. | otherwise
  508. = do -- It's not in the HPT because we are in one shot mode,
  509. -- so use the Finder to get a ModLocation...
  510. mb_stuff <- findHomeModule hsc_env mod_name
  511. case mb_stuff of
  512. Found loc mod -> found loc mod
  513. _ -> no_obj mod_name
  514. where
  515. found loc mod = do {
  516. -- ...and then find the linkable for it
  517. mb_lnk <- findObjectLinkableMaybe mod loc ;
  518. case mb_lnk of {
  519. Nothing -> no_obj mod ;
  520. Just lnk -> adjust_linkable lnk
  521. }}
  522. adjust_linkable lnk
  523. | replace_osuf = do
  524. new_uls <- mapM adjust_ul (linkableUnlinked lnk)
  525. return lnk{ linkableUnlinked=new_uls }
  526. | otherwise =
  527. return lnk
  528. adjust_ul (DotO file) = do
  529. MASSERT (osuf `isSuffixOf` file)
  530. let file_base = reverse (drop (length osuf + 1) (reverse file))
  531. dyn_file = file_base <.> "dyn_o"
  532. new_file = file_base <.> normalObjectSuffix
  533. -- Note that even if dYNAMIC_BY_DEFAULT is on, we might
  534. -- still have dynamic object files called .o, so we need
  535. -- to try both filenames.
  536. use_dyn <- if dYNAMIC_BY_DEFAULT dflags
  537. then do doesFileExist dyn_file
  538. else return False
  539. if use_dyn
  540. then return (DotO dyn_file)
  541. else do ok <- doesFileExist new_file
  542. if (not ok)
  543. then dieWith dflags span $
  544. ptext (sLit "cannot find normal object file ")
  545. <> quotes (text new_file) $$ while_linking_expr
  546. else return (DotO new_file)
  547. adjust_ul (DotA fp) = panic ("adjust_ul DotA " ++ show fp)
  548. adjust_ul (DotDLL fp) = panic ("adjust_ul DotDLL " ++ show fp)
  549. adjust_ul l@(BCOs {}) = return l
  550. \end{code}
  551. %************************************************************************
  552. %* *
  553. Loading a Decls statement
  554. %* *
  555. %************************************************************************
  556. \begin{code}
  557. linkDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO () --[HValue]
  558. linkDecls hsc_env span (ByteCode unlinkedBCOs itblEnv) = do
  559. -- Initialise the linker (if it's not been done already)
  560. let dflags = hsc_dflags hsc_env
  561. initDynLinker dflags
  562. -- Take lock for the actual work.
  563. modifyPLS $ \pls0 -> do
  564. -- Link the packages and modules required
  565. (pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
  566. if failed ok
  567. then ghcError (ProgramError "")
  568. else do
  569. -- Link the expression itself
  570. let ie = plusNameEnv (itbl_env pls) itblEnv
  571. ce = closure_env pls
  572. -- Link the necessary packages and linkables
  573. (final_gce, _) <- linkSomeBCOs dflags False ie ce unlinkedBCOs
  574. let pls2 = pls { closure_env = final_gce,
  575. itbl_env = ie }
  576. return (pls2, ()) --hvals)
  577. where
  578. free_names = concatMap (nameSetToList . bcoFreeNames) unlinkedBCOs
  579. needed_mods :: [Module]
  580. needed_mods = [ nameModule n | n <- free_names,
  581. isExternalName n, -- Names from other modules
  582. not (isWiredInName n) -- Exclude wired-in names
  583. ] -- (see note below)
  584. -- Exclude wired-in names because we may not have read
  585. -- their interface files, so getLinkDeps will fail
  586. -- All wired-in names are in the base package, which we link
  587. -- by default, so we can safely ignore them here.
  588. \end{code}
  589. %************************************************************************
  590. %* *
  591. Loading a single module
  592. %* *
  593. %************************************************************************
  594. \begin{code}
  595. linkModule :: HscEnv -> Module -> IO ()
  596. linkModule hsc_env mod = do
  597. initDynLinker (hsc_dflags hsc_env)
  598. modifyPLS_ $ \pls -> do
  599. (pls', ok) <- linkDependencies hsc_env pls noSrcSpan [mod]
  600. if (failed ok) then ghcError (ProgramError "could not link module")
  601. else return pls'
  602. \end{code}
  603. %************************************************************************
  604. %* *
  605. Link some linkables
  606. The linkables may consist of a mixture of
  607. byte-code modules and object modules
  608. %* *
  609. %************************************************************************
  610. \begin{code}
  611. linkModules :: DynFlags -> PersistentLinkerState -> [Linkable]
  612. -> IO (PersistentLinkerState, SuccessFlag)
  613. linkModules dflags pls linkables
  614. = mask_ $ do -- don't want to be interrupted by ^C in here
  615. let (objs, bcos) = partition isObjectLinkable
  616. (concatMap partitionLinkable linkables)
  617. -- Load objects first; they can't depend on BCOs
  618. (pls1, ok_flag) <- dynLinkObjs dflags pls objs
  619. if failed ok_flag then
  620. return (pls1, Failed)
  621. else do
  622. pls2 <- dynLinkBCOs dflags pls1 bcos
  623. return (pls2, Succeeded)
  624. -- HACK to support f-x-dynamic in the interpreter; no other purpose
  625. partitionLinkable :: Linkable -> [Linkable]
  626. partitionLinkable li
  627. = let li_uls = linkableUnlinked li
  628. li_uls_obj = filter isObject li_uls
  629. li_uls_bco = filter isInterpretable li_uls
  630. in
  631. case (li_uls_obj, li_uls_bco) of
  632. (_:_, _:_) -> [li {linkableUnlinked=li_uls_obj},
  633. li {linkableUnlinked=li_uls_bco}]
  634. _ -> [li]
  635. findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
  636. findModuleLinkable_maybe lis mod
  637. = case [LM time nm us | LM time nm us <- lis, nm == mod] of
  638. [] -> Nothing
  639. [li] -> Just li
  640. _ -> pprPanic "findModuleLinkable" (ppr mod)
  641. linkableInSet :: Linkable -> [Linkable] -> Bool
  642. linkableInSet l objs_loaded =
  643. case findModuleLinkable_maybe objs_loaded (linkableModule l) of
  644. Nothing -> False
  645. Just m -> linkableTime l == linkableTime m
  646. \end{code}
  647. %************************************************************************
  648. %* *
  649. \subsection{The object-code linker}
  650. %* *
  651. %************************************************************************
  652. \begin{code}
  653. dynLinkObjs :: DynFlags -> PersistentLinkerState -> [Linkable]
  654. -> IO (PersistentLinkerState, SuccessFlag)
  655. dynLinkObjs dflags pls objs = do
  656. -- Load the object files and link them
  657. let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
  658. pls1 = pls { objs_loaded = objs_loaded' }
  659. unlinkeds = concatMap linkableUnlinked new_objs
  660. mapM_ loadObj (map nameOfObject unlinkeds)
  661. -- Link them all together
  662. ok <- resolveObjs
  663. -- If resolving failed, unload all our
  664. -- object modules and carry on
  665. if succeeded ok then do
  666. return (pls1, Succeeded)
  667. else do
  668. pls2 <- unload_wkr dflags [] pls1
  669. return (pls2, Failed)
  670. rmDupLinkables :: [Linkable] -- Already loaded
  671. -> [Linkable] -- New linkables
  672. -> ([Linkable], -- New loaded set (including new ones)
  673. [Linkable]) -- New linkables (excluding dups)
  674. rmDupLinkables already ls
  675. = go already [] ls
  676. where
  677. go already extras [] = (already, extras)
  678. go already extras (l:ls)
  679. | linkableInSet l already = go already extras ls
  680. | otherwise = go (l:already) (l:extras) ls
  681. \end{code}
  682. %************************************************************************
  683. %* *
  684. \subsection{The byte-code linker}
  685. %* *
  686. %************************************************************************
  687. \begin{code}
  688. dynLinkBCOs :: DynFlags -> PersistentLinkerState -> [Linkable]
  689. -> IO PersistentLinkerState
  690. dynLinkBCOs dflags pls bcos = do
  691. let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
  692. pls1 = pls { bcos_loaded = bcos_loaded' }
  693. unlinkeds :: [Unlinked]
  694. unlinkeds = concatMap linkableUnlinked new_bcos
  695. cbcs :: [CompiledByteCode]
  696. cbcs = map byteCodeOfObject unlinkeds
  697. ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
  698. ies = [ie | ByteCode _ ie <- cbcs]
  699. gce = closure_env pls
  700. final_ie = foldr plusNameEnv (itbl_env pls) ies
  701. (final_gce, _linked_bcos) <- linkSomeBCOs dflags True final_ie gce ul_bcos
  702. -- XXX What happens to these linked_bcos?
  703. let pls2 = pls1 { closure_env = final_gce,
  704. itbl_env = final_ie }
  705. return pls2
  706. -- Link a bunch of BCOs and return them + updated closure env.
  707. linkSomeBCOs :: DynFlags
  708. -> Bool -- False <=> add _all_ BCOs to returned closure env
  709. -- True <=> add only toplevel BCOs to closure env
  710. -> ItblEnv
  711. -> ClosureEnv
  712. -> [UnlinkedBCO]
  713. -> IO (ClosureEnv, [HValue])
  714. -- The returned HValues are associated 1-1 with
  715. -- the incoming unlinked BCOs. Each gives the
  716. -- value of the corresponding unlinked BCO
  717. linkSomeBCOs dflags toplevs_only ie ce_in ul_bcos
  718. = do let nms = map unlinkedBCOName ul_bcos
  719. hvals <- fixIO
  720. ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
  721. in mapM (linkBCO dflags ie ce_out) ul_bcos )
  722. let ce_all_additions = zip nms hvals
  723. ce_top_additions = filter (isExternalName.fst) ce_all_additions
  724. ce_additions = if toplevs_only then ce_top_additions
  725. else ce_all_additions
  726. ce_out = -- make sure we're not inserting duplicate names into the
  727. -- closure environment, which leads to trouble.
  728. ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
  729. extendClosureEnv ce_in ce_additions
  730. return (ce_out, hvals)
  731. \end{code}
  732. %************************************************************************
  733. %* *
  734. Unload some object modules
  735. %* *
  736. %************************************************************************
  737. \begin{code}
  738. -- ---------------------------------------------------------------------------
  739. -- | Unloading old objects ready for a new compilation sweep.
  740. --
  741. -- The compilation manager provides us with a list of linkables that it
  742. -- considers \"stable\", i.e. won't be recompiled this time around. For
  743. -- each of the modules current linked in memory,
  744. --
  745. -- * if the linkable is stable (and it's the same one -- the user may have
  746. -- recompiled the module on the side), we keep it,
  747. --
  748. -- * otherwise, we unload it.
  749. --
  750. -- * we also implicitly unload all temporary bindings at this point.
  751. --
  752. unload :: DynFlags
  753. -> [Linkable] -- ^ The linkables to *keep*.
  754. -> IO ()
  755. unload dflags linkables
  756. = mask_ $ do -- mask, so we're safe from Ctrl-C in here
  757. -- Initialise the linker (if it's not been done already)
  758. initDynLinker dflags
  759. new_pls
  760. <- modifyPLS $ \pls -> do
  761. pls1 <- unload_wkr dflags linkables pls
  762. return (pls1, pls1)
  763. debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
  764. debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
  765. return ()
  766. unload_wkr :: DynFlags
  767. -> [Linkable] -- stable linkables
  768. -> PersistentLinkerState
  769. -> IO PersistentLinkerState
  770. -- Does the core unload business
  771. -- (the wrapper blocks exceptions and deals with the PLS get and put)
  772. unload_wkr _ linkables pls
  773. = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
  774. objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
  775. bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
  776. let bcos_retained = map linkableModule bcos_loaded'
  777. itbl_env' = filterNameMap bcos_retained (itbl_env pls)
  778. closure_env' = filterNameMap bcos_retained (closure_env pls)
  779. new_pls = pls { itbl_env = itbl_env',
  780. closure_env = closure_env',
  781. bcos_loaded = bcos_loaded',
  782. objs_loaded = objs_loaded' }
  783. return new_pls
  784. where
  785. maybeUnload :: [Linkable] -> Linkable -> IO Bool
  786. maybeUnload keep_linkables lnk
  787. | linkableInSet lnk keep_linkables = return True
  788. | otherwise
  789. = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
  790. -- The components of a BCO linkable may contain
  791. -- dot-o files. Which is very confusing.
  792. --
  793. -- But the BCO parts can be unlinked just by
  794. -- letting go of them (plus of course depopulating
  795. -- the symbol table which is done in the main body)
  796. return False
  797. \end{code}
  798. %************************************************************************
  799. %* *
  800. Loading packages
  801. %* *
  802. %************************************************************************
  803. \begin{code}
  804. data LibrarySpec
  805. = Object FilePath -- Full path name of a .o file, including trailing .o
  806. -- For dynamic objects only, try to find the object
  807. -- file in all the directories specified in
  808. -- v_Library_paths before giving up.
  809. | Archive FilePath -- Full path name of a .a file, including trailing .a
  810. | DLL String -- "Unadorned" name of a .DLL/.so
  811. -- e.g. On unix "qt" denotes "libqt.so"
  812. -- On WinDoze "burble" denotes "burble.DLL"
  813. -- loadDLL is platform-specific and adds the lib/.so/.DLL
  814. -- suffixes platform-dependently
  815. | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
  816. -- (ends with .dll or .so).
  817. | Framework String -- Only used for darwin, but does no harm
  818. -- If this package is already part of the GHCi binary, we'll already
  819. -- have the right DLLs for this package loaded, so don't try to
  820. -- load them again.
  821. --
  822. -- But on Win32 we must load them 'again'; doing so is a harmless no-op
  823. -- as far as the loader is concerned, but it does initialise the list
  824. -- of DLL handles that rts/Linker.c maintains, and that in turn is
  825. -- used by lookupSymbol. So we must call addDLL for each library
  826. -- just to get the DLL handle into the list.
  827. partOfGHCi :: [PackageName]
  828. partOfGHCi
  829. | isWindowsHost || isDarwinHost = []
  830. | otherwise = map PackageName
  831. ["base", "template-haskell", "editline"]
  832. showLS :: LibrarySpec -> String
  833. showLS (Object nm) = "(static) " ++ nm
  834. showLS (Archive nm) = "(static archive) " ++ nm
  835. showLS (DLL nm) = "(dynamic) " ++ nm
  836. showLS (DLLPath nm) = "(dynamic) " ++ nm
  837. showLS (Framework nm) = "(framework) " ++ nm
  838. -- | Link exactly the specified packages, and their dependents (unless of
  839. -- course they are already linked). The dependents are linked
  840. -- automatically, and it doesn't matter what order you specify the input
  841. -- packages.
  842. --
  843. linkPackages :: DynFlags -> [PackageId] -> IO ()
  844. -- NOTE: in fact, since each module tracks all the packages it depends on,
  845. -- we don't really need to use the package-config dependencies.
  846. --
  847. -- However we do need the package-config stuff (to find aux libs etc),
  848. -- and following them lets us load libraries in the right order, which
  849. -- perhaps makes the error message a bit more localised if we get a link
  850. -- failure. So the dependency walking code is still here.
  851. linkPackages dflags new_pkgs = do
  852. -- It's probably not safe to try to load packages concurrently, so we take
  853. -- a lock.
  854. initDynLinker dflags
  855. modifyPLS_ $ \pls -> do
  856. linkPackages' dflags new_pkgs pls
  857. linkPackages' :: DynFlags -> [PackageId] -> PersistentLinkerState
  858. -> IO PersistentLinkerState
  859. linkPackages' dflags new_pks pls = do
  860. pkgs' <- link (pkgs_loaded pls) new_pks
  861. return $! pls { pkgs_loaded = pkgs' }
  862. where
  863. pkg_map = pkgIdMap (pkgState dflags)
  864. ipid_map = installedPackageIdMap (pkgState dflags)
  865. link :: [PackageId] -> [PackageId] -> IO [PackageId]
  866. link pkgs new_pkgs =
  867. foldM link_one pkgs new_pkgs
  868. link_one pkgs new_pkg
  869. | new_pkg `elem` pkgs -- Already linked
  870. = return pkgs
  871. | Just pkg_cfg <- lookupPackage pkg_map new_pkg
  872. = do { -- Link dependents first
  873. pkgs' <- link pkgs [ Maybes.expectJust "link_one" $
  874. Map.lookup ipid ipid_map
  875. | ipid <- depends pkg_cfg ]
  876. -- Now link the package itself
  877. ; linkPackage dflags pkg_cfg
  878. ; return (new_pkg : pkgs') }
  879. | otherwise
  880. = ghcError (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
  881. linkPackage :: DynFlags -> PackageConfig -> IO ()
  882. linkPackage dflags pkg
  883. = do
  884. let platform = targetPlatform dflags
  885. dirs = Packages.libraryDirs pkg
  886. let hs_libs = Packages.hsLibraries pkg
  887. -- The FFI GHCi import lib isn't needed as
  888. -- compiler/ghci/Linker.lhs + rts/Linker.c link the
  889. -- interpreted references to FFI to the compiled FFI.
  890. -- We therefore filter it out so that we don't get
  891. -- duplicate symbol errors.
  892. hs_libs' = filter ("HSffi" /=) hs_libs
  893. -- Because of slight differences between the GHC dynamic linker and
  894. -- the native system linker some packages have to link with a
  895. -- different list of libraries when using GHCi. Examples include: libs
  896. -- that are actually gnu ld scripts, and the possability that the .a
  897. -- libs do not exactly match the .so/.dll equivalents. So if the
  898. -- package file provides an "extra-ghci-libraries" field then we use
  899. -- that instead of the "extra-libraries" field.
  900. extra_libs =
  901. (if null (Packages.extraGHCiLibraries pkg)
  902. then Packages.extraLibraries pkg
  903. else Packages.extraGHCiLibraries pkg)
  904. ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
  905. hs_classifieds <- mapM (locateLib dflags True dirs) hs_libs'
  906. extra_classifieds <- mapM (locateLib dflags False dirs) extra_libs
  907. let classifieds = hs_classifieds ++ extra_classifieds
  908. -- Complication: all the .so's must be loaded before any of the .o's.
  909. let known_dlls = [ dll | DLLPath dll <- classifieds ]
  910. dlls = [ dll | DLL dll <- classifieds ]
  911. objs = [ obj | Object obj <- classifieds ]
  912. archs = [ arch | Archive arch <- classifieds ]
  913. maybePutStr dflags ("Loading package " ++ display (sourcePackageId pkg) ++ " ... ")
  914. -- See comments with partOfGHCi
  915. when (packageName pkg `notElem` partOfGHCi) $ do
  916. loadFrameworks platform pkg
  917. mapM_ load_dyn (known_dlls ++ map (mkSOName platform) dlls)
  918. -- After loading all the DLLs, we can load the static objects.
  919. -- Ordering isn't important here, because we do one final link
  920. -- step to resolve everything.
  921. mapM_ loadObj objs
  922. mapM_ loadArchive archs
  923. maybePutStr dflags "linking ... "
  924. ok <- resolveObjs
  925. if succeeded ok then maybePutStrLn dflags "done."
  926. else ghcError (InstallationError ("unable to load package `" ++ display (sourcePackageId pkg) ++ "'"))
  927. -- we have already searched the filesystem; the strings passed to load_dyn
  928. -- can be passed directly to loadDLL. They are either fully-qualified
  929. -- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so"). In the latter case,
  930. -- loadDLL is going to search the system paths to find the library.
  931. --
  932. load_dyn :: FilePath -> IO ()
  933. load_dyn dll = do r <- loadDLL dll
  934. case r of
  935. Nothing -> return ()
  936. Just err -> ghcError (CmdLineError ("can't load .so/.DLL for: "
  937. ++ dll ++ " (" ++ err ++ ")" ))
  938. loadFrameworks :: Platform -> InstalledPackageInfo_ ModuleName -> IO ()
  939. loadFrameworks platform pkg
  940. = case platformOS platform of
  941. OSDarwin -> mapM_ load frameworks
  942. _ -> return ()
  943. where
  944. fw_dirs = Packages.frameworkDirs pkg
  945. frameworks = Packages.frameworks pkg
  946. load fw = do r <- loadFramework fw_dirs fw
  947. case r of
  948. Nothing -> return ()
  949. Just err -> ghcError (CmdLineError ("can't load framework: "
  950. ++ fw ++ " (" ++ err ++ ")" ))
  951. -- Try to find an object file for a given library in the given paths.
  952. -- If it isn't present, we assume that addDLL in the RTS can find it,
  953. -- which generally means that it should be a dynamic library in the
  954. -- standard system search path.
  955. locateLib :: DynFlags -> Bool -> [FilePath] -> String -> IO LibrarySpec
  956. locateLib dflags is_hs dirs lib
  957. | not is_hs
  958. -- For non-Haskell libraries (e.g. gmp, iconv):
  959. -- first look in library-dirs for a dynamic library (libfoo.so)
  960. -- then look in library-dirs for a static library (libfoo.a)
  961. -- then try "gcc --print-file-name" to search gcc's search path
  962. -- for a dynamic library (#5289)
  963. -- otherwise, assume loadDLL can find it
  964. --
  965. = findDll `orElse` findArchive `orElse` tryGcc `orElse` assumeDll
  966. | not isDynamicGhcLib
  967. -- When the GHC package was not compiled as dynamic library
  968. -- (=DYNAMIC not set), we search for .o libraries or, if they
  969. -- don't exist, .a libraries.
  970. = findObject `orElse` findArchive `orElse` assumeDll
  971. | otherwise
  972. -- When the GHC package was compiled as dynamic library (=DYNAMIC set),
  973. -- we search for .so libraries first.
  974. = findHSDll `orElse` findDynObject `orElse` findDynArchive `orElse`
  975. findObject `orElse` findArchive `orElse` assumeDll
  976. where
  977. mk_obj_path dir = dir </> (lib <.> "o")
  978. mk_dyn_obj_path dir = dir </> (lib <.> "dyn_o")
  979. mk_arch_path dir = dir </> ("lib" ++ lib <.> "a")
  980. mk_dyn_arch_path dir = dir </> ("lib" ++ lib <.> "dyn_a")
  981. hs_dyn_lib_name = lib ++ "-ghc" ++ cProjectVersion
  982. mk_hs_dyn_lib_path dir = dir </> mkSOName platform hs_dyn_lib_name
  983. so_name = mkSOName platform lib
  984. mk_dyn_lib_path dir = dir </> so_name
  985. findObject = liftM (fmap Object) $ findFile mk_obj_path dirs
  986. findDynObject = do putStrLn "In findDynObject"
  987. liftM (fmap Object) $ findFile mk_dyn_obj_path dirs
  988. findArchive = liftM (fmap Archive) $ findFile mk_arch_path dirs
  989. findDynArchive = liftM (fmap Archive) $ findFile mk_dyn_arch_path dirs
  990. findHSDll = liftM (fmap DLLPath) $ findFile mk_hs_dyn_lib_path dirs
  991. findDll = liftM (fmap DLLPath) $ findFile mk_dyn_lib_path dirs
  992. tryGcc = liftM (fmap DLLPath) $ searchForLibUsingGcc dflags so_name dirs
  993. assumeDll = return (DLL lib)
  994. infixr `orElse`
  995. f `orElse` g = do m <- f
  996. case m of
  997. Just x -> return x
  998. Nothing -> g
  999. platform = targetPlatform dflags
  1000. searchForLibUsingGcc :: DynFlags -> String -> [FilePath] -> IO (Maybe FilePath)
  1001. searchForLibUsingGcc dflags so dirs = do
  1002. str <- askCc dflags (map (FileOption "-L") dirs
  1003. ++ [Option "--print-file-name", Option so])
  1004. let file = case lines str of
  1005. [] -> ""
  1006. l:_ -> l
  1007. if (file == so)
  1008. then return Nothing
  1009. else return (Just file)
  1010. -- ----------------------------------------------------------------------------
  1011. -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
  1012. -- Darwin / MacOS X only: load a framework
  1013. -- a framework is a dynamic library packaged inside a directory of the same
  1014. -- name. They are searched for in different paths than normal libraries.
  1015. loadFramework :: [FilePath] -> FilePath -> IO (Maybe String)
  1016. loadFramework extraPaths rootname
  1017. = do { either_dir <- tryIO getHomeDirectory
  1018. ; let homeFrameworkPath = case either_dir of
  1019. Left _ -> []
  1020. Right dir -> [dir ++ "/Library/Frameworks"]
  1021. ps = extraPaths ++ homeFrameworkPath ++ defaultFrameworkPaths
  1022. ; mb_fwk <- findFile mk_fwk ps
  1023. ; case mb_fwk of
  1024. Just fwk_path -> loadDLL fwk_path
  1025. Nothing -> return (Just "not found") }
  1026. --

Large files files are truncated, but you can click here to view the full file