{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections, RecordWildCards #-}{-# LANGUAGE BangPatterns #-}{-# OPTIONS_GHC -fno-cse #-}-- -fno-cse is needed for GLOBAL_VAR's to behave properly---- (c) The University of Glasgow 2002-2006---- | The dynamic linker for GHCi.---- This module deals with the top-level issues of dynamic linking,-- calling the object-code linker and the byte-code linker where-- necessary.moduleLinker(getHValue ,showLinkerState ,linkExpr ,linkDecls ,unload ,withExtendedLinkEnv ,extendLinkEnv ,deleteFromLinkEnv ,extendLoadedPkgs ,linkPackages ,initDynLinker ,linkModule ,linkCmdLineLibs )where#include "HsVersions.h"
importGhcPrelude importGHCi importGHCi.RemoteTypes importLoadIface importByteCodeLink importByteCodeAsm importByteCodeTypes importTcRnMonad importPackages importDriverPhases importFinder importHscTypes importName importNameEnv importModule importListSetOps importDynFlags importBasicTypes importOutputable importPanic importUtil importErrUtils importSrcLoc importqualifiedMaybes importUniqDSet importFastString importPlatform importSysTools importFileCleanup -- Standard librariesimportControl.MonadimportData.Char(isSpace)importData.IORefimportData.ListimportData.MaybeimportControl.Concurrent.MVarimportSystem.FilePathimportSystem.DirectoryimportSystem.IO.UnsafeimportSystem.Environment(lookupEnv)#if defined(mingw32_HOST_OS)
importSystem.Win32.Info(getSystemDirectory)#endif
importException -- needed for 2nd stage#if STAGE >= 2
importForeign(Ptr)#endif
{- **********************************************************************
 The Linker's state
 ********************************************************************* -}{-
The persistent linker state *must* match the actual state of the
C dynamic linker at all times, so we keep it in a private global variable.
The global IORef used for PersistentLinkerState actually contains another MVar,
which in turn contains a Maybe PersistentLinkerState. The MVar serves to ensure
mutual exclusion between multiple loaded copies of the GHC library. The Maybe
may be Nothing to indicate that the linker has not yet been initialised.
The PersistentLinkerState maps Names to actual closures (for
interpreted code only), for use during linking.
-}#if STAGE < 2
GLOBAL_VAR_M(v_PersistentLinkerState,newMVarNothing,MVar(MaybePersistentLinkerState))#else
SHARED_GLOBAL_VAR_M(v_PersistentLinkerState,getOrSetLibHSghcPersistentLinkerState,"getOrSetLibHSghcPersistentLinkerState",newMVarNothing,MVar(MaybePersistentLinkerState))#endif
uninitialised::a uninitialised =panic "Dynamic linker not initialised"modifyPLS_::(PersistentLinkerState ->IOPersistentLinkerState )->IO()modifyPLS_ f =readIORefv_PersistentLinkerState >>=flipmodifyMVar_(fmappure.f .fromMaybeuninitialised )modifyPLS::(PersistentLinkerState ->IO(PersistentLinkerState ,a ))->IOa modifyPLS f =readIORefv_PersistentLinkerState >>=flipmodifyMVar(fmapFst pure.f .fromMaybeuninitialised )wherefmapFst f =fmap(\(x ,y )->(f x ,y ))readPLS::IOPersistentLinkerState readPLS =readIORefv_PersistentLinkerState >>=fmap(fromMaybeuninitialised ).readMVarmodifyMbPLS_::(MaybePersistentLinkerState ->IO(MaybePersistentLinkerState ))->IO()modifyMbPLS_ f =readIORefv_PersistentLinkerState >>=flipmodifyMVar_f dataPersistentLinkerState =PersistentLinkerState {-- Current global mapping from Names to their true valuesclosure_env ::ClosureEnv ,-- The current global mapping from RdrNames of DataCons to-- info table addresses.-- When a new Unlinked is linked into the running image, or an existing-- module in the image is replaced, the itbl_env must be updated-- appropriately.itbl_env ::!ItblEnv ,-- The currently loaded interpreted modules (home package)bcos_loaded ::![Linkable ],-- And the currently-loaded compiled modules (home package)objs_loaded ::![Linkable ],-- The currently-loaded packages; always object code-- Held, as usual, in dependency order; though I am not sure if-- that is really importantpkgs_loaded ::![LinkerUnitId ],-- we need to remember the name of previous temporary DLL/.so-- libraries so we can link them (see #10322)temp_sos ::![(FilePath,String)]}emptyPLS::DynFlags ->PersistentLinkerState emptyPLS _=PersistentLinkerState {closure_env=emptyNameEnv ,itbl_env=emptyNameEnv ,pkgs_loaded=init_pkgs ,bcos_loaded=[],objs_loaded=[],temp_sos=[]}-- Packages that don't need loading, because the compiler-- shares them with the interpreted program.---- The linker's symbol table is populated with RTS symbols using an-- explicit list. See rts/Linker.c for details.whereinit_pkgs =maptoInstalledUnitId [rtsUnitId ]extendLoadedPkgs::[InstalledUnitId ]->IO()extendLoadedPkgs pkgs =modifyPLS_ $\s ->returns {pkgs_loaded=pkgs ++pkgs_loadeds }extendLinkEnv::[(Name ,ForeignHValue )]->IO()extendLinkEnv new_bindings =modifyPLS_ $\pls @PersistentLinkerState {..}->doletnew_ce =extendClosureEnv closure_env new_bindings return$!pls {closure_env=new_ce }-- strictness is important for not retaining old copies of the plsdeleteFromLinkEnv::[Name ]->IO()deleteFromLinkEnv to_remove =modifyPLS_ $\pls ->doletce =closure_envpls letnew_ce =delListFromNameEnv ce to_remove returnpls {closure_env=new_ce }-- | Get the 'HValue' associated with the given name.---- May cause loading the module that contains the name.---- Throws a 'ProgramError' if loading fails or the name cannot be found.getHValue::HscEnv ->Name ->IOForeignHValue getHValue hsc_env name =doinitDynLinker hsc_env pls <-modifyPLS $\pls ->doif(isExternalName name )thendo(pls' ,ok )<-linkDependencies hsc_env pls noSrcSpan [nameModule name ]if(failed ok )thenthrowGhcExceptionIO (ProgramError "")elsereturn(pls' ,pls' )elsereturn(pls ,pls )caselookupNameEnv (closure_envpls )name ofJust(_,aa )->returnaa Nothing->ASSERT2(isExternalNamename ,ppr name)doletsym_to_find =nameToCLabel name "closure"m <-lookupClosure hsc_env (unpackFS sym_to_find )casem ofJusthvref ->mkFinalizedHValue hsc_env hvref Nothing->linkFail "ByteCodeLink.lookupCE"(unpackFS sym_to_find )linkDependencies::HscEnv ->PersistentLinkerState ->SrcSpan ->[Module ]->IO(PersistentLinkerState ,SuccessFlag )linkDependencies hsc_env pls span needed_mods =do-- initDynLinker (hsc_dflags hsc_env)lethpt =hsc_HPThsc_env dflags =hsc_dflagshsc_env -- The interpreter and dynamic linker can only handle object code built-- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.-- So here we check the build tag: if we're building a non-standard way-- then we need to find & link object files built the "normal" way.maybe_normal_osuf <-checkNonStdWay dflags span -- Find what packages and linkables are required(lnks ,pkgs )<-getLinkDeps hsc_env hpt pls maybe_normal_osuf span needed_mods -- Link the packages and modules requiredpls1 <-linkPackages' hsc_env pkgs pls linkModules hsc_env pls1 lnks -- | Temporarily extend the linker state.withExtendedLinkEnv::(ExceptionMonad m )=>[(Name ,ForeignHValue )]->m a ->m a withExtendedLinkEnv new_env action =gbracket (liftIO$extendLinkEnv new_env )(\_->reset_old_env )(\_->action )where-- Remember that the linker state might be side-effected-- during the execution of the IO action, and we don't want to-- lose those changes (we might have linked a new module or-- package), so the reset action only removes the names we-- added earlier.reset_old_env =liftIO$domodifyPLS_ $\pls ->letcur =closure_envpls new =delListFromNameEnv cur (mapfstnew_env )inreturnpls {closure_env=new }-- | Display the persistent linker state.showLinkerState::DynFlags ->IO()showLinkerState dflags =dopls <-readPLS putLogMsg dflags NoReason SevDump noSrcSpan (defaultDumpStyle dflags )(vcat [text "----- Linker state -----",text "Pkgs:"<+> ppr (pkgs_loadedpls ),text "Objs:"<+> ppr (objs_loadedpls ),text "BCOs:"<+> ppr (bcos_loadedpls )]){- **********************************************************************
 Initialisation
 ********************************************************************* -}-- | Initialise the dynamic linker. This entails---- a) Calling the C initialisation procedure,---- b) Loading any packages specified on the command line,---- c) Loading any packages specified on the command line, now held in the-- @-l@ options in @v_Opt_l@,---- d) Loading any @.o\/.dll@ files specified on the command line, now held-- in @ldInputs@,---- e) Loading any MacOS frameworks.---- NOTE: This function is idempotent; if called more than once, it does-- nothing. This is useful in Template Haskell, where we call it before-- trying to link.--initDynLinker::HscEnv ->IO()initDynLinker hsc_env =modifyMbPLS_ $\pls ->docasepls ofJust_->returnpls Nothing->Just<$>reallyInitDynLinker hsc_env reallyInitDynLinker::HscEnv ->IOPersistentLinkerState reallyInitDynLinker hsc_env =do-- Initialise the linker stateletdflags =hsc_dflagshsc_env pls0 =emptyPLS dflags -- (a) initialise the C dynamic linkerinitObjLinker hsc_env -- (b) Load packages from the command-line (Note [preload packages])pls <-linkPackages' hsc_env (preloadPackages(pkgStatedflags ))pls0 -- steps (c), (d) and (e)linkCmdLineLibs' hsc_env pls linkCmdLineLibs::HscEnv ->IO()linkCmdLineLibs hsc_env =doinitDynLinker hsc_env modifyPLS_ $\pls ->dolinkCmdLineLibs' hsc_env pls linkCmdLineLibs'::HscEnv ->PersistentLinkerState ->IOPersistentLinkerState linkCmdLineLibs' hsc_env pls =doletdflags @(DynFlags {ldInputs=cmdline_ld_inputs ,libraryPaths=lib_paths_base })=hsc_dflagshsc_env -- (c) Link libraries from the command-lineletminus_ls_1 =[lib |Option ('-':'l':lib )<-cmdline_ld_inputs ]-- On Windows we want to add libpthread by default just as GCC would.-- However because we don't know the actual name of pthread's dll we-- need to defer this to the locateLib call so we can't initialize it-- inside of the rts. Instead we do it here to be able to find the-- import library for pthreads. See Trac #13210.letplatform =targetPlatform dflags os =platformOSplatform minus_ls =caseos ofOSMinGW32 ->"pthread":minus_ls_1 _->minus_ls_1 -- See Note [Fork/Exec Windows]gcc_paths <-getGCCPaths dflags os lib_paths_env <-addEnvPaths "LIBRARY_PATH"lib_paths_base maybePutStrLn dflags "Search directories (user):"maybePutStr dflags (unlines$map(" "++)lib_paths_env )maybePutStrLn dflags "Search directories (gcc):"maybePutStr dflags (unlines$map(" "++)gcc_paths )libspecs <-mapM(locateLib hsc_env Falselib_paths_env gcc_paths )minus_ls -- (d) Link .o files from the command-lineclassified_ld_inputs <-mapM(classifyLdInput dflags )[f |FileOption _f <-cmdline_ld_inputs ]-- (e) Link any MacOS frameworksletplatform =targetPlatform dflags let(framework_paths ,frameworks )=ifplatformUsesFrameworks platform then(frameworkPathsdflags ,cmdlineFrameworksdflags )else([],[])-- Finally do (c),(d),(e)letcmdline_lib_specs =catMaybesclassified_ld_inputs ++libspecs ++mapFramework frameworks ifnullcmdline_lib_specs thenreturnpls elsedo-- Add directories to library search paths, this only has an effect-- on Windows. On Unix OSes this function is a NOP.letall_paths =letpaths =takeDirectory(fst$sPgm_c$settingsdflags ):framework_paths ++lib_paths_base ++[takeDirectorydll |DLLPath dll <-libspecs ]innub$mapnormalisepaths letlib_paths =nub$lib_paths_base ++gcc_paths all_paths_env <-addEnvPaths "LD_LIBRARY_PATH"all_paths pathCache <-mapM(addLibrarySearchPath hsc_env )all_paths_env pls1 <-foldM(preloadLib hsc_env lib_paths framework_paths )pls cmdline_lib_specs maybePutStr dflags "final link ... "ok <-resolveObjs hsc_env -- DLLs are loaded, reset the search pathsmapM_(removeLibrarySearchPath hsc_env )$reversepathCache ifsucceeded ok thenmaybePutStrLn dflags "done"elsethrowGhcExceptionIO (ProgramError "linking extra libraries/objects failed")returnpls1 {- Note [preload packages]
Why do we need to preload packages from the command line? This is an
explanation copied from #2437:
I tried to implement the suggestion from #3560, thinking it would be
easy, but there are two reasons we link in packages eagerly when they
are mentioned on the command line:
 * So that you can link in extra object files or libraries that
 depend on the packages. e.g. ghc -package foo -lbar where bar is a
 C library that depends on something in foo. So we could link in
 foo eagerly if and only if there are extra C libs or objects to
 link in, but....
 * Haskell code can depend on a C function exported by a package, and
 the normal dependency tracking that TH uses can't know about these
 dependencies. The test ghcilink004 relies on this, for example.
I conclude that we need two -package flags: one that says "this is a
package I want to make available", and one that says "this is a
package I want to link in eagerly". Would that be too complicated for
users?
-}classifyLdInput::DynFlags ->FilePath->IO(MaybeLibrarySpec )classifyLdInput dflags f |isObjectFilename platform f =return(Just(Object f ))|isDynLibFilename platform f =return(Just(DLLPath f ))|otherwise=doputLogMsg dflags NoReason SevInfo noSrcSpan (defaultUserStyle dflags )(text ("Warning: ignoring unrecognised input `"++f ++"'"))returnNothingwhereplatform =targetPlatform dflags preloadLib::HscEnv ->[String]->[String]->PersistentLinkerState ->LibrarySpec ->IOPersistentLinkerState preloadLib hsc_env lib_paths framework_paths pls lib_spec =domaybePutStr dflags ("Loading object "++showLS lib_spec ++" ... ")caselib_spec ofObject static_ish ->do(b ,pls1 )<-preload_static lib_paths static_ish maybePutStrLn dflags (ifb then"done"else"not found")returnpls1 Archive static_ish ->dob <-preload_static_archive lib_paths static_ish maybePutStrLn dflags (ifb then"done"else"not found")returnpls DLL dll_unadorned ->domaybe_errstr <-loadDLL hsc_env (mkSOName platform dll_unadorned )casemaybe_errstr ofNothing->maybePutStrLn dflags "done"Justmm |platformOSplatform /=OSDarwin ->preloadFailed mm lib_paths lib_spec Justmm |otherwise->do-- As a backup, on Darwin, try to also load a .so file-- since (apparently) some things install that way - see-- ticket #8770.letlibfile =("lib"++dll_unadorned )<.>"so"err2 <-loadDLL hsc_env libfile caseerr2 ofNothing->maybePutStrLn dflags "done"Just_->preloadFailed mm lib_paths lib_spec returnpls DLLPath dll_path ->dodomaybe_errstr <-loadDLL hsc_env dll_path casemaybe_errstr ofNothing->maybePutStrLn dflags "done"Justmm ->preloadFailed mm lib_paths lib_spec returnpls Framework framework ->ifplatformUsesFrameworks (targetPlatform dflags )thendomaybe_errstr <-loadFramework hsc_env framework_paths framework casemaybe_errstr ofNothing->maybePutStrLn dflags "done"Justmm ->preloadFailed mm framework_paths lib_spec returnpls elsepanic "preloadLib Framework"wheredflags =hsc_dflagshsc_env platform =targetPlatform dflags preloadFailed::String->[String]->LibrarySpec ->IO()preloadFailed sys_errmsg paths spec =domaybePutStr dflags "failed.\n"throwGhcExceptionIO $CmdLineError ("user specified .o/.so/.DLL could not be loaded ("++sys_errmsg ++")\nWhilst trying to load: "++showLS spec ++"\nAdditional directories searched:"++(ifnullpaths then" (none)"elseintercalate"\n"(map(" "++)paths )))-- Not interested in the paths in the static case.preload_static _paths name =dob <-doesFileExistname ifnotb thenreturn(False,pls )elseifdynamicGhc thendopls1 <-dynLoadObjs hsc_env pls [name ]return(True,pls1 )elsedoloadObj hsc_env name return(True,pls )preload_static_archive _paths name =dob <-doesFileExistname ifnotb thenreturnFalseelsedoifdynamicGhc thenthrowGhcExceptionIO $CmdLineError dynamic_msg elseloadArchive hsc_env name returnTruewheredynamic_msg =unlines["User-specified static library could not be loaded ("++name ++")","Loading static libraries is not supported in this configuration.","Try using a dynamic library instead."]{- **********************************************************************
 Link a byte-code expression
 ********************************************************************* -}-- | Link a single expression, /including/ first linking packages and-- modules that this expression depends on.---- Raises an IO exception ('ProgramError') if it can't find a compiled-- version of the dependents to link.--linkExpr::HscEnv ->SrcSpan ->UnlinkedBCO ->IOForeignHValue linkExpr hsc_env span root_ul_bco =do{-- Initialise the linker (if it's not been done already);initDynLinker hsc_env -- Take lock for the actual work.;modifyPLS $\pls0 ->do{-- Link the packages and modules required;(pls ,ok )<-linkDependencies hsc_env pls0 span needed_mods ;iffailed ok thenthrowGhcExceptionIO (ProgramError "")elsedo{-- Link the expression itselfletie =itbl_envpls ce =closure_envpls -- Link the necessary packages and linkables;letnobreakarray =error"no break array"bco_ix =mkNameEnv [(unlinkedBCONameroot_ul_bco ,0)];resolved <-linkBCO hsc_env ie ce bco_ix nobreakarray root_ul_bco ;[root_hvref ]<-createBCOs hsc_env [resolved ];fhv <-mkFinalizedHValue hsc_env root_hvref ;return(pls ,fhv )}}}wherefree_names =uniqDSetToList (bcoFreeNames root_ul_bco )needed_mods::[Module ]needed_mods =[nameModule n |n <-free_names ,isExternalName n ,-- Names from other modulesnot(isWiredInName n )-- Exclude wired-in names]-- (see note below)-- Exclude wired-in names because we may not have read-- their interface files, so getLinkDeps will fail-- All wired-in names are in the base package, which we link-- by default, so we can safely ignore them here.dieWith::DynFlags ->SrcSpan ->MsgDoc ->IOa dieWith dflags span msg =throwGhcExceptionIO (ProgramError (showSDoc dflags (mkLocMessage SevFatal span msg )))checkNonStdWay::DynFlags ->SrcSpan ->IO(MaybeFilePath)checkNonStdWay dflags srcspan |gopt Opt_ExternalInterpreter dflags =returnNothing-- with -fexternal-interpreter we load the .o files, whatever way-- they were built. If they were built for a non-std way, then-- we will use the appropriate variant of the iserv binary to load them.|interpWays ==haskellWays =returnNothing-- Only if we are compiling with the same ways as GHC is built-- with, can we dynamically load those object files. (see #3604)|objectSufdflags ==normalObjectSuffix &&not(nullhaskellWays )=failNonStd dflags srcspan |otherwise=return(Just(interpTag ++"o"))wherehaskellWays =filter(not.wayRTSOnly )(waysdflags )interpTag =casemkBuildTag interpWays of""->""tag ->tag ++"_"normalObjectSuffix::StringnormalObjectSuffix =phaseInputExt StopLn failNonStd::DynFlags ->SrcSpan ->IO(MaybeFilePath)failNonStd dflags srcspan =dieWith dflags srcspan $text "Cannot load"<+> compWay <+> text "objects when GHC is built"<+> ghciWay $$ text "To fix this, either:"$$ text " (1) Use -fexternal-interpreter, or"$$ text " (2) Build the program twice: once"<+> ghciWay <> text ", and then"$$ text " with"<+> compWay <+> text "using -osuf to set a different object file suffix."wherecompWay |WayDyn `elem`waysdflags =text "-dynamic"|WayProf `elem`waysdflags =text "-prof"|otherwise=text "normal"ghciWay |dynamicGhc =text "with -dynamic"|rtsIsProfiled =text "with -prof"|otherwise=text "the normal way"getLinkDeps::HscEnv ->HomePackageTable ->PersistentLinkerState ->MaybeFilePath-- replace object suffices?->SrcSpan -- for error messages->[Module ]-- If you need these->IO([Linkable ],[InstalledUnitId ])-- ... then link these first-- Fails with an IO exception if it can't find enough filesgetLinkDeps hsc_env hpt pls replace_osuf span mods -- Find all the packages and linkables that a set of modules depends on=do{-- 1. Find the dependent home-pkg-modules/packages from each iface-- (omitting modules from the interactive package, which is already linked);(mods_s ,pkgs_s )<-follow_deps (filterOut isInteractiveModule mods )emptyUniqDSet emptyUniqDSet ;;let{-- 2. Exclude ones already linked-- Main reason: avoid findModule calls in get_linkablemods_needed =mods_s `minusList `linked_mods ;pkgs_needed =pkgs_s `minusList `pkgs_loadedpls ;linked_mods =map(moduleName.linkableModule)(objs_loadedpls ++bcos_loadedpls )}-- 3. For each dependent module, find its linkable-- This will either be in the HPT or (in the case of one-shot-- compilation) we may need to use maybe_getFileLinkable;let{osuf =objectSufdflags };lnks_needed <-mapM(get_linkable osuf )mods_needed ;return(lnks_needed ,pkgs_needed )}wheredflags =hsc_dflagshsc_env this_pkg =thisPackage dflags -- The ModIface contains the transitive closure of the module dependencies-- within the current package, *except* for boot modules: if we encounter-- a boot module, we have to find its real interface and discover the-- dependencies of that. Hence we need to traverse the dependency-- tree recursively. See bug #936, testcase ghci/prog007.follow_deps::[Module ]-- modules to follow->UniqDSet ModuleName -- accum. module dependencies->UniqDSet InstalledUnitId -- accum. package dependencies->IO([ModuleName ],[InstalledUnitId ])-- resultfollow_deps []acc_mods acc_pkgs =return(uniqDSetToList acc_mods ,uniqDSetToList acc_pkgs )follow_deps(mod :mods )acc_mods acc_pkgs =domb_iface <-initIfaceCheck (text "getLinkDeps")hsc_env $loadInterface msg mod (ImportByUser False)iface <-casemb_iface ofMaybes.Failed err ->throwGhcExceptionIO (ProgramError (showSDoc dflags err ))Maybes.Succeeded iface ->returniface when(mi_boot iface )$link_boot_mod_error mod letpkg =moduleUnitIdmod deps =mi_depsiface pkg_deps =dep_pkgsdeps (boot_deps ,mod_deps )=partitionWith is_boot (dep_modsdeps )whereis_boot (m ,True)=Leftm is_boot(m ,False)=Rightm boot_deps' =filter(not.(`elementOfUniqDSet `acc_mods ))boot_deps acc_mods' =addListToUniqDSet acc_mods (moduleNamemod :mod_deps )acc_pkgs' =addListToUniqDSet acc_pkgs $mapfstpkg_deps --ifpkg /=this_pkg thenfollow_deps mods acc_mods (addOneToUniqDSet acc_pkgs' (toInstalledUnitId pkg ))elsefollow_deps (map(mkModule this_pkg )boot_deps' ++mods )acc_mods' acc_pkgs' wheremsg =text "need to link module"<+> ppr mod <+> text "due to use of Template Haskell"link_boot_mod_error mod =throwGhcExceptionIO (ProgramError (showSDoc dflags (text "module"<+> ppr mod <+> text "cannot be linked; it is only available as a boot module")))no_obj::Outputable a =>a ->IOb no_obj mod =dieWith dflags span $text "cannot find object file for module "<> quotes (ppr mod )$$ while_linking_expr while_linking_expr =text "while linking an interpreted expression"-- This one is a build-system bugget_linkable osuf mod_name -- A home-package module|Justmod_info <-lookupHpt hpt mod_name =adjust_linkable (Maybes.expectJust "getLinkDeps"(hm_linkablemod_info ))|otherwise=do-- It's not in the HPT because we are in one shot mode,-- so use the Finder to get a ModLocation...mb_stuff <-findHomeModule hsc_env mod_name casemb_stuff ofFound loc mod ->found loc mod _->no_obj mod_name wherefound loc mod =do{-- ...and then find the linkable for itmb_lnk <-findObjectLinkableMaybe mod loc ;casemb_lnk of{Nothing->no_obj mod ;Justlnk ->adjust_linkable lnk }}adjust_linkable lnk |Justnew_osuf <-replace_osuf =donew_uls <-mapM(adjust_ul new_osuf )(linkableUnlinkedlnk )returnlnk {linkableUnlinked=new_uls }|otherwise=returnlnk adjust_ul new_osuf (DotO file )=doMASSERT(osuf `isSuffixOf`file)letfile_base =fromJust(stripExtensionosuf file )new_file =file_base <.>new_osuf ok <-doesFileExistnew_file if(notok )thendieWith dflags span $text "cannot find object file "<> quotes (text new_file )$$ while_linking_expr elsereturn(DotO new_file )adjust_ul_(DotA fp )=panic ("adjust_ul DotA "++showfp )adjust_ul_(DotDLL fp )=panic ("adjust_ul DotDLL "++showfp )adjust_ul_l @(BCOs {})=returnl {- **********************************************************************
 Loading a Decls statement
 ********************************************************************* -}linkDecls::HscEnv ->SrcSpan ->CompiledByteCode ->IO()linkDecls hsc_env span cbc @CompiledByteCode {..}=do-- Initialise the linker (if it's not been done already)initDynLinker hsc_env -- Take lock for the actual work.modifyPLS $\pls0 ->do-- Link the packages and modules required(pls ,ok )<-linkDependencies hsc_env pls0 span needed_mods iffailed ok thenthrowGhcExceptionIO (ProgramError "")elsedo-- Link the expression itselfletie =plusNameEnv (itbl_envpls )bc_itbls ce =closure_envpls -- Link the necessary packages and linkablesnew_bindings <-linkSomeBCOs hsc_env ie ce [cbc ]nms_fhvs <-makeForeignNamedHValueRefs hsc_env new_bindings letpls2 =pls {closure_env=extendClosureEnv ce nms_fhvs ,itbl_env=ie }return(pls2 ,())wherefree_names =uniqDSetToList $foldr(unionUniqDSets .bcoFreeNames )emptyUniqDSet bc_bcos needed_mods::[Module ]needed_mods =[nameModule n |n <-free_names ,isExternalName n ,-- Names from other modulesnot(isWiredInName n )-- Exclude wired-in names]-- (see note below)-- Exclude wired-in names because we may not have read-- their interface files, so getLinkDeps will fail-- All wired-in names are in the base package, which we link-- by default, so we can safely ignore them here.{- **********************************************************************
 Loading a single module
 ********************************************************************* -}linkModule::HscEnv ->Module ->IO()linkModule hsc_env mod =doinitDynLinker hsc_env modifyPLS_ $\pls ->do(pls' ,ok )<-linkDependencies hsc_env pls noSrcSpan [mod ]if(failed ok )thenthrowGhcExceptionIO (ProgramError "could not link module")elsereturnpls' {- **********************************************************************
 Link some linkables
 The linkables may consist of a mixture of
 byte-code modules and object modules
 ********************************************************************* -}linkModules::HscEnv ->PersistentLinkerState ->[Linkable ]->IO(PersistentLinkerState ,SuccessFlag )linkModules hsc_env pls linkables =mask_$do-- don't want to be interrupted by ^C in herelet(objs ,bcos )=partitionisObjectLinkable (concatMappartitionLinkable linkables )-- Load objects first; they can't depend on BCOs(pls1 ,ok_flag )<-dynLinkObjs hsc_env pls objs iffailed ok_flag thenreturn(pls1 ,Failed )elsedopls2 <-dynLinkBCOs hsc_env pls1 bcos return(pls2 ,Succeeded )-- HACK to support f-x-dynamic in the interpreter; no other purposepartitionLinkable::Linkable ->[Linkable ]partitionLinkable li =letli_uls =linkableUnlinkedli li_uls_obj =filterisObject li_uls li_uls_bco =filterisInterpretable li_uls incase(li_uls_obj ,li_uls_bco )of(_:_,_:_)->[li {linkableUnlinked=li_uls_obj },li {linkableUnlinked=li_uls_bco }]_->[li ]findModuleLinkable_maybe::[Linkable ]->Module ->MaybeLinkable findModuleLinkable_maybe lis mod =case[LM time nm us |LM time nm us <-lis ,nm ==mod ]of[]->Nothing[li ]->Justli _->pprPanic "findModuleLinkable"(ppr mod )linkableInSet::Linkable ->[Linkable ]->BoollinkableInSet l objs_loaded =casefindModuleLinkable_maybe objs_loaded (linkableModulel )ofNothing->FalseJustm ->linkableTimel ==linkableTimem {- **********************************************************************
 The object-code linker
 ********************************************************************* -}dynLinkObjs::HscEnv ->PersistentLinkerState ->[Linkable ]->IO(PersistentLinkerState ,SuccessFlag )dynLinkObjs hsc_env pls objs =do-- Load the object files and link themlet(objs_loaded' ,new_objs )=rmDupLinkables (objs_loadedpls )objs pls1 =pls {objs_loaded=objs_loaded' }unlinkeds =concatMaplinkableUnlinkednew_objs wanted_objs =mapnameOfObject unlinkeds ifinterpreterDynamic (hsc_dflagshsc_env )thendopls2 <-dynLoadObjs hsc_env pls1 wanted_objs return(pls2 ,Succeeded )elsedomapM_(loadObj hsc_env )wanted_objs -- Link them all togetherok <-resolveObjs hsc_env -- If resolving failed, unload all our-- object modules and carry onifsucceeded ok thendoreturn(pls1 ,Succeeded )elsedopls2 <-unload_wkr hsc_env []pls1 return(pls2 ,Failed )dynLoadObjs::HscEnv ->PersistentLinkerState ->[FilePath]->IOPersistentLinkerState dynLoadObjs _pls []=returnpls dynLoadObjshsc_env pls objs =doletdflags =hsc_dflagshsc_env letplatform =targetPlatform dflags letminus_ls =[lib |Option ('-':'l':lib )<-ldInputsdflags ]letminus_big_ls =[lib |Option ('-':'L':lib )<-ldInputsdflags ](soFile ,libPath ,libName )<-newTempLibName dflags TFL_CurrentModule (soExt platform )letdflags2 =dflags {-- We don't want the original ldInputs in-- (they're already linked in), but we do want-- to link against previous dynLoadObjs-- libraries if there were any, so that the linker-- can resolve dependencies when it loads this-- library.ldInputs=concatMap(\l ->[Option ("-l"++l )])(nub$snd<$>temp_sospls )++concatMap(\lp ->[Option ("-L"++lp ),Option "-Xlinker",Option "-rpath",Option "-Xlinker",Option lp ])(nub$fst<$>temp_sospls )++concatMap(\lp ->[Option ("-L"++lp ),Option "-Xlinker",Option "-rpath",Option "-Xlinker",Option lp ])minus_big_ls -- See Note [-Xlinker -rpath vs -Wl,-rpath]++map(\l ->Option ("-l"++l ))minus_ls ,-- Add -l options and -L options from dflags.---- When running TH for a non-dynamic way, we still-- need to make -l flags to link against the dynamic-- libraries, so we need to add WayDyn to ways.---- Even if we're e.g. profiling, we still want-- the vanilla dynamic libraries, so we set the-- ways / build tag to be just WayDyn.ways=[WayDyn ],buildTag=mkBuildTag [WayDyn ],outputFile=JustsoFile }-- link all "loaded packages" so symbols in those can be resolved-- Note: We are loading packages with local scope, so to see the-- symbols in this link we must link all loaded packages again.linkDynLib dflags2 objs (pkgs_loadedpls )-- if we got this far, extend the lifetime of the library filechangeTempFilesLifetime dflags TFL_GhcSession [soFile ]m <-loadDLL hsc_env soFile casem ofNothing->returnpls {temp_sos=(libPath ,libName ):temp_sospls }Justerr ->panic ("Loading temp shared object failed: "++err )rmDupLinkables::[Linkable ]-- Already loaded->[Linkable ]-- New linkables->([Linkable ],-- New loaded set (including new ones)[Linkable ])-- New linkables (excluding dups)rmDupLinkables already ls =go already []ls wherego already extras []=(already ,extras )goalready extras (l :ls )|linkableInSet l already =go already extras ls |otherwise=go (l :already )(l :extras )ls {- **********************************************************************
 The byte-code linker
 ********************************************************************* -}dynLinkBCOs::HscEnv ->PersistentLinkerState ->[Linkable ]->IOPersistentLinkerState dynLinkBCOs hsc_env pls bcos =dolet(bcos_loaded' ,new_bcos )=rmDupLinkables (bcos_loadedpls )bcos pls1 =pls {bcos_loaded=bcos_loaded' }unlinkeds::[Unlinked ]unlinkeds =concatMaplinkableUnlinkednew_bcos cbcs::[CompiledByteCode ]cbcs =mapbyteCodeOfObject unlinkeds ies =mapbc_itblscbcs gce =closure_envpls final_ie =foldrplusNameEnv (itbl_envpls )ies names_and_refs <-linkSomeBCOs hsc_env final_ie gce cbcs -- We only want to add the external ones to the ClosureEnvlet(to_add ,to_drop )=partition(isExternalName .fst)names_and_refs -- Immediately release any HValueRefs we're not going to addfreeHValueRefs hsc_env (mapsndto_drop )-- Wrap finalizers on the ones we want to keepnew_binds <-makeForeignNamedHValueRefs hsc_env to_add returnpls1 {closure_env=extendClosureEnv gce new_binds ,itbl_env=final_ie }-- Link a bunch of BCOs and return references to their valueslinkSomeBCOs::HscEnv ->ItblEnv ->ClosureEnv ->[CompiledByteCode ]->IO[(Name ,HValueRef )]-- The returned HValueRefs are associated 1-1 with-- the incoming unlinked BCOs. Each gives the-- value of the corresponding unlinked BCOlinkSomeBCOs hsc_env ie ce mods =foldrfun do_link mods []wherefun CompiledByteCode {..}inner accum =casebc_breaks ofNothing->inner ((panic "linkSomeBCOs: no break array",bc_bcos ):accum )Justmb ->withForeignRef (modBreaks_flagsmb )$\breakarray ->inner ((breakarray ,bc_bcos ):accum )do_link []=return[]do_linkmods =doletflat =[(breakarray ,bco )|(breakarray ,bcos )<-mods ,bco <-bcos ]names =map(unlinkedBCOName.snd)flat bco_ix =mkNameEnv (zipnames [0..])resolved <-sequence[linkBCO hsc_env ie ce bco_ix breakarray bco |(breakarray ,bco )<-flat ]hvrefs <-createBCOs hsc_env resolved return(zipnames hvrefs )-- | Useful to apply to the result of 'linkSomeBCOs'makeForeignNamedHValueRefs::HscEnv ->[(Name ,HValueRef )]->IO[(Name ,ForeignHValue )]makeForeignNamedHValueRefs hsc_env bindings =mapM(\(n ,hvref )->(n ,)<$>mkFinalizedHValue hsc_env hvref )bindings {- **********************************************************************
 Unload some object modules
 ********************************************************************* -}-- ----------------------------------------------------------------------------- | Unloading old objects ready for a new compilation sweep.---- The compilation manager provides us with a list of linkables that it-- considers \"stable\", i.e. won't be recompiled this time around. For-- each of the modules current linked in memory,---- * if the linkable is stable (and it's the same one -- the user may have-- recompiled the module on the side), we keep it,---- * otherwise, we unload it.---- * we also implicitly unload all temporary bindings at this point.--unload::HscEnv ->[Linkable ]-- ^ The linkables to *keep*.->IO()unload hsc_env linkables =mask_$do-- mask, so we're safe from Ctrl-C in here-- Initialise the linker (if it's not been done already)initDynLinker hsc_env new_pls <-modifyPLS $\pls ->dopls1 <-unload_wkr hsc_env linkables pls return(pls1 ,pls1 )letdflags =hsc_dflagshsc_env debugTraceMsg dflags 3$text "unload: retaining objs"<+> ppr (objs_loadednew_pls )debugTraceMsg dflags 3$text "unload: retaining bcos"<+> ppr (bcos_loadednew_pls )return()unload_wkr::HscEnv ->[Linkable ]-- stable linkables->PersistentLinkerState ->IOPersistentLinkerState -- Does the core unload business-- (the wrapper blocks exceptions and deals with the PLS get and put)unload_wkr hsc_env keep_linkables pls @PersistentLinkerState {..}=do-- NB. careful strictness here to avoid keeping the old PLS when-- we're unloading some code. -fghci-leak-check with the tests in-- testsuite/ghci can detect space leaks here.let(objs_to_keep ,bcos_to_keep )=partitionisObjectLinkable keep_linkables discard keep l =not(linkableInSet l keep )(objs_to_unload ,remaining_objs_loaded )=partition(discard objs_to_keep )objs_loaded (bcos_to_unload ,remaining_bcos_loaded )=partition(discard bcos_to_keep )bcos_loaded mapM_unloadObjs objs_to_unload mapM_unloadObjs bcos_to_unload -- If we unloaded any object files at all, we need to purge the cache-- of lookupSymbol results.when(not(null(objs_to_unload ++filter(not.null.linkableObjs )bcos_to_unload )))$purgeLookupSymbolCache hsc_env let!bcos_retained =mkModuleSet $maplinkableModuleremaining_bcos_loaded -- Note that we want to remove all *local*-- (i.e. non-isExternal) names too (these are the-- temporary bindings from the command line).keep_name (n ,_)=isExternalName n &&nameModule n `elemModuleSet `bcos_retained itbl_env' =filterNameEnv keep_name itbl_env closure_env' =filterNameEnv keep_name closure_env !new_pls =pls {itbl_env=itbl_env' ,closure_env=closure_env' ,bcos_loaded=remaining_bcos_loaded ,objs_loaded=remaining_objs_loaded }returnnew_pls whereunloadObjs::Linkable ->IO()unloadObjs lnk |dynamicGhc =return()-- We don't do any cleanup when linking objects with the-- dynamic linker. Doing so introduces extra complexity for-- not much benefit.|otherwise=mapM_(unloadObj hsc_env )[f |DotO f <-linkableUnlinkedlnk ]-- The components of a BCO linkable may contain-- dot-o files. Which is very confusing.---- But the BCO parts can be unlinked just by-- letting go of them (plus of course depopulating-- the symbol table which is done in the main body){- **********************************************************************
 Loading packages
 ********************************************************************* -}dataLibrarySpec =Object FilePath-- Full path name of a .o file, including trailing .o-- For dynamic objects only, try to find the object-- file in all the directories specified in-- v_Library_paths before giving up.|Archive FilePath-- Full path name of a .a file, including trailing .a|DLL String-- "Unadorned" name of a .DLL/.so-- e.g. On unix "qt" denotes "libqt.so"-- On Windows "burble" denotes "burble.DLL" or "libburble.dll"-- loadDLL is platform-specific and adds the lib/.so/.DLL-- suffixes platform-dependently|DLLPath FilePath-- Absolute or relative pathname to a dynamic library-- (ends with .dll or .so).|Framework String-- Only used for darwin, but does no harm-- If this package is already part of the GHCi binary, we'll already-- have the right DLLs for this package loaded, so don't try to-- load them again.---- But on Win32 we must load them 'again'; doing so is a harmless no-op-- as far as the loader is concerned, but it does initialise the list-- of DLL handles that rts/Linker.c maintains, and that in turn is-- used by lookupSymbol. So we must call addDLL for each library-- just to get the DLL handle into the list.partOfGHCi::[PackageName ]partOfGHCi |isWindowsHost ||isDarwinHost =[]|otherwise=map(PackageName .mkFastString )["base","template-haskell","editline"]showLS::LibrarySpec ->StringshowLS (Object nm )="(static) "++nm showLS(Archive nm )="(static archive) "++nm showLS(DLL nm )="(dynamic) "++nm showLS(DLLPath nm )="(dynamic) "++nm showLS(Framework nm )="(framework) "++nm -- TODO: Make this type more precisetypeLinkerUnitId =InstalledUnitId -- | Link exactly the specified packages, and their dependents (unless of-- course they are already linked). The dependents are linked-- automatically, and it doesn't matter what order you specify the input-- packages.--linkPackages::HscEnv ->[LinkerUnitId ]->IO()-- NOTE: in fact, since each module tracks all the packages it depends on,-- we don't really need to use the package-config dependencies.---- However we do need the package-config stuff (to find aux libs etc),-- and following them lets us load libraries in the right order, which-- perhaps makes the error message a bit more localised if we get a link-- failure. So the dependency walking code is still here.linkPackages hsc_env new_pkgs =do-- It's probably not safe to try to load packages concurrently, so we take-- a lock.initDynLinker hsc_env modifyPLS_ $\pls ->dolinkPackages' hsc_env new_pkgs pls linkPackages'::HscEnv ->[LinkerUnitId ]->PersistentLinkerState ->IOPersistentLinkerState linkPackages' hsc_env new_pks pls =dopkgs' <-link (pkgs_loadedpls )new_pks return$!pls {pkgs_loaded=pkgs' }wheredflags =hsc_dflagshsc_env link::[LinkerUnitId ]->[LinkerUnitId ]->IO[LinkerUnitId ]link pkgs new_pkgs =foldMlink_one pkgs new_pkgs link_one pkgs new_pkg |new_pkg `elem`pkgs -- Already linked=returnpkgs |Justpkg_cfg <-lookupInstalledPackage dflags new_pkg =do{-- Link dependents firstpkgs' <-link pkgs (dependspkg_cfg )-- Now link the package itself;linkPackage hsc_env pkg_cfg ;return(new_pkg :pkgs' )}|otherwise=throwGhcExceptionIO (CmdLineError ("unknown package: "++unpackFS (installedUnitIdFSnew_pkg )))linkPackage::HscEnv ->PackageConfig ->IO()linkPackage hsc_env pkg =doletdflags =hsc_dflagshsc_env platform =targetPlatform dflags is_dyn =interpreterDynamic dflags dirs |is_dyn =Packages.libraryDynDirspkg |otherwise=Packages.libraryDirspkg leths_libs =Packages.hsLibrariespkg -- The FFI GHCi import lib isn't needed as-- compiler/ghci/Linker.hs + rts/Linker.c link the-- interpreted references to FFI to the compiled FFI.-- We therefore filter it out so that we don't get-- duplicate symbol errors.hs_libs' =filter("HSffi"/=)hs_libs -- Because of slight differences between the GHC dynamic linker and-- the native system linker some packages have to link with a-- different list of libraries when using GHCi. Examples include: libs-- that are actually gnu ld scripts, and the possibility that the .a-- libs do not exactly match the .so/.dll equivalents. So if the-- package file provides an "extra-ghci-libraries" field then we use-- that instead of the "extra-libraries" field.extra_libs =(ifnull(Packages.extraGHCiLibrariespkg )thenPackages.extraLibrariespkg elsePackages.extraGHCiLibrariespkg )++[lib |'-':'l':lib <-Packages.ldOptionspkg ]-- See Note [Fork/Exec Windows]gcc_paths <-getGCCPaths dflags (platformOSplatform )dirs_env <-addEnvPaths "LIBRARY_PATH"dirs hs_classifieds <-mapM(locateLib hsc_env Truedirs_env gcc_paths )hs_libs' extra_classifieds <-mapM(locateLib hsc_env Falsedirs_env gcc_paths )extra_libs letclassifieds =hs_classifieds ++extra_classifieds -- Complication: all the .so's must be loaded before any of the .o's.letknown_dlls =[dll |DLLPath dll <-classifieds ]dlls =[dll |DLL dll <-classifieds ]objs =[obj |Object obj <-classifieds ]archs =[arch |Archive arch <-classifieds ]-- Add directories to library search pathsletdll_paths =maptakeDirectoryknown_dlls all_paths =nub$mapnormalise$dll_paths ++dirs all_paths_env <-addEnvPaths "LD_LIBRARY_PATH"all_paths pathCache <-mapM(addLibrarySearchPath hsc_env )all_paths_env maybePutStr dflags ("Loading package "++sourcePackageIdString pkg ++" ... ")-- See comments with partOfGHCiwhen(packageNamepkg `notElem`partOfGHCi )$doloadFrameworks hsc_env platform pkg -- See Note [Crash early load_dyn and locateLib]-- Crash early if can't load any of `known_dlls`mapM_(load_dyn hsc_env True)known_dlls -- For remaining `dlls` crash early only when there is surely-- no package's DLL around ... (not is_dyn)mapM_(load_dyn hsc_env (notis_dyn ).mkSOName platform )dlls -- After loading all the DLLs, we can load the static objects.-- Ordering isn't important here, because we do one final link-- step to resolve everything.mapM_(loadObj hsc_env )objs mapM_(loadArchive hsc_env )archs maybePutStr dflags "linking ... "ok <-resolveObjs hsc_env -- DLLs are loaded, reset the search paths-- Import libraries will be loaded via loadArchive so only-- reset the DLL search path after all archives are loaded-- as well.mapM_(removeLibrarySearchPath hsc_env )$reversepathCache ifsucceeded ok thenmaybePutStrLn dflags "done."elseleterrmsg ="unable to load package `"++sourcePackageIdString pkg ++"'"inthrowGhcExceptionIO (InstallationError errmsg ){-
Note [Crash early load_dyn and locateLib]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a package is "normal" (exposes it's code from more than zero Haskell
modules, unlike e.g. that in ghcilink004) and is built "dyn" way, then
it has it's code compiled and linked into the DLL, which GHCi linker picks
when loading the package's code (see the big comment in the beginning of
`locateLib`).
When loading DLLs, GHCi linker simply calls the system's `dlopen` or
`LoadLibrary` APIs. This is quite different from the case when GHCi linker
loads an object file or static library. When loading an object file or static
library GHCi linker parses them and resolves all symbols "manually".
These object file or static library may reference some external symbols
defined in some external DLLs. And GHCi should know which these
external DLLs are.
But when GHCi loads a DLL, it's the *system* linker who manages all
the necessary dependencies, and it is able to load this DLL not having
any extra info. Thus we don't *have to* crash in this case even if we
are unable to load any supposed dependencies explicitly.
Suppose during GHCi session a client of the package wants to
`foreign import` a symbol which isn't exposed by the package DLL, but
is exposed by such an external (dependency) DLL.
If the DLL isn't *explicitly* loaded because `load_dyn` failed to do
this, then the client code eventually crashes because the GHCi linker
isn't able to locate this symbol (GHCi linker maintains a list of
explicitly loaded DLLs it looks into when trying to find a symbol).
This is why we still should try to load all the dependency DLLs
even though we know that the system linker loads them implicitly when
loading the package DLL.
Why we still keep the `crash_early` opportunity then not allowing such
a permissive behaviour for any DLLs? Well, we, perhaps, improve a user
experience in some cases slightly.
But if it happens there exist other corner cases where our current
usage of `crash_early` flag is overly restrictive, we may lift the
restriction very easily.
-}-- we have already searched the filesystem; the strings passed to load_dyn-- can be passed directly to loadDLL. They are either fully-qualified-- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so"). In the latter case,-- loadDLL is going to search the system paths to find the library.load_dyn::HscEnv ->Bool->FilePath->IO()load_dyn hsc_env crash_early dll =dor <-loadDLL hsc_env dll caser ofNothing->return()Justerr ->ifcrash_early thencmdLineErrorIO err elseletdflags =hsc_dflagshsc_env inwhen(wopt Opt_WarnMissedExtraSharedLib dflags )$putLogMsg dflags (Reason Opt_WarnMissedExtraSharedLib )SevWarning noSrcSpan (defaultUserStyle dflags )(note err )wherenote err =vcat $maptext [err ,"It's OK if you don't want to use symbols from it directly.","(the package DLL is loaded by the system linker"," which manages dependencies by itself)."]loadFrameworks::HscEnv ->Platform ->PackageConfig ->IO()loadFrameworks hsc_env platform pkg =when(platformUsesFrameworks platform )$mapM_load frameworks wherefw_dirs =Packages.frameworkDirspkg frameworks =Packages.frameworkspkg load fw =dor <-loadFramework hsc_env fw_dirs fw caser ofNothing->return()Justerr ->cmdLineErrorIO ("can't load framework: "++fw ++" ("++err ++")")-- Try to find an object file for a given library in the given paths.-- If it isn't present, we assume that addDLL in the RTS can find it,-- which generally means that it should be a dynamic library in the-- standard system search path.-- For GHCi we tend to prefer dynamic libraries over static ones as-- they are easier to load and manage, have less overhead.locateLib::HscEnv ->Bool->[FilePath]->[FilePath]->String->IOLibrarySpec locateLib hsc_env is_hs lib_dirs gcc_dirs lib |notis_hs -- For non-Haskell libraries (e.g. gmp, iconv):-- first look in library-dirs for a dynamic library (on User paths only)-- (libfoo.so)-- then try looking for import libraries on Windows (on User paths only)-- (.dll.a, .lib)-- first look in library-dirs for a dynamic library (on GCC paths only)-- (libfoo.so)-- then check for system dynamic libraries (e.g. kernel32.dll on windows)-- then try looking for import libraries on Windows (on GCC paths only)-- (.dll.a, .lib)-- then look in library-dirs for a static library (libfoo.a)-- then look in library-dirs and inplace GCC for a dynamic library (libfoo.so)-- then try looking for import libraries on Windows (.dll.a, .lib)-- then look in library-dirs and inplace GCC for a static library (libfoo.a)-- then try "gcc --print-file-name" to search gcc's search path-- for a dynamic library (#5289)-- otherwise, assume loadDLL can find it---- The logic is a bit complicated, but the rationale behind it is that-- loading a shared library for us is O(1) while loading an archive is-- O(n). Loading an import library is also O(n) so in general we prefer-- shared libraries because they are simpler and faster.--=findDll user `orElse `tryImpLib user `orElse `findDll gcc `orElse `findSysDll `orElse `tryImpLib gcc `orElse `findArchive `orElse `tryGcc `orElse `assumeDll |loading_dynamic_hs_libs -- search for .so libraries first.=findHSDll `orElse `findDynObject `orElse `assumeDll |otherwise-- use HSfoo.{o,p_o} if it exists, otherwise fallback to libHSfoo{,_p}.a=findObject `orElse `findArchive `orElse `assumeDll wheredflags =hsc_dflagshsc_env dirs =lib_dirs ++gcc_dirs gcc =Falseuser =Trueobj_file |is_hs &&loading_profiled_hs_libs =lib <.>"p_o"|otherwise=lib <.>"o"dyn_obj_file =lib <.>"dyn_o"arch_files =["lib"++lib ++lib_tag <.>"a",lib <.>"a"-- native code has no lib_tag,"lib"++lib ,lib ]lib_tag =ifis_hs &&loading_profiled_hs_libs then"_p"else""loading_profiled_hs_libs =interpreterProfiled dflags loading_dynamic_hs_libs =interpreterDynamic dflags import_libs =[lib <.>"lib","lib"++lib <.>"lib","lib"++lib <.>"dll.a",lib <.>"dll.a"]hs_dyn_lib_name =lib ++'-':programName dflags ++projectVersion dflags hs_dyn_lib_file =mkHsSOName platform hs_dyn_lib_name so_name =mkSOName platform lib lib_so_name ="lib"++so_name dyn_lib_file =case(arch ,os )of(ArchX86_64 ,OSSolaris2 )->"64"</>so_name _->so_name findObject =liftM(fmapObject )$findFiledirs obj_file findDynObject =liftM(fmapObject )$findFiledirs dyn_obj_file findArchive =letlocal name =liftM(fmapArchive )$findFiledirs name inapply (maplocal arch_files )findHSDll =liftM(fmapDLLPath )$findFiledirs hs_dyn_lib_file findDll re =letdirs' =ifre ==user thenlib_dirs elsegcc_dirs inliftM(fmapDLLPath )$findFiledirs' dyn_lib_file findSysDll =fmap(fmap$DLL .dropExtension.takeFileName)$findSystemLibrary hsc_env so_name tryGcc =letsearch =searchForLibUsingGcc dflags dllpath =liftM(fmapDLLPath )short =dllpath $search so_name lib_dirs full =dllpath $search lib_so_name lib_dirs gcc name =liftM(fmapArchive )$search name lib_dirs files =import_libs ++arch_files inapply $short :full :mapgcc files tryImpLib re =caseos ofOSMinGW32 ->letdirs' =ifre ==user thenlib_dirs elsegcc_dirs implib name =liftM(fmapArchive )$findFiledirs' name inapply (mapimplib import_libs )_->returnNothingassumeDll =return(DLL lib )infixr`orElse`f `orElse `g =f >>=maybeg returnapply []=returnNothingapply(x :xs )=dox' <-x ifisJustx' thenreturnx' elseapply xs platform =targetPlatform dflags arch =platformArchplatform os =platformOSplatform searchForLibUsingGcc::DynFlags ->String->[FilePath]->IO(MaybeFilePath)searchForLibUsingGcc dflags so dirs =do-- GCC does not seem to extend the library search path (using -L) when using-- --print-file-name. So instead pass it a new base location.str <-askLd dflags (map(FileOption "-B")dirs ++[Option "--print-file-name",Option so ])letfile =caselinesstr of[]->""l :_->l if(file ==so )thenreturnNothingelsedob <-doesFileExistfile -- file could be a folder (see #16063)return(ifb thenJustfile elseNothing)-- | Retrieve the list of search directory GCC and the System use to find-- libraries and components. See Note [Fork/Exec Windows].getGCCPaths::DynFlags ->OS ->IO[FilePath]getGCCPaths dflags os =caseos ofOSMinGW32 ->dogcc_dirs <-getGccSearchDirectory dflags "libraries"sys_dirs <-getSystemDirectories return$nub$gcc_dirs ++sys_dirs _->return[]-- | Cache for the GCC search directories as this can't easily change-- during an invocation of GHC. (Maybe with some env. variable but we'll)-- deal with that highly unlikely scenario then.{-# NOINLINEgccSearchDirCache#-}gccSearchDirCache::IORef[(String,[String])]gccSearchDirCache =unsafePerformIO$newIORef[]-- Note [Fork/Exec Windows]-- ~~~~~~~~~~~~~~~~~~~~~~~~-- fork/exec is expensive on Windows, for each time we ask GCC for a library we-- have to eat the cost of af least 3 of these: gcc -> real_gcc -> cc1.-- So instead get a list of location that GCC would search and use findDirs-- which hopefully is written in an optimized mannor to take advantage of-- caching. At the very least we remove the overhead of the fork/exec and waits-- which dominate a large percentage of startup time on Windows.getGccSearchDirectory::DynFlags ->String->IO[FilePath]getGccSearchDirectory dflags key =docache <-readIORefgccSearchDirCache caselookupkey cache ofJustx ->returnx Nothing->dostr <-askLd dflags [Option "--print-search-dirs"]letline =dropWhileisSpacestr name =key ++": ="ifnullline thenreturn[]elsedoletval =split $find name line dirs <-filterMdoesDirectoryExistval modifyIORef'gccSearchDirCache ((key ,dirs ):)returnval wheresplit::FilePath->[FilePath]split r =casebreak(==';')r of(s ,[])->[s ](s ,(_:xs ))->s :split xs find::String->String->Stringfind r x =letlst =linesx val =filter(r `isPrefixOf`)lst inifnullval then[]elsecasebreak(=='=')(headval )of(_,[])->[](_,(_:xs ))->xs -- | Get a list of system search directories, this to alleviate pressure on-- the findSysDll function.getSystemDirectories::IO[FilePath]#if defined(mingw32_HOST_OS)
getSystemDirectories=fmap(:[])getSystemDirectory#else
getSystemDirectories =return[]#endif
-- | Merge the given list of paths with those in the environment variable-- given. If the variable does not exist then just return the identity.addEnvPaths::String->[String]->IO[String]addEnvPaths name list =do-- According to POSIX (chapter 8.3) a zero-length prefix means current-- working directory. Replace empty strings in the env variable with-- `working_dir` (see also #14695).working_dir <-getCurrentDirectoryvalues <-lookupEnvname casevalues ofNothing->returnlist Justarr ->return$list ++splitEnv working_dir arr wheresplitEnv::FilePath->String->[String]splitEnv working_dir value =casebreak(==envListSep )value of(x ,[])->[ifnullx thenworking_dir elsex ](x ,(_:xs ))->(ifnullx thenworking_dir elsex ):splitEnv working_dir xs #if defined(mingw32_HOST_OS)
envListSep=';'#else
envListSep =':'#endif
-- ------------------------------------------------------------------------------ Loading a dynamic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)-- Darwin / MacOS X only: load a framework-- a framework is a dynamic library packaged inside a directory of the same-- name. They are searched for in different paths than normal libraries.loadFramework::HscEnv ->[FilePath]->FilePath->IO(MaybeString)loadFramework hsc_env extraPaths rootname =do{either_dir <-tryIO getHomeDirectory;lethomeFrameworkPath =caseeither_dir ofLeft_->[]Rightdir ->[dir </>"Library/Frameworks"]ps =extraPaths ++homeFrameworkPath ++defaultFrameworkPaths ;mb_fwk <-findFileps fwk_file ;casemb_fwk ofJustfwk_path ->loadDLL hsc_env fwk_path Nothing->return(Just"not found")}-- Tried all our known library paths, but dlopen()-- has no built-in paths for frameworks: give upwherefwk_file =rootname <.>"framework"</>rootname -- sorry for the hardcoded paths, I hope they won't change anytime soon:defaultFrameworkPaths =["/Library/Frameworks","/System/Library/Frameworks"]{- **********************************************************************
 Helper functions
 ********************************************************************* -}maybePutStr::DynFlags ->String->IO()maybePutStr dflags s =when(verbositydflags >1)$putLogMsg dflags NoReason SevInteractive noSrcSpan (defaultUserStyle dflags )(text s )maybePutStrLn::DynFlags ->String->IO()maybePutStrLn dflags s =maybePutStr dflags (s ++"\n")

AltStyle によって変換されたページ (->オリジナル) /