PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/ghc-7.0.4/compiler/ghci/Linker.lhs

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