PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/ghci/Linker.lhs

https://github.com/luite/ghc
Haskell | 1297 lines | 828 code | 197 blank | 272 comment | 73 complexity | 8e06bb78076c6e3830054be7ec4ad565 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-2012
  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 throwGhcExceptionIO (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 = if platformUsesFrameworks platform
  256. then frameworkPaths dflags
  257. else []
  258. ; let frameworks = if platformUsesFrameworks platform
  259. then cmdlineFrameworks dflags
  260. else []
  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 throwGhcExceptionIO (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. if platformUsesFrameworks (targetPlatform dflags)
  326. then do maybe_errstr <- loadFramework framework_paths framework
  327. case maybe_errstr of
  328. Nothing -> maybePutStrLn dflags "done"
  329. Just mm -> preloadFailed mm framework_paths lib_spec
  330. else panic "preloadLib Framework"
  331. where
  332. platform = targetPlatform dflags
  333. preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
  334. preloadFailed sys_errmsg paths spec
  335. = do maybePutStr dflags "failed.\n"
  336. throwGhcExceptionIO $
  337. CmdLineError (
  338. "user specified .o/.so/.DLL could not be loaded ("
  339. ++ sys_errmsg ++ ")\nWhilst trying to load: "
  340. ++ showLS spec ++ "\nAdditional directories searched:"
  341. ++ (if null paths then " (none)" else
  342. (concat (intersperse "\n" (map (" "++) paths)))))
  343. -- Not interested in the paths in the static case.
  344. preload_static _paths name
  345. = do b <- doesFileExist name
  346. if not b then return False
  347. else do if cDYNAMIC_GHC_PROGRAMS
  348. then dynLoadObjs dflags [name]
  349. else loadObj name
  350. return True
  351. preload_static_archive _paths name
  352. = do b <- doesFileExist name
  353. if not b then return False
  354. else do if cDYNAMIC_GHC_PROGRAMS
  355. then panic "Loading archives not supported"
  356. else loadArchive name
  357. return True
  358. \end{code}
  359. %************************************************************************
  360. %* *
  361. Link a byte-code expression
  362. %* *
  363. %************************************************************************
  364. \begin{code}
  365. -- | Link a single expression, /including/ first linking packages and
  366. -- modules that this expression depends on.
  367. --
  368. -- Raises an IO exception ('ProgramError') if it can't find a compiled
  369. -- version of the dependents to link.
  370. --
  371. linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO HValue
  372. linkExpr hsc_env span root_ul_bco
  373. = do {
  374. -- Initialise the linker (if it's not been done already)
  375. let dflags = hsc_dflags hsc_env
  376. ; initDynLinker dflags
  377. -- Take lock for the actual work.
  378. ; modifyPLS $ \pls0 -> do {
  379. -- Link the packages and modules required
  380. ; (pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
  381. ; if failed ok then
  382. throwGhcExceptionIO (ProgramError "")
  383. else do {
  384. -- Link the expression itself
  385. let ie = itbl_env pls
  386. ce = closure_env pls
  387. -- Link the necessary packages and linkables
  388. ; (_, (root_hval:_)) <- linkSomeBCOs dflags False ie ce [root_ul_bco]
  389. ; return (pls, root_hval)
  390. }}}
  391. where
  392. free_names = nameSetToList (bcoFreeNames root_ul_bco)
  393. needed_mods :: [Module]
  394. needed_mods = [ nameModule n | n <- free_names,
  395. isExternalName n, -- Names from other modules
  396. not (isWiredInName n) -- Exclude wired-in names
  397. ] -- (see note below)
  398. -- Exclude wired-in names because we may not have read
  399. -- their interface files, so getLinkDeps will fail
  400. -- All wired-in names are in the base package, which we link
  401. -- by default, so we can safely ignore them here.
  402. dieWith :: DynFlags -> SrcSpan -> MsgDoc -> IO a
  403. dieWith dflags span msg = throwGhcExceptionIO (ProgramError (showSDoc dflags (mkLocMessage SevFatal span msg)))
  404. checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
  405. checkNonStdWay dflags srcspan =
  406. if interpWays == haskellWays
  407. then return Nothing
  408. -- see #3604: object files compiled for way "dyn" need to link to the
  409. -- dynamic packages, so we can't load them into a statically-linked GHCi.
  410. -- we have to treat "dyn" in the same way as "prof".
  411. --
  412. -- In the future when GHCi is dynamically linked we should be able to relax
  413. -- this, but they we may have to make it possible to load either ordinary
  414. -- .o files or -dynamic .o files into GHCi (currently that's not possible
  415. -- because the dynamic objects contain refs to e.g. __stginit_base_Prelude_dyn
  416. -- whereas we have __stginit_base_Prelude_.
  417. else if objectSuf dflags == normalObjectSuffix && not (null haskellWays)
  418. then failNonStd dflags srcspan
  419. else return $ Just $ if cDYNAMIC_GHC_PROGRAMS
  420. then "dyn_o"
  421. else "o"
  422. where haskellWays = filter (not . wayRTSOnly) (ways dflags)
  423. normalObjectSuffix :: String
  424. normalObjectSuffix = phaseInputExt StopLn
  425. failNonStd :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
  426. failNonStd dflags srcspan = dieWith dflags srcspan $
  427. ptext (sLit "Dynamic linking required, but this is a non-standard build (eg. prof).") $$
  428. ptext (sLit "You need to build the program twice: once the") <+> ghciWay <+> ptext (sLit "way, and then") $$
  429. ptext (sLit "in the desired way using -osuf to set the object file suffix.")
  430. where ghciWay = if cDYNAMIC_GHC_PROGRAMS
  431. then ptext (sLit "dynamic")
  432. else ptext (sLit "normal")
  433. getLinkDeps :: HscEnv -> HomePackageTable
  434. -> PersistentLinkerState
  435. -> Maybe FilePath -- replace object suffices?
  436. -> SrcSpan -- for error messages
  437. -> [Module] -- If you need these
  438. -> IO ([Linkable], [PackageId]) -- ... then link these first
  439. -- Fails with an IO exception if it can't find enough files
  440. getLinkDeps hsc_env hpt pls replace_osuf span mods
  441. -- Find all the packages and linkables that a set of modules depends on
  442. = do {
  443. -- 1. Find the dependent home-pkg-modules/packages from each iface
  444. -- (omitting iINTERACTIVE, which is already linked)
  445. (mods_s, pkgs_s) <- follow_deps (filter ((/=) iNTERACTIVE) mods)
  446. emptyUniqSet emptyUniqSet;
  447. let {
  448. -- 2. Exclude ones already linked
  449. -- Main reason: avoid findModule calls in get_linkable
  450. mods_needed = mods_s `minusList` linked_mods ;
  451. pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
  452. linked_mods = map (moduleName.linkableModule)
  453. (objs_loaded pls ++ bcos_loaded pls)
  454. } ;
  455. -- 3. For each dependent module, find its linkable
  456. -- This will either be in the HPT or (in the case of one-shot
  457. -- compilation) we may need to use maybe_getFileLinkable
  458. let { osuf = objectSuf dflags } ;
  459. lnks_needed <- mapM (get_linkable osuf) mods_needed ;
  460. return (lnks_needed, pkgs_needed) }
  461. where
  462. dflags = hsc_dflags hsc_env
  463. this_pkg = thisPackage dflags
  464. -- The ModIface contains the transitive closure of the module dependencies
  465. -- within the current package, *except* for boot modules: if we encounter
  466. -- a boot module, we have to find its real interface and discover the
  467. -- dependencies of that. Hence we need to traverse the dependency
  468. -- tree recursively. See bug #936, testcase ghci/prog007.
  469. follow_deps :: [Module] -- modules to follow
  470. -> UniqSet ModuleName -- accum. module dependencies
  471. -> UniqSet PackageId -- accum. package dependencies
  472. -> IO ([ModuleName], [PackageId]) -- result
  473. follow_deps [] acc_mods acc_pkgs
  474. = return (uniqSetToList acc_mods, uniqSetToList acc_pkgs)
  475. follow_deps (mod:mods) acc_mods acc_pkgs
  476. = do
  477. mb_iface <- initIfaceCheck hsc_env $
  478. loadInterface msg mod (ImportByUser False)
  479. iface <- case mb_iface of
  480. Maybes.Failed err -> throwGhcExceptionIO (ProgramError (showSDoc dflags err))
  481. Maybes.Succeeded iface -> return iface
  482. when (mi_boot iface) $ link_boot_mod_error mod
  483. let
  484. pkg = modulePackageId mod
  485. deps = mi_deps iface
  486. pkg_deps = dep_pkgs deps
  487. (boot_deps, mod_deps) = partitionWith is_boot (dep_mods deps)
  488. where is_boot (m,True) = Left m
  489. is_boot (m,False) = Right m
  490. boot_deps' = filter (not . (`elementOfUniqSet` acc_mods)) boot_deps
  491. acc_mods' = addListToUniqSet acc_mods (moduleName mod : mod_deps)
  492. acc_pkgs' = addListToUniqSet acc_pkgs $ map fst pkg_deps
  493. --
  494. if pkg /= this_pkg
  495. then follow_deps mods acc_mods (addOneToUniqSet acc_pkgs' pkg)
  496. else follow_deps (map (mkModule this_pkg) boot_deps' ++ mods)
  497. acc_mods' acc_pkgs'
  498. where
  499. msg = text "need to link module" <+> ppr mod <+>
  500. text "due to use of Template Haskell"
  501. link_boot_mod_error mod =
  502. throwGhcExceptionIO (ProgramError (showSDoc dflags (
  503. text "module" <+> ppr mod <+>
  504. text "cannot be linked; it is only available as a boot module")))
  505. no_obj :: Outputable a => a -> IO b
  506. no_obj mod = dieWith dflags span $
  507. ptext (sLit "cannot find object file for module ") <>
  508. quotes (ppr mod) $$
  509. while_linking_expr
  510. while_linking_expr = ptext (sLit "while linking an interpreted expression")
  511. -- This one is a build-system bug
  512. get_linkable osuf mod_name -- A home-package module
  513. | Just mod_info <- lookupUFM hpt mod_name
  514. = adjust_linkable (Maybes.expectJust "getLinkDeps" (hm_linkable mod_info))
  515. | otherwise
  516. = do -- It's not in the HPT because we are in one shot mode,
  517. -- so use the Finder to get a ModLocation...
  518. mb_stuff <- findHomeModule hsc_env mod_name
  519. case mb_stuff of
  520. Found loc mod -> found loc mod
  521. _ -> no_obj mod_name
  522. where
  523. found loc mod = do {
  524. -- ...and then find the linkable for it
  525. mb_lnk <- findObjectLinkableMaybe mod loc ;
  526. case mb_lnk of {
  527. Nothing -> no_obj mod ;
  528. Just lnk -> adjust_linkable lnk
  529. }}
  530. adjust_linkable lnk
  531. | Just new_osuf <- replace_osuf = do
  532. new_uls <- mapM (adjust_ul new_osuf)
  533. (linkableUnlinked lnk)
  534. return lnk{ linkableUnlinked=new_uls }
  535. | otherwise =
  536. return lnk
  537. adjust_ul new_osuf (DotO file) = do
  538. MASSERT (osuf `isSuffixOf` file)
  539. let file_base = reverse (drop (length osuf + 1) (reverse file))
  540. new_file = file_base <.> new_osuf
  541. 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 throwGhcExceptionIO (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 throwGhcExceptionIO (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. wanted_objs = map nameOfObject unlinkeds
  661. if cDYNAMIC_GHC_PROGRAMS
  662. then do dynLoadObjs dflags wanted_objs
  663. return (pls, Succeeded)
  664. else do mapM_ loadObj wanted_objs
  665. -- Link them all together
  666. ok <- resolveObjs
  667. -- If resolving failed, unload all our
  668. -- object modules and carry on
  669. if succeeded ok then do
  670. return (pls1, Succeeded)
  671. else do
  672. pls2 <- unload_wkr dflags [] pls1
  673. return (pls2, Failed)
  674. dynLoadObjs :: DynFlags -> [FilePath] -> IO ()
  675. dynLoadObjs dflags objs = do
  676. let platform = targetPlatform dflags
  677. soFile <- newTempName dflags (soExt platform)
  678. let -- When running TH for a non-dynamic way, we still need to make
  679. -- -l flags to link against the dynamic libraries, so we turn
  680. -- Opt_Static off
  681. dflags1 = gopt_unset dflags Opt_Static
  682. dflags2 = dflags1 {
  683. -- We don't want to link the ldInputs in; we'll
  684. -- be calling dynLoadObjs with any objects that
  685. -- need to be linked.
  686. ldInputs = [],
  687. -- Even if we're e.g. profiling, we still want
  688. -- the vanilla dynamic libraries, so we set the
  689. -- ways / build tag to be just WayDyn.
  690. ways = [WayDyn],
  691. buildTag = mkBuildTag [WayDyn],
  692. outputFile = Just soFile
  693. }
  694. linkDynLib dflags2 objs []
  695. consIORef (filesToNotIntermediateClean dflags) soFile
  696. m <- loadDLL soFile
  697. case m of
  698. Nothing -> return ()
  699. Just err -> panic ("Loading temp shared object failed: " ++ err)
  700. rmDupLinkables :: [Linkable] -- Already loaded
  701. -> [Linkable] -- New linkables
  702. -> ([Linkable], -- New loaded set (including new ones)
  703. [Linkable]) -- New linkables (excluding dups)
  704. rmDupLinkables already ls
  705. = go already [] ls
  706. where
  707. go already extras [] = (already, extras)
  708. go already extras (l:ls)
  709. | linkableInSet l already = go already extras ls
  710. | otherwise = go (l:already) (l:extras) ls
  711. \end{code}
  712. %************************************************************************
  713. %* *
  714. \subsection{The byte-code linker}
  715. %* *
  716. %************************************************************************
  717. \begin{code}
  718. dynLinkBCOs :: DynFlags -> PersistentLinkerState -> [Linkable]
  719. -> IO PersistentLinkerState
  720. dynLinkBCOs dflags pls bcos = do
  721. let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
  722. pls1 = pls { bcos_loaded = bcos_loaded' }
  723. unlinkeds :: [Unlinked]
  724. unlinkeds = concatMap linkableUnlinked new_bcos
  725. cbcs :: [CompiledByteCode]
  726. cbcs = map byteCodeOfObject unlinkeds
  727. ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
  728. ies = [ie | ByteCode _ ie <- cbcs]
  729. gce = closure_env pls
  730. final_ie = foldr plusNameEnv (itbl_env pls) ies
  731. (final_gce, _linked_bcos) <- linkSomeBCOs dflags True final_ie gce ul_bcos
  732. -- XXX What happens to these linked_bcos?
  733. let pls2 = pls1 { closure_env = final_gce,
  734. itbl_env = final_ie }
  735. return pls2
  736. -- Link a bunch of BCOs and return them + updated closure env.
  737. linkSomeBCOs :: DynFlags
  738. -> Bool -- False <=> add _all_ BCOs to returned closure env
  739. -- True <=> add only toplevel BCOs to closure env
  740. -> ItblEnv
  741. -> ClosureEnv
  742. -> [UnlinkedBCO]
  743. -> IO (ClosureEnv, [HValue])
  744. -- The returned HValues are associated 1-1 with
  745. -- the incoming unlinked BCOs. Each gives the
  746. -- value of the corresponding unlinked BCO
  747. linkSomeBCOs dflags toplevs_only ie ce_in ul_bcos
  748. = do let nms = map unlinkedBCOName ul_bcos
  749. hvals <- fixIO
  750. ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
  751. in mapM (linkBCO dflags ie ce_out) ul_bcos )
  752. let ce_all_additions = zip nms hvals
  753. ce_top_additions = filter (isExternalName.fst) ce_all_additions
  754. ce_additions = if toplevs_only then ce_top_additions
  755. else ce_all_additions
  756. ce_out = -- make sure we're not inserting duplicate names into the
  757. -- closure environment, which leads to trouble.
  758. ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
  759. extendClosureEnv ce_in ce_additions
  760. return (ce_out, hvals)
  761. \end{code}
  762. %************************************************************************
  763. %* *
  764. Unload some object modules
  765. %* *
  766. %************************************************************************
  767. \begin{code}
  768. -- ---------------------------------------------------------------------------
  769. -- | Unloading old objects ready for a new compilation sweep.
  770. --
  771. -- The compilation manager provides us with a list of linkables that it
  772. -- considers \"stable\", i.e. won't be recompiled this time around. For
  773. -- each of the modules current linked in memory,
  774. --
  775. -- * if the linkable is stable (and it's the same one -- the user may have
  776. -- recompiled the module on the side), we keep it,
  777. --
  778. -- * otherwise, we unload it.
  779. --
  780. -- * we also implicitly unload all temporary bindings at this point.
  781. --
  782. unload :: DynFlags
  783. -> [Linkable] -- ^ The linkables to *keep*.
  784. -> IO ()
  785. unload dflags linkables
  786. = mask_ $ do -- mask, so we're safe from Ctrl-C in here
  787. -- Initialise the linker (if it's not been done already)
  788. initDynLinker dflags
  789. new_pls
  790. <- modifyPLS $ \pls -> do
  791. pls1 <- unload_wkr dflags linkables pls
  792. return (pls1, pls1)
  793. debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
  794. debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
  795. return ()
  796. unload_wkr :: DynFlags
  797. -> [Linkable] -- stable linkables
  798. -> PersistentLinkerState
  799. -> IO PersistentLinkerState
  800. -- Does the core unload business
  801. -- (the wrapper blocks exceptions and deals with the PLS get and put)
  802. unload_wkr _ linkables pls
  803. = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
  804. objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
  805. bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
  806. let bcos_retained = map linkableModule bcos_loaded'
  807. itbl_env' = filterNameMap bcos_retained (itbl_env pls)
  808. closure_env' = filterNameMap bcos_retained (closure_env pls)
  809. new_pls = pls { itbl_env = itbl_env',
  810. closure_env = closure_env',
  811. bcos_loaded = bcos_loaded',
  812. objs_loaded = objs_loaded' }
  813. return new_pls
  814. where
  815. maybeUnload :: [Linkable] -> Linkable -> IO Bool
  816. maybeUnload keep_linkables lnk
  817. | linkableInSet lnk keep_linkables = return True
  818. | otherwise
  819. = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
  820. -- The components of a BCO linkable may contain
  821. -- dot-o files. Which is very confusing.
  822. --
  823. -- But the BCO parts can be unlinked just by
  824. -- letting go of them (plus of course depopulating
  825. -- the symbol table which is done in the main body)
  826. return False
  827. \end{code}
  828. %************************************************************************
  829. %* *
  830. Loading packages
  831. %* *
  832. %************************************************************************
  833. \begin{code}
  834. data LibrarySpec
  835. = Object FilePath -- Full path name of a .o file, including trailing .o
  836. -- For dynamic objects only, try to find the object
  837. -- file in all the directories specified in
  838. -- v_Library_paths before giving up.
  839. | Archive FilePath -- Full path name of a .a file, including trailing .a
  840. | DLL String -- "Unadorned" name of a .DLL/.so
  841. -- e.g. On unix "qt" denotes "libqt.so"
  842. -- On WinDoze "burble" denotes "burble.DLL"
  843. -- loadDLL is platform-specific and adds the lib/.so/.DLL
  844. -- suffixes platform-dependently
  845. | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
  846. -- (ends with .dll or .so).
  847. | Framework String -- Only used for darwin, but does no harm
  848. -- If this package is already part of the GHCi binary, we'll already
  849. -- have the right DLLs for this package loaded, so don't try to
  850. -- load them again.
  851. --
  852. -- But on Win32 we must load them 'again'; doing so is a harmless no-op
  853. -- as far as the loader is concerned, but it does initialise the list
  854. -- of DLL handles that rts/Linker.c maintains, and that in turn is
  855. -- used by lookupSymbol. So we must call addDLL for each library
  856. -- just to get the DLL handle into the list.
  857. partOfGHCi :: [PackageName]
  858. partOfGHCi
  859. | isWindowsHost || isDarwinHost = []
  860. | otherwise = map PackageName
  861. ["base", "template-haskell", "editline"]
  862. showLS :: LibrarySpec -> String
  863. showLS (Object nm) = "(static) " ++ nm
  864. showLS (Archive nm) = "(static archive) " ++ nm
  865. showLS (DLL nm) = "(dynamic) " ++ nm
  866. showLS (DLLPath nm) = "(dynamic) " ++ nm
  867. showLS (Framework nm) = "(framework) " ++ nm
  868. -- | Link exactly the specified packages, and their dependents (unless of
  869. -- course they are already linked). The dependents are linked
  870. -- automatically, and it doesn't matter what order you specify the input
  871. -- packages.
  872. --
  873. linkPackages :: DynFlags -> [PackageId] -> IO ()
  874. -- NOTE: in fact, since each module tracks all the packages it depends on,
  875. -- we don't really need to use the package-config dependencies.
  876. --
  877. -- However we do need the package-config stuff (to find aux libs etc),
  878. -- and following them lets us load libraries in the right order, which
  879. -- perhaps makes the error message a bit more localised if we get a link
  880. -- failure. So the dependency walking code is still here.
  881. linkPackages dflags new_pkgs = do
  882. -- It's probably not safe to try to load packages concurrently, so we take
  883. -- a lock.
  884. initDynLinker dflags
  885. modifyPLS_ $ \pls -> do
  886. linkPackages' dflags new_pkgs pls
  887. linkPackages' :: DynFlags -> [PackageId] -> PersistentLinkerState
  888. -> IO PersistentLinkerState
  889. linkPackages' dflags new_pks pls = do
  890. pkgs' <- link (pkgs_loaded pls) new_pks
  891. return $! pls { pkgs_loaded = pkgs' }
  892. where
  893. pkg_map = pkgIdMap (pkgState dflags)
  894. ipid_map = installedPackageIdMap (pkgState dflags)
  895. link :: [PackageId] -> [PackageId] -> IO [PackageId]
  896. link pkgs new_pkgs =
  897. foldM link_one pkgs new_pkgs
  898. link_one pkgs new_pkg
  899. | new_pkg `elem` pkgs -- Already linked
  900. = return pkgs
  901. | Just pkg_cfg <- lookupPackage pkg_map new_pkg
  902. = do { -- Link dependents first
  903. pkgs' <- link pkgs [ Maybes.expectJust "link_one" $
  904. Map.lookup ipid ipid_map
  905. | ipid <- depends pkg_cfg ]
  906. -- Now link the package itself
  907. ; linkPackage dflags pkg_cfg
  908. ; return (new_pkg : pkgs') }
  909. | otherwise
  910. = throwGhcExceptionIO (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
  911. linkPackage :: DynFlags -> PackageConfig -> IO ()
  912. linkPackage dflags pkg
  913. = do
  914. let platform = targetPlatform dflags
  915. dirs = Packages.libraryDirs pkg
  916. let hs_libs = Packages.hsLibraries pkg
  917. -- The FFI GHCi import lib isn't needed as
  918. -- compiler/ghci/Linker.lhs + rts/Linker.c link the
  919. -- interpreted references to FFI to the compiled FFI.
  920. -- We therefore filter it out so that we don't get
  921. -- duplicate symbol errors.
  922. hs_libs' = filter ("HSffi" /=) hs_libs
  923. -- Because of slight differences between the GHC dynamic linker and
  924. -- the native system linker some packages have to link with a
  925. -- different list of libraries when using GHCi. Examples include: libs
  926. -- that are actually gnu ld scripts, and the possability that the .a
  927. -- libs do not exactly match the .so/.dll equivalents. So if the
  928. -- package file provides an "extra-ghci-libraries" field then we use
  929. -- that instead of the "extra-libraries" field.
  930. extra_libs =
  931. (if null (Packages.extraGHCiLibraries pkg)
  932. then Packages.extraLibraries pkg
  933. else Packages.extraGHCiLibraries pkg)
  934. ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
  935. hs_classifieds <- mapM (locateLib dflags True dirs) hs_libs'
  936. extra_classifieds <- mapM (locateLib dflags False dirs) extra_libs
  937. let classifieds = hs_classifieds ++ extra_classifieds
  938. -- Complication: all the .so's must be loaded before any of the .o's.
  939. let known_dlls = [ dll | DLLPath dll <- classifieds ]
  940. dlls = [ dll | DLL dll <- classifieds ]
  941. objs = [ obj | Object obj <- classifieds ]
  942. archs = [ arch | Archive arch <- classifieds ]
  943. maybePutStr dflags ("Loading package " ++ display (sourcePackageId pkg) ++ " ... ")
  944. -- See comments with partOfGHCi
  945. when (packageName pkg `notElem` partOfGHCi) $ do
  946. loadFrameworks platform pkg
  947. mapM_ load_dyn (known_dlls ++ map (mkSOName platform) dlls)
  948. -- After loading all the DLLs, we can load the static objects.
  949. -- Ordering isn't important here, because we do one final link
  950. -- step to resolve everything.
  951. mapM_ loadObj objs
  952. mapM_ loadArchive archs
  953. maybePutStr dflags "linking ... "
  954. ok <- resolveObjs
  955. if succeeded ok then maybePutStrLn dflags "done."
  956. else throwGhcExceptionIO (InstallationError ("unable to load package `" ++ display (sourcePackageId pkg) ++ "'"))
  957. -- we have already searched the filesystem; the strings passed to load_dyn
  958. -- can be passed directly to loadDLL. They are either fully-qualified
  959. -- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so"). In the latter case,
  960. -- loadDLL is going to search the system paths to find the library.
  961. --
  962. load_dyn :: FilePath -> IO ()
  963. load_dyn dll = do r <- loadDLL dll
  964. case r of
  965. Nothing -> return ()
  966. Just err -> throwGhcExceptionIO (CmdLineError ("can't load .so/.DLL for: "
  967. ++ dll ++ " (" ++ err ++ ")" ))
  968. loadFrameworks :: Platform -> InstalledPackageInfo_ ModuleName -> IO ()
  969. loadFrameworks platform pkg
  970. = if platformUsesFrameworks platform
  971. then mapM_ load frameworks
  972. else return ()
  973. where
  974. fw_dirs = Packages.frameworkDirs pkg
  975. frameworks = Packages.frameworks pkg
  976. load fw = do r <- loadFramework fw_dirs fw
  977. case r of
  978. Nothing -> return ()
  979. Just err -> throwGhcExceptionIO (CmdLineError ("can't load framework: "
  980. ++ fw ++ " (" ++ err ++ ")" ))
  981. -- Try to find an object file for a given library in the given paths.
  982. -- If it isn't present, we assume that addDLL in the RTS can find it,
  983. -- which generally means that it should be a dynamic library in the
  984. -- standard system search path.
  985. locateLib :: DynFlags -> Bool -> [FilePath] -> String -> IO LibrarySpec
  986. locateLib dflags is_hs dirs lib
  987. | not is_hs
  988. -- For non-Haskell libraries (e.g. gmp, iconv):
  989. -- first look in library-dirs for a dynamic library (libfoo.so)
  990. -- then look in library-dirs for a static library (libfoo.a)
  991. -- then try "gcc --print-file-name" to search gcc's search path
  992. -- for a dynamic library (#5289)
  993. -- otherwise, assume loadDLL can find it
  994. --
  995. = findDll `orElse` findArchive `orElse` tryGcc `orElse` assumeDll
  996. | not cDYNAMIC_GHC_PROGRAMS
  997. -- When the GHC package was not compiled as dynamic library
  998. -- (=DYNAMIC not set), we search for .o libraries or, if they
  999. -- don't exist, .a libraries.
  1000. = findObject `orElse` findArchive `orElse` assumeDll
  1001. | otherwise
  1002. -- When the GHC package was compiled as dynamic library (=DYNAMIC set),
  1003. -- we search for .so libraries first.
  1004. = findHSDll `orElse` findDynObject `orElse` assumeDll
  1005. where
  1006. mk_obj_path dir = dir </> (lib <.> "o")
  1007. mk_dyn_obj_path dir = dir </> (lib <.> "dyn_o")
  1008. mk_arch_path dir = dir </> ("lib" ++ lib <.> "a")
  1009. hs_dyn_lib_name = lib ++ "-ghc" ++ cProjectVersion
  1010. mk_hs_dyn_lib_path dir = dir </> mkSOName platform hs_dyn_lib_name
  1011. so_name = mkSOName platform lib
  1012. mk_dyn_lib_path dir = dir </> so_name
  1013. findObject = liftM (fmap Object) $ findFile mk_obj_path dirs
  1014. findDynObject = liftM (fmap Object) $ findFile mk_dyn_obj_path dirs
  1015. findArchive = liftM (fmap Archive) $ findFile mk_arch_path dirs
  1016. findHSDll = liftM (fmap DLLPath) $ findFile mk_hs_dyn_lib_path dirs
  1017. findDll = liftM (fmap DLLPath) $ findFile mk_dyn_lib_path dirs
  1018. tryGcc = liftM (fmap DLLPath) $ searchForLibUsingGcc dflags so_name dirs
  1019. assumeDll = return (DLL lib)
  1020. infixr `orElse`
  1021. f `orElse` g = do m <- f
  1022. case m of
  1023. Just x -> return x

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