{-# LANGUAGE CPP #-}
{-# LANGUAGE TupleSections, RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}

--
--  (c) The University of Glasgow 2002-2006

-- | The loader
--
-- This module deals with the top-level issues of dynamic linking (loading),
-- calling the object-code linker and the byte-code linker where necessary.
module GHC.Linker.Loader
   ( Loader (..)
   , LoaderState (..)
   , initLoaderState
   , uninitializedLoader
   , showLoaderState
   , getLoaderState
   -- * Load & Unload
   , loadExpr
   , loadDecls
   , loadPackages
   , loadModule
   , loadCmdLineLibs
   , loadName
   , unload
   -- * LoadedEnv
   , withExtendedLoadedEnv
   , extendLoadedEnv
   , deleteFromLoadedEnv
   )
where

import GHC.Prelude

import GHC.Settings

import GHC.Platform
import GHC.Platform.Ways

import GHC.Driver.Phases
import GHC.Driver.Env
import GHC.Driver.Session
import GHC.Driver.Ppr
import GHC.Driver.Config
import GHC.Driver.Config.Diagnostic
import GHC.Driver.Config.Finder

import GHC.Tc.Utils.Monad

import GHC.Runtime.Interpreter
import GHCi.RemoteTypes


import GHC.ByteCode.Linker
import GHC.ByteCode.Asm
import GHC.ByteCode.Types

import GHC.SysTools

import GHC.Types.Basic
import GHC.Types.Name
import GHC.Types.Name.Env
import GHC.Types.SrcLoc
import GHC.Types.Unique.DSet
import GHC.Types.Unique.DFM

import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.Panic.Plain
import GHC.Utils.Error
import GHC.Utils.Logger
import GHC.Utils.TmpFs

import GHC.Unit.Env
import GHC.Unit.Finder
import GHC.Unit.Module
import GHC.Unit.Module.ModIface
import GHC.Unit.Module.Deps
import GHC.Unit.Home.ModInfo
import GHC.Unit.State as Packages

import qualified GHC.Data.ShortText as ST
import qualified GHC.Data.Maybe as Maybes
import GHC.Data.FastString

import GHC.Linker.MacOS
import GHC.Linker.Dynamic
import GHC.Linker.Types

-- Standard libraries
import Control.Monad

import qualified Data.Set as Set
import qualified Data.Map as M
import Data.Char (isSpace)
import Data.IORef
import Data.List (intercalate, isPrefixOf, isSuffixOf, nub, partition)
import Data.Maybe
import Control.Concurrent.MVar
import qualified Control.Monad.Catch as MC

import System.FilePath
import System.Directory
import System.IO.Unsafe
import System.Environment (lookupEnv)

#if defined(mingw32_HOST_OS)
import System.Win32.Info (getSystemDirectory)
#endif

import GHC.Utils.Exception

import GHC.Unit.Module.Graph
import GHC.Types.SourceFile
import GHC.Utils.Misc
import GHC.Iface.Load
import GHC.Unit.Home
import Data.Either
import Control.Applicative

uninitialised :: a
uninitialised :: forall a. a
uninitialised = forall a. String -> a
panic String
"Loader not initialised"

modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp LoaderState -> IO LoaderState
f =
  forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ (Loader -> MVar (Maybe LoaderState)
loader_state (Interp -> Loader
interpLoader Interp
interp))
    (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. LoaderState -> IO LoaderState
f forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> Maybe a -> a
fromMaybe forall a. a
uninitialised)

modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
modifyLoaderState :: forall a. Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
modifyLoaderState Interp
interp LoaderState -> IO (LoaderState, a)
f =
  forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar (Loader -> MVar (Maybe LoaderState)
loader_state (Interp -> Loader
interpLoader Interp
interp))
    (forall {f :: * -> *} {t} {a} {b}.
Functor f =>
(t -> a) -> f (t, b) -> f (a, b)
fmapFst forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. LoaderState -> IO (LoaderState, a)
f forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> Maybe a -> a
fromMaybe forall a. a
uninitialised)
  where fmapFst :: (t -> a) -> f (t, b) -> f (a, b)
fmapFst t -> a
f = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(t
x, b
y) -> (t -> a
f t
x, b
y))

getLoaderState :: Interp -> IO (Maybe LoaderState)
getLoaderState :: Interp -> IO (Maybe LoaderState)
getLoaderState Interp
interp = forall a. MVar a -> IO a
readMVar (Loader -> MVar (Maybe LoaderState)
loader_state (Interp -> Loader
interpLoader Interp
interp))


emptyLoaderState :: LoaderState
emptyLoaderState :: LoaderState
emptyLoaderState = LoaderState
   { closure_env :: ClosureEnv
closure_env = forall a. NameEnv a
emptyNameEnv
   , itbl_env :: ItblEnv
itbl_env    = forall a. NameEnv a
emptyNameEnv
   , pkgs_loaded :: PkgsLoaded
pkgs_loaded = PkgsLoaded
init_pkgs
   , bcos_loaded :: LinkableSet
bcos_loaded = forall a. ModuleEnv a
emptyModuleEnv
   , objs_loaded :: LinkableSet
objs_loaded = forall a. ModuleEnv a
emptyModuleEnv
   , temp_sos :: [(String, String)]
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.
  where init_pkgs :: PkgsLoaded
init_pkgs = forall key elt. Uniquable key => key -> elt -> UniqDFM key elt
unitUDFM UnitId
rtsUnitId (UnitId
-> [LibrarySpec]
-> [LibrarySpec]
-> UniqDSet UnitId
-> LoadedPkgInfo
LoadedPkgInfo UnitId
rtsUnitId [] [] forall a. UniqDSet a
emptyUniqDSet)

extendLoadedEnv :: Interp -> [(Name,ForeignHValue)] -> IO ()
extendLoadedEnv :: Interp -> [(Name, ForeignHValue)] -> IO ()
extendLoadedEnv Interp
interp [(Name, ForeignHValue)]
new_bindings =
  Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp forall a b. (a -> b) -> a -> b
$ \pls :: LoaderState
pls@LoaderState{[(String, String)]
LinkableSet
PkgsLoaded
ItblEnv
ClosureEnv
temp_sos :: [(String, String)]
pkgs_loaded :: PkgsLoaded
objs_loaded :: LinkableSet
bcos_loaded :: LinkableSet
itbl_env :: ItblEnv
closure_env :: ClosureEnv
temp_sos :: LoaderState -> [(String, String)]
objs_loaded :: LoaderState -> LinkableSet
bcos_loaded :: LoaderState -> LinkableSet
pkgs_loaded :: LoaderState -> PkgsLoaded
itbl_env :: LoaderState -> ItblEnv
closure_env :: LoaderState -> ClosureEnv
..} -> do
    let new_ce :: ClosureEnv
new_ce = ClosureEnv -> [(Name, ForeignHValue)] -> ClosureEnv
extendClosureEnv ClosureEnv
closure_env [(Name, ForeignHValue)]
new_bindings
    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! LoaderState
pls{ closure_env :: ClosureEnv
closure_env = ClosureEnv
new_ce }
    -- strictness is important for not retaining old copies of the pls

deleteFromLoadedEnv :: Interp -> [Name] -> IO ()
deleteFromLoadedEnv :: Interp -> [Name] -> IO ()
deleteFromLoadedEnv Interp
interp [Name]
to_remove =
  Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls -> do
    let ce :: ClosureEnv
ce = LoaderState -> ClosureEnv
closure_env LoaderState
pls
    let new_ce :: ClosureEnv
new_ce = forall a. NameEnv a -> [Name] -> NameEnv a
delListFromNameEnv ClosureEnv
ce [Name]
to_remove
    forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls{ closure_env :: ClosureEnv
closure_env = ClosureEnv
new_ce }

-- | Load the module containing the given Name and get its associated 'HValue'.
--
-- Throws a 'ProgramError' if loading fails or the name cannot be found.
loadName :: Interp -> HscEnv -> Name -> IO (ForeignHValue, [Linkable], PkgsLoaded)
loadName :: Interp
-> HscEnv -> Name -> IO (ForeignHValue, [Linkable], PkgsLoaded)
loadName Interp
interp HscEnv
hsc_env Name
name = do
  Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env
  forall a. Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
modifyLoaderState Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls0 -> do
    (LoaderState
pls, [Linkable]
links, PkgsLoaded
pkgs) <- if Bool -> Bool
not (Name -> Bool
isExternalName Name
name)
       then forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls0, [], forall key elt. UniqDFM key elt
emptyUDFM)
       else do
         (LoaderState
pls', SuccessFlag
ok, [Linkable]
links, PkgsLoaded
pkgs) <- Interp
-> HscEnv
-> LoaderState
-> SrcSpan
-> [Module]
-> IO (LoaderState, SuccessFlag, [Linkable], PkgsLoaded)
loadDependencies Interp
interp HscEnv
hsc_env LoaderState
pls0 SrcSpan
noSrcSpan
                                      [HasDebugCallStack => Name -> Module
nameModule Name
name]
         if SuccessFlag -> Bool
failed SuccessFlag
ok
           then forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"")
           else forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls', [Linkable]
links, PkgsLoaded
pkgs)

    case forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv (LoaderState -> ClosureEnv
closure_env LoaderState
pls) Name
name of
      Just (Name
_,ForeignHValue
aa) -> forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls,(ForeignHValue
aa, [Linkable]
links, PkgsLoaded
pkgs))
      Maybe (Name, ForeignHValue)
Nothing     -> forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (Name -> Bool
isExternalName Name
name) (forall a. Outputable a => a -> SDoc
ppr Name
name) forall a b. (a -> b) -> a -> b
$
                     do let sym_to_find :: FastString
sym_to_find = Name -> String -> FastString
nameToCLabel Name
name String
"closure"
                        Maybe HValueRef
m <- Interp -> String -> IO (Maybe HValueRef)
lookupClosure Interp
interp (FastString -> String
unpackFS FastString
sym_to_find)
                        ForeignHValue
r <- case Maybe HValueRef
m of
                          Just HValueRef
hvref -> forall a. Interp -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue Interp
interp HValueRef
hvref
                          Maybe HValueRef
Nothing -> forall a. String -> String -> IO a
linkFail String
"GHC.Linker.Loader.loadName"
                                       (FastString -> String
unpackFS FastString
sym_to_find)
                        forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls,(ForeignHValue
r, [Linkable]
links, PkgsLoaded
pkgs))

loadDependencies
  :: Interp
  -> HscEnv
  -> LoaderState
  -> SrcSpan
  -> [Module]
  -> IO (LoaderState, SuccessFlag, [Linkable], PkgsLoaded) -- ^ returns the set of linkables required
loadDependencies :: Interp
-> HscEnv
-> LoaderState
-> SrcSpan
-> [Module]
-> IO (LoaderState, SuccessFlag, [Linkable], PkgsLoaded)
loadDependencies Interp
interp HscEnv
hsc_env LoaderState
pls SrcSpan
span [Module]
needed_mods = do
--   initLoaderState (hsc_dflags hsc_env) dl
   let dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_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 String
maybe_normal_osuf <- DynFlags -> Interp -> SrcSpan -> IO (Maybe String)
checkNonStdWay DynFlags
dflags Interp
interp SrcSpan
span

   -- Find what packages and linkables are required
   ([Linkable]
lnks, [Linkable]
all_lnks, [UnitId]
pkgs, UniqDSet UnitId
this_pkgs_needed)
      <- HscEnv
-> LoaderState
-> Maybe String
-> SrcSpan
-> [Module]
-> IO ([Linkable], [Linkable], [UnitId], UniqDSet UnitId)
getLinkDeps HscEnv
hsc_env LoaderState
pls
           Maybe String
maybe_normal_osuf SrcSpan
span [Module]
needed_mods

   -- Link the packages and modules required
   LoaderState
pls1 <- Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState
loadPackages' Interp
interp HscEnv
hsc_env [UnitId]
pkgs LoaderState
pls
   (LoaderState
pls2, SuccessFlag
succ) <- Interp
-> HscEnv
-> LoaderState
-> [Linkable]
-> IO (LoaderState, SuccessFlag)
loadModuleLinkables Interp
interp HscEnv
hsc_env LoaderState
pls1 [Linkable]
lnks
   let this_pkgs_loaded :: PkgsLoaded
this_pkgs_loaded = forall key elt elt2.
UniqDFM key elt -> UniqDFM key elt2 -> UniqDFM key elt
udfmRestrictKeys PkgsLoaded
all_pkgs_loaded forall a b. (a -> b) -> a -> b
$ forall a. UniqDSet a -> UniqDFM a a
getUniqDSet UniqDSet UnitId
trans_pkgs_needed
       all_pkgs_loaded :: PkgsLoaded
all_pkgs_loaded = LoaderState -> PkgsLoaded
pkgs_loaded LoaderState
pls2
       trans_pkgs_needed :: UniqDSet UnitId
trans_pkgs_needed = forall a. [UniqDSet a] -> UniqDSet a
unionManyUniqDSets (UniqDSet UnitId
this_pkgs_needed forall a. a -> [a] -> [a]
: [ LoadedPkgInfo -> UniqDSet UnitId
loaded_pkg_trans_deps LoadedPkgInfo
pkg
                                                                  | UnitId
pkg_id <- forall a. UniqDSet a -> [a]
uniqDSetToList UniqDSet UnitId
this_pkgs_needed
                                                                  , Just LoadedPkgInfo
pkg <- [forall key elt.
Uniquable key =>
UniqDFM key elt -> key -> Maybe elt
lookupUDFM PkgsLoaded
all_pkgs_loaded UnitId
pkg_id]
                                                                  ])
   forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls2, SuccessFlag
succ, [Linkable]
all_lnks, PkgsLoaded
this_pkgs_loaded)


-- | Temporarily extend the loaded env.
withExtendedLoadedEnv
  :: (ExceptionMonad m)
  => Interp
  -> [(Name,ForeignHValue)]
  -> m a
  -> m a
withExtendedLoadedEnv :: forall (m :: * -> *) a.
ExceptionMonad m =>
Interp -> [(Name, ForeignHValue)] -> m a -> m a
withExtendedLoadedEnv Interp
interp [(Name, ForeignHValue)]
new_env m a
action
    = forall (m :: * -> *) a c b.
MonadMask m =>
m a -> (a -> m c) -> (a -> m b) -> m b
MC.bracket (forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ Interp -> [(Name, ForeignHValue)] -> IO ()
extendLoadedEnv Interp
interp [(Name, ForeignHValue)]
new_env)
               (\()
_ -> m ()
reset_old_env)
               (\()
_ -> m a
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 :: m ()
reset_old_env = forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$
            Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls ->
                let cur :: ClosureEnv
cur = LoaderState -> ClosureEnv
closure_env LoaderState
pls
                    new :: ClosureEnv
new = forall a. NameEnv a -> [Name] -> NameEnv a
delListFromNameEnv ClosureEnv
cur (forall a b. (a -> b) -> [a] -> [b]
map forall a b. (a, b) -> a
fst [(Name, ForeignHValue)]
new_env)
                in forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls{ closure_env :: ClosureEnv
closure_env = ClosureEnv
new }


-- | Display the loader state.
showLoaderState :: Interp -> IO SDoc
showLoaderState :: Interp -> IO SDoc
showLoaderState Interp
interp = do
  Maybe LoaderState
ls <- forall a. MVar a -> IO a
readMVar (Loader -> MVar (Maybe LoaderState)
loader_state (Interp -> Loader
interpLoader Interp
interp))
  let docs :: [SDoc]
docs = case Maybe LoaderState
ls of
        Maybe LoaderState
Nothing  -> [ String -> SDoc
text String
"Loader not initialised"]
        Just LoaderState
pls -> [ String -> SDoc
text String
"Pkgs:" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr (forall a b. (a -> b) -> [a] -> [b]
map LoadedPkgInfo -> UnitId
loaded_pkg_uid forall a b. (a -> b) -> a -> b
$ forall key elt. UniqDFM key elt -> [elt]
eltsUDFM forall a b. (a -> b) -> a -> b
$ LoaderState -> PkgsLoaded
pkgs_loaded LoaderState
pls)
                    , String -> SDoc
text String
"Objs:" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr (forall a. ModuleEnv a -> [a]
moduleEnvElts forall a b. (a -> b) -> a -> b
$ LoaderState -> LinkableSet
objs_loaded LoaderState
pls)
                    , String -> SDoc
text String
"BCOs:" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr (forall a. ModuleEnv a -> [a]
moduleEnvElts forall a b. (a -> b) -> a -> b
$ LoaderState -> LinkableSet
bcos_loaded LoaderState
pls)
                    ]

  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultDumpStyle
         forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
vcat (String -> SDoc
text String
"----- Loader state -----"forall a. a -> [a] -> [a]
:[SDoc]
docs)


{- **********************************************************************

                        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.
--
initLoaderState :: Interp -> HscEnv -> IO ()
initLoaderState :: Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env = do
  forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ (Loader -> MVar (Maybe LoaderState)
loader_state (Interp -> Loader
interpLoader Interp
interp)) forall a b. (a -> b) -> a -> b
$ \Maybe LoaderState
pls -> do
    case Maybe LoaderState
pls of
      Just  LoaderState
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return Maybe LoaderState
pls
      Maybe LoaderState
Nothing -> forall a. a -> Maybe a
Just forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Interp -> HscEnv -> IO LoaderState
reallyInitLoaderState Interp
interp HscEnv
hsc_env

reallyInitLoaderState :: Interp -> HscEnv -> IO LoaderState
reallyInitLoaderState :: Interp -> HscEnv -> IO LoaderState
reallyInitLoaderState Interp
interp HscEnv
hsc_env = do
  -- Initialise the linker state
  let pls0 :: LoaderState
pls0 = LoaderState
emptyLoaderState

  -- (a) initialise the C dynamic linker
  Interp -> IO ()
initObjLinker Interp
interp


  -- (b) Load packages from the command-line (Note [preload packages])
  LoaderState
pls <- forall b a. (b -> UnitId -> a -> b) -> b -> UnitEnvGraph a -> b
unitEnv_foldWithKey (\IO LoaderState
k UnitId
u HomeUnitEnv
env -> IO LoaderState
k forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \LoaderState
pls' -> Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState
loadPackages' Interp
interp (HasDebugCallStack => UnitId -> HscEnv -> HscEnv
hscSetActiveUnitId UnitId
u HscEnv
hsc_env) (UnitState -> [UnitId]
preloadUnits (HomeUnitEnv -> UnitState
homeUnitEnv_units HomeUnitEnv
env)) LoaderState
pls') (forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls0) (HscEnv -> HomeUnitGraph
hsc_HUG HscEnv
hsc_env)

  -- steps (c), (d) and (e)
  Interp -> HscEnv -> LoaderState -> IO LoaderState
loadCmdLineLibs' Interp
interp HscEnv
hsc_env LoaderState
pls


loadCmdLineLibs :: Interp -> HscEnv -> IO ()
loadCmdLineLibs :: Interp -> HscEnv -> IO ()
loadCmdLineLibs Interp
interp HscEnv
hsc_env = do
  Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env
  Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls ->
    Interp -> HscEnv -> LoaderState -> IO LoaderState
loadCmdLineLibs' Interp
interp HscEnv
hsc_env LoaderState
pls


loadCmdLineLibs' :: Interp -> HscEnv -> LoaderState -> IO LoaderState
loadCmdLineLibs' :: Interp -> HscEnv -> LoaderState -> IO LoaderState
loadCmdLineLibs' Interp
interp HscEnv
hsc_env LoaderState
pls = forall a b. (a, b) -> b
snd forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
    forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM
      (\(Set UnitId
done', LoaderState
pls') UnitId
cur_uid ->  Set UnitId -> UnitId -> LoaderState -> IO (Set UnitId, LoaderState)
load Set UnitId
done' UnitId
cur_uid LoaderState
pls')
      (forall a. Set a
Set.empty, LoaderState
pls)
      (HscEnv -> Set UnitId
hsc_all_home_unit_ids HscEnv
hsc_env)

  where
    load :: Set.Set UnitId -> UnitId -> LoaderState -> IO (Set.Set UnitId, LoaderState)
    load :: Set UnitId -> UnitId -> LoaderState -> IO (Set UnitId, LoaderState)
load Set UnitId
done UnitId
uid LoaderState
pls | UnitId
uid forall a. Ord a => a -> Set a -> Bool
`Set.member` Set UnitId
done = forall (m :: * -> *) a. Monad m => a -> m a
return (Set UnitId
done, LoaderState
pls)
    load Set UnitId
done UnitId
uid LoaderState
pls = do
      let hsc' :: HscEnv
hsc' = HasDebugCallStack => UnitId -> HscEnv -> HscEnv
hscSetActiveUnitId UnitId
uid HscEnv
hsc_env
      -- Load potential dependencies first
      (Set UnitId
done', LoaderState
pls') <- forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (\(Set UnitId
done', LoaderState
pls') UnitId
uid -> Set UnitId -> UnitId -> LoaderState -> IO (Set UnitId, LoaderState)
load Set UnitId
done' UnitId
uid LoaderState
pls') (Set UnitId
done, LoaderState
pls)
                          (UnitState -> [UnitId]
homeUnitDepends (HasDebugCallStack => HscEnv -> UnitState
hsc_units HscEnv
hsc'))
      LoaderState
pls'' <- Interp -> HscEnv -> LoaderState -> IO LoaderState
loadCmdLineLibs'' Interp
interp HscEnv
hsc' LoaderState
pls'
      forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ (forall a. Ord a => a -> Set a -> Set a
Set.insert UnitId
uid Set UnitId
done', LoaderState
pls'')

loadCmdLineLibs''
  :: Interp
  -> HscEnv
  -> LoaderState
  -> IO LoaderState
loadCmdLineLibs'' :: Interp -> HscEnv -> LoaderState -> IO LoaderState
loadCmdLineLibs'' Interp
interp HscEnv
hsc_env LoaderState
pls =
  do

      let dflags :: DynFlags
dflags@(DynFlags { ldInputs :: DynFlags -> [Option]
ldInputs = [Option]
cmdline_ld_inputs
                           , libraryPaths :: DynFlags -> [String]
libraryPaths = [String]
lib_paths_base})
            = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
      let logger :: Logger
logger = HscEnv -> Logger
hsc_logger HscEnv
hsc_env

      -- (c) Link libraries from the command-line
      let minus_ls_1 :: [String]
minus_ls_1 = [ String
lib | Option (Char
'-':Char
'l':String
lib) <- [Option]
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 #13210.
      let platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
          os :: OS
os       = Platform -> OS
platformOS Platform
platform
          minus_ls :: [String]
minus_ls = case OS
os of
                       OS
OSMinGW32 -> String
"pthread" forall a. a -> [a] -> [a]
: [String]
minus_ls_1
                       OS
_         -> [String]
minus_ls_1
      -- See Note [Fork/Exec Windows]
      [String]
gcc_paths <- Logger -> DynFlags -> OS -> IO [String]
getGCCPaths Logger
logger DynFlags
dflags OS
os

      [String]
lib_paths_env <- String -> [String] -> IO [String]
addEnvPaths String
"LIBRARY_PATH" [String]
lib_paths_base

      Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"Search directories (user):"
      Logger -> String -> IO ()
maybePutStr Logger
logger ([String] -> String
unlines forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map (String
"  "forall a. [a] -> [a] -> [a]
++) [String]
lib_paths_env)
      Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"Search directories (gcc):"
      Logger -> String -> IO ()
maybePutStr Logger
logger ([String] -> String
unlines forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map (String
"  "forall a. [a] -> [a] -> [a]
++) [String]
gcc_paths)

      [LibrarySpec]
libspecs
        <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Interp
-> HscEnv
-> Bool
-> [String]
-> [String]
-> String
-> IO LibrarySpec
locateLib Interp
interp HscEnv
hsc_env Bool
False [String]
lib_paths_env [String]
gcc_paths) [String]
minus_ls

      -- (d) Link .o files from the command-line
      [Maybe LibrarySpec]
classified_ld_inputs <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Logger -> Platform -> String -> IO (Maybe LibrarySpec)
classifyLdInput Logger
logger Platform
platform)
                                [ String
f | FileOption String
_ String
f <- [Option]
cmdline_ld_inputs ]

      -- (e) Link any MacOS frameworks
      let platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
      let ([String]
framework_paths, [String]
frameworks) =
            if Platform -> Bool
platformUsesFrameworks Platform
platform
             then (DynFlags -> [String]
frameworkPaths DynFlags
dflags, DynFlags -> [String]
cmdlineFrameworks DynFlags
dflags)
              else ([],[])

      -- Finally do (c),(d),(e)
      let cmdline_lib_specs :: [LibrarySpec]
cmdline_lib_specs = forall a. [Maybe a] -> [a]
catMaybes [Maybe LibrarySpec]
classified_ld_inputs
                           forall a. [a] -> [a] -> [a]
++ [LibrarySpec]
libspecs
                           forall a. [a] -> [a] -> [a]
++ forall a b. (a -> b) -> [a] -> [b]
map String -> LibrarySpec
Framework [String]
frameworks
      if forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LibrarySpec]
cmdline_lib_specs
         then forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls
         else do
           -- Add directories to library search paths, this only has an effect
           -- on Windows. On Unix OSes this function is a NOP.
           let all_paths :: [String]
all_paths = let paths :: [String]
paths = String -> String
takeDirectory (DynFlags -> String
pgm_c DynFlags
dflags)
                                     forall a. a -> [a] -> [a]
: [String]
framework_paths
                                    forall a. [a] -> [a] -> [a]
++ [String]
lib_paths_base
                                    forall a. [a] -> [a] -> [a]
++ [ String -> String
takeDirectory String
dll | DLLPath String
dll <- [LibrarySpec]
libspecs ]
                           in forall a. Eq a => [a] -> [a]
nub forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map String -> String
normalise [String]
paths
           let lib_paths :: [String]
lib_paths = forall a. Eq a => [a] -> [a]
nub forall a b. (a -> b) -> a -> b
$ [String]
lib_paths_base forall a. [a] -> [a] -> [a]
++ [String]
gcc_paths
           [String]
all_paths_env <- String -> [String] -> IO [String]
addEnvPaths String
"LD_LIBRARY_PATH" [String]
all_paths
           [Ptr ()]
pathCache <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Interp -> String -> IO (Ptr ())
addLibrarySearchPath Interp
interp) [String]
all_paths_env

           let merged_specs :: [LibrarySpec]
merged_specs = [LibrarySpec] -> [LibrarySpec]
mergeStaticObjects [LibrarySpec]
cmdline_lib_specs
           LoaderState
pls1 <- forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (Interp
-> HscEnv
-> [String]
-> [String]
-> LoaderState
-> LibrarySpec
-> IO LoaderState
preloadLib Interp
interp HscEnv
hsc_env [String]
lib_paths [String]
framework_paths) LoaderState
pls
                         [LibrarySpec]
merged_specs

           Logger -> String -> IO ()
maybePutStr Logger
logger String
"final link ... "
           SuccessFlag
ok <- Interp -> IO SuccessFlag
resolveObjs Interp
interp

           -- DLLs are loaded, reset the search paths
           forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> Ptr () -> IO Bool
removeLibrarySearchPath Interp
interp) forall a b. (a -> b) -> a -> b
$ forall a. [a] -> [a]
reverse [Ptr ()]
pathCache

           if SuccessFlag -> Bool
succeeded SuccessFlag
ok then Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"done"
           else forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"linking extra libraries/objects failed")

           forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls1

-- | Merge runs of consecutive of 'Objects'. This allows for resolution of
-- cyclic symbol references when dynamically linking. Specifically, we link
-- together all of the static objects into a single shared object, avoiding
-- the issue we saw in #13786.
mergeStaticObjects :: [LibrarySpec] -> [LibrarySpec]
mergeStaticObjects :: [LibrarySpec] -> [LibrarySpec]
mergeStaticObjects [LibrarySpec]
specs = [String] -> [LibrarySpec] -> [LibrarySpec]
go [] [LibrarySpec]
specs
  where
    go :: [FilePath] -> [LibrarySpec] -> [LibrarySpec]
    go :: [String] -> [LibrarySpec] -> [LibrarySpec]
go [String]
accum (Objects [String]
objs : [LibrarySpec]
rest) = [String] -> [LibrarySpec] -> [LibrarySpec]
go ([String]
objs forall a. [a] -> [a] -> [a]
++ [String]
accum) [LibrarySpec]
rest
    go accum :: [String]
accum@(String
_:[String]
_) [LibrarySpec]
rest = [String] -> LibrarySpec
Objects (forall a. [a] -> [a]
reverse [String]
accum) forall a. a -> [a] -> [a]
: [String] -> [LibrarySpec] -> [LibrarySpec]
go [] [LibrarySpec]
rest
    go [] (LibrarySpec
spec:[LibrarySpec]
rest) = LibrarySpec
spec forall a. a -> [a] -> [a]
: [String] -> [LibrarySpec] -> [LibrarySpec]
go [] [LibrarySpec]
rest
    go [] [] = []

{- 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 :: Logger -> Platform -> FilePath -> IO (Maybe LibrarySpec)
classifyLdInput :: Logger -> Platform -> String -> IO (Maybe LibrarySpec)
classifyLdInput Logger
logger Platform
platform String
f
  | Platform -> String -> Bool
isObjectFilename Platform
platform String
f = forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> Maybe a
Just ([String] -> LibrarySpec
Objects [String
f]))
  | Platform -> String -> Bool
isDynLibFilename Platform
platform String
f = forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> Maybe a
Just (String -> LibrarySpec
DLLPath String
f))
  | Bool
otherwise          = do
        Logger -> MessageClass -> SrcSpan -> SDoc -> IO ()
logMsg Logger
logger MessageClass
MCInfo SrcSpan
noSrcSpan
            forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultUserStyle
            (String -> SDoc
text (String
"Warning: ignoring unrecognised input `" forall a. [a] -> [a] -> [a]
++ String
f forall a. [a] -> [a] -> [a]
++ String
"'"))
        forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing

preloadLib
  :: Interp
  -> HscEnv
  -> [String]
  -> [String]
  -> LoaderState
  -> LibrarySpec
  -> IO LoaderState
preloadLib :: Interp
-> HscEnv
-> [String]
-> [String]
-> LoaderState
-> LibrarySpec
-> IO LoaderState
preloadLib Interp
interp HscEnv
hsc_env [String]
lib_paths [String]
framework_paths LoaderState
pls LibrarySpec
lib_spec = do
  Logger -> String -> IO ()
maybePutStr Logger
logger (String
"Loading object " forall a. [a] -> [a] -> [a]
++ LibrarySpec -> String
showLS LibrarySpec
lib_spec forall a. [a] -> [a] -> [a]
++ String
" ... ")
  case LibrarySpec
lib_spec of
    Objects [String]
static_ishs -> do
      (Bool
b, LoaderState
pls1) <- [String] -> [String] -> IO (Bool, LoaderState)
preload_statics [String]
lib_paths [String]
static_ishs
      Logger -> String -> IO ()
maybePutStrLn Logger
logger (if Bool
b  then String
"done" else String
"not found")
      forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls1

    Archive String
static_ish -> do
      Bool
b <- [String] -> String -> IO Bool
preload_static_archive [String]
lib_paths String
static_ish
      Logger -> String -> IO ()
maybePutStrLn Logger
logger (if Bool
b  then String
"done" else String
"not found")
      forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls

    DLL String
dll_unadorned -> do
      Maybe String
maybe_errstr <- Interp -> String -> IO (Maybe String)
loadDLL Interp
interp (Platform -> String -> String
platformSOName Platform
platform String
dll_unadorned)
      case Maybe String
maybe_errstr of
         Maybe String
Nothing -> Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"done"
         Just String
mm | Platform -> OS
platformOS Platform
platform forall a. Eq a => a -> a -> Bool
/= OS
OSDarwin ->
           String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
mm [String]
lib_paths LibrarySpec
lib_spec
         Just String
mm | Bool
otherwise -> do
           -- As a backup, on Darwin, try to also load a .so file
           -- since (apparently) some things install that way - see
           -- ticket #8770.
           let libfile :: String
libfile = (String
"lib" forall a. [a] -> [a] -> [a]
++ String
dll_unadorned) String -> String -> String
<.> String
"so"
           Maybe String
err2 <- Interp -> String -> IO (Maybe String)
loadDLL Interp
interp String
libfile
           case Maybe String
err2 of
             Maybe String
Nothing -> Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"done"
             Just String
_  -> String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
mm [String]
lib_paths LibrarySpec
lib_spec
      forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls

    DLLPath String
dll_path -> do
      do Maybe String
maybe_errstr <- Interp -> String -> IO (Maybe String)
loadDLL Interp
interp String
dll_path
         case Maybe String
maybe_errstr of
            Maybe String
Nothing -> Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"done"
            Just String
mm -> String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
mm [String]
lib_paths LibrarySpec
lib_spec
         forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls

    Framework String
framework ->
      if Platform -> Bool
platformUsesFrameworks (DynFlags -> Platform
targetPlatform DynFlags
dflags)
      then do Maybe String
maybe_errstr <- Interp -> [String] -> String -> IO (Maybe String)
loadFramework Interp
interp [String]
framework_paths String
framework
              case Maybe String
maybe_errstr of
                 Maybe String
Nothing -> Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"done"
                 Just String
mm -> String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
mm [String]
framework_paths LibrarySpec
lib_spec
              forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls
      else forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"preloadLib Framework")

  where
    dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
    logger :: Logger
logger = HscEnv -> Logger
hsc_logger HscEnv
hsc_env

    platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags

    preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
    preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
sys_errmsg [String]
paths LibrarySpec
spec
       = do Logger -> String -> IO ()
maybePutStr Logger
logger String
"failed.\n"
            forall a. GhcException -> IO a
throwGhcExceptionIO forall a b. (a -> b) -> a -> b
$
              String -> GhcException
CmdLineError (
                    String
"user specified .o/.so/.DLL could not be loaded ("
                    forall a. [a] -> [a] -> [a]
++ String
sys_errmsg forall a. [a] -> [a] -> [a]
++ String
")\nWhilst trying to load:  "
                    forall a. [a] -> [a] -> [a]
++ LibrarySpec -> String
showLS LibrarySpec
spec forall a. [a] -> [a] -> [a]
++ String
"\nAdditional directories searched:"
                    forall a. [a] -> [a] -> [a]
++ (if forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
paths then String
" (none)" else
                        forall a. [a] -> [[a]] -> [a]
intercalate String
"\n" (forall a b. (a -> b) -> [a] -> [b]
map (String
"   "forall a. [a] -> [a] -> [a]
++) [String]
paths)))

    -- Not interested in the paths in the static case.
    preload_statics :: [String] -> [String] -> IO (Bool, LoaderState)
preload_statics [String]
_paths [String]
names
       = do Bool
b <- forall (t :: * -> *). Foldable t => t Bool -> Bool
or forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM String -> IO Bool
doesFileExist [String]
names
            if Bool -> Bool
not Bool
b then forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
False, LoaderState
pls)
                     else if Bool
hostIsDynamic
                             then  do LoaderState
pls1 <- Interp -> HscEnv -> LoaderState -> [String] -> IO LoaderState
dynLoadObjs Interp
interp HscEnv
hsc_env LoaderState
pls [String]
names
                                      forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, LoaderState
pls1)
                             else  do forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> String -> IO ()
loadObj Interp
interp) [String]
names
                                      forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, LoaderState
pls)

    preload_static_archive :: [String] -> String -> IO Bool
preload_static_archive [String]
_paths String
name
       = do Bool
b <- String -> IO Bool
doesFileExist String
name
            if Bool -> Bool
not Bool
b then forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
                     else do if Bool
hostIsDynamic
                                 then forall a. GhcException -> IO a
throwGhcExceptionIO forall a b. (a -> b) -> a -> b
$
                                      String -> GhcException
CmdLineError String
dynamic_msg
                                 else Interp -> String -> IO ()
loadArchive Interp
interp String
name
                             forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
      where
        dynamic_msg :: String
dynamic_msg = [String] -> String
unlines
          [ String
"User-specified static library could not be loaded ("
            forall a. [a] -> [a] -> [a]
++ String
name forall a. [a] -> [a] -> [a]
++ String
")"
          , String
"Loading static libraries is not supported in this configuration."
          , String
"Try using a dynamic library instead."
          ]


{- **********************************************************************

                        Link a byte-code expression

  ********************************************************************* -}

-- | Load a single expression, /including/ first loading 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 load.
--
loadExpr :: Interp -> HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
loadExpr :: Interp -> HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
loadExpr Interp
interp HscEnv
hsc_env SrcSpan
span UnlinkedBCO
root_ul_bco = do
  -- Initialise the linker (if it's not been done already)
  Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env

  -- Take lock for the actual work.
  forall a. Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
modifyLoaderState Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls0 -> do
    -- Load the packages and modules required
    (LoaderState
pls, SuccessFlag
ok, [Linkable]
_, PkgsLoaded
_) <- Interp
-> HscEnv
-> LoaderState
-> SrcSpan
-> [Module]
-> IO (LoaderState, SuccessFlag, [Linkable], PkgsLoaded)
loadDependencies Interp
interp HscEnv
hsc_env LoaderState
pls0 SrcSpan
span [Module]
needed_mods
    if SuccessFlag -> Bool
failed SuccessFlag
ok
      then forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"")
      else do
        -- Load the expression itself
        let ie :: ItblEnv
ie = LoaderState -> ItblEnv
itbl_env LoaderState
pls
            ce :: ClosureEnv
ce = LoaderState -> ClosureEnv
closure_env LoaderState
pls

        -- Load the necessary packages and linkables
        let nobreakarray :: a
nobreakarray = forall a. HasCallStack => String -> a
error String
"no break array"
            bco_ix :: NameEnv Int
bco_ix = forall a. [(Name, a)] -> NameEnv a
mkNameEnv [(UnlinkedBCO -> Name
unlinkedBCOName UnlinkedBCO
root_ul_bco, Int
0)]
        ResolvedBCO
resolved <- Interp
-> ItblEnv
-> ClosureEnv
-> NameEnv Int
-> RemoteRef BreakArray
-> UnlinkedBCO
-> IO ResolvedBCO
linkBCO Interp
interp ItblEnv
ie ClosureEnv
ce NameEnv Int
bco_ix forall a. a
nobreakarray UnlinkedBCO
root_ul_bco
        BCOOpts
bco_opts <- DynFlags -> IO BCOOpts
initBCOOpts (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env)
        [HValueRef
root_hvref] <- Interp -> BCOOpts -> [ResolvedBCO] -> IO [HValueRef]
createBCOs Interp
interp BCOOpts
bco_opts [ResolvedBCO
resolved]
        ForeignHValue
fhv <- forall a. Interp -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue Interp
interp HValueRef
root_hvref
        forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls, ForeignHValue
fhv)
  where
     free_names :: [Name]
free_names = forall a. UniqDSet a -> [a]
uniqDSetToList (UnlinkedBCO -> UniqDSet Name
bcoFreeNames UnlinkedBCO
root_ul_bco)

     needed_mods :: [Module]
     needed_mods :: [Module]
needed_mods = [ HasDebugCallStack => Name -> Module
nameModule Name
n | Name
n <- [Name]
free_names,
                     Name -> Bool
isExternalName Name
n,      -- Names from other modules
                     Bool -> Bool
not (Name -> Bool
isWiredInName Name
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 -> SDoc -> IO a
dieWith :: forall a. DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
span SDoc
msg = forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags (MessageClass -> SrcSpan -> SDoc -> SDoc
mkLocMessage MessageClass
MCFatal SrcSpan
span SDoc
msg)))


checkNonStdWay :: DynFlags -> Interp -> SrcSpan -> IO (Maybe FilePath)
checkNonStdWay :: DynFlags -> Interp -> SrcSpan -> IO (Maybe String)
checkNonStdWay DynFlags
_dflags Interp
interp SrcSpan
_srcspan
  | ExternalInterp {} <- Interp -> InterpInstance
interpInstance Interp
interp = forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
    -- 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.

-- #if-guard the following equations otherwise the pattern match checker will
-- complain that they are redundant.
#if defined(HAVE_INTERNAL_INTERPRETER)
checkNonStdWay dflags _interp srcspan
  | hostFullWays == targetFullWays = return Nothing
    -- Only if we are compiling with the same ways as GHC is built
    -- with, can we dynamically load those object files. (see #3604)

  | objectSuf_ dflags == normalObjectSuffix && not (null targetFullWays)
  = failNonStd dflags srcspan

  | otherwise = return (Just (hostWayTag ++ "o"))
  where
    targetFullWays = fullWays (ways dflags)
    hostWayTag = case waysTag hostFullWays of
                  "" -> ""
                  tag -> tag ++ "_"

    normalObjectSuffix :: String
    normalObjectSuffix = phaseInputExt StopLn

data Way' = Normal | Prof | Dyn

failNonStd :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
failNonStd dflags srcspan = dieWith dflags srcspan $
  text "Cannot load" <+> pprWay' compWay <+>
     text "objects when GHC is built" <+> pprWay' ghciWay $$
  text "To fix this, either:" $$
  text "  (1) Use -fexternal-interpreter, or" $$
  buildTwiceMsg
    where compWay
            | ways dflags `hasWay` WayDyn  = Dyn
            | ways dflags `hasWay` WayProf = Prof
            | otherwise = Normal
          ghciWay
            | hostIsDynamic = Dyn
            | hostIsProfiled = Prof
            | otherwise = Normal
          buildTwiceMsg = case (ghciWay, compWay) of
            (Normal, Dyn) -> dynamicTooMsg
            (Dyn, Normal) -> dynamicTooMsg
            _ ->
              text "  (2) Build the program twice: once" <+>
                pprWay' ghciWay <> text ", and then" $$
              text "      " <> pprWay' compWay <+>
                text "using -osuf to set a different object file suffix."
          dynamicTooMsg = text "  (2) Use -dynamic-too," <+>
            text "and use -osuf and -dynosuf to set object file suffixes as needed."
          pprWay' :: Way' -> SDoc
          pprWay' way = text $ case way of
            Normal -> "the normal way"
            Prof -> "with -prof"
            Dyn -> "with -dynamic"
#endif

getLinkDeps :: HscEnv
            -> LoaderState
            -> Maybe FilePath                   -- replace object suffixes?
            -> SrcSpan                          -- for error messages
            -> [Module]                         -- If you need these
            -> IO ([Linkable], [Linkable], [UnitId], UniqDSet UnitId)     -- ... then link these first
            -- The module and package dependencies for the needed modules are returned.
            -- See Note [Object File Dependencies]
-- Fails with an IO exception if it can't find enough files

getLinkDeps :: HscEnv
-> LoaderState
-> Maybe String
-> SrcSpan
-> [Module]
-> IO ([Linkable], [Linkable], [UnitId], UniqDSet UnitId)
getLinkDeps HscEnv
hsc_env LoaderState
pls Maybe String
replace_osuf SrcSpan
span [Module]
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)
      ; ([Module]
mods_s, UniqDSet UnitId
pkgs_s) <-
          -- Why two code paths here? There is a significant amount of repeated work
          -- performed calculating transitive dependencies
          -- if --make uses the oneShot code path (see MultiLayerModulesTH_* tests)
          if GhcMode -> Bool
isOneShot (DynFlags -> GhcMode
ghcMode DynFlags
dflags)
            then [Module]
-> UniqDSet Module
-> UniqDSet UnitId
-> IO ([Module], UniqDSet UnitId)
follow_deps (forall a. (a -> Bool) -> [a] -> [a]
filterOut Module -> Bool
isInteractiveModule [Module]
mods)
                              forall a. UniqDSet a
emptyUniqDSet forall a. UniqDSet a
emptyUniqDSet;
            else do
              ([UniqDSet UnitId]
pkgs, [Maybe Module]
mmods) <- forall a b. [(a, b)] -> ([a], [b])
unzip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ModNodeKeyWithUid -> IO (UniqDSet UnitId, Maybe Module)
get_mod_info [ModNodeKeyWithUid]
all_home_mods
              forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. [Maybe a] -> [a]
catMaybes [Maybe Module]
mmods, forall a. [UniqDSet a] -> UniqDSet a
unionManyUniqDSets (UniqDSet UnitId
init_pkg_set forall a. a -> [a] -> [a]
: [UniqDSet UnitId]
pkgs))

      ; let
        -- 2.  Exclude ones already linked
        --      Main reason: avoid findModule calls in get_linkable
            ([Module]
mods_needed, [Linkable]
links_got) = forall a b. [Either a b] -> ([a], [b])
partitionEithers (forall a b. (a -> b) -> [a] -> [b]
map Module -> Either Module Linkable
split_mods [Module]
mods_s)
            pkgs_needed :: [UnitId]
pkgs_needed = forall key elt. UniqDFM key elt -> [elt]
eltsUDFM forall a b. (a -> b) -> a -> b
$ forall a. UniqDSet a -> UniqDFM a a
getUniqDSet UniqDSet UnitId
pkgs_s forall key elt elt2.
UniqDFM key elt -> UniqDFM key elt2 -> UniqDFM key elt
`minusUDFM` LoaderState -> PkgsLoaded
pkgs_loaded LoaderState
pls

            split_mods :: Module -> Either Module Linkable
split_mods Module
mod =
                let is_linked :: Maybe Linkable
is_linked = LinkableSet -> Module -> Maybe Linkable
findModuleLinkable_maybe (LoaderState -> LinkableSet
objs_loaded LoaderState
pls) Module
mod forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> LinkableSet -> Module -> Maybe Linkable
findModuleLinkable_maybe (LoaderState -> LinkableSet
bcos_loaded LoaderState
pls) Module
mod
                in case Maybe Linkable
is_linked of
                     Just Linkable
linkable -> forall a b. b -> Either a b
Right Linkable
linkable
                     Maybe Linkable
Nothing -> forall a b. a -> Either a b
Left Module
mod

        -- 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 :: String
osuf = DynFlags -> String
objectSuf DynFlags
dflags }
      ; [Linkable]
lnks_needed <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (String -> Module -> IO Linkable
get_linkable String
osuf) [Module]
mods_needed

      ; forall (m :: * -> *) a. Monad m => a -> m a
return ([Linkable]
lnks_needed, [Linkable]
links_got forall a. [a] -> [a] -> [a]
++ [Linkable]
lnks_needed, [UnitId]
pkgs_needed, UniqDSet UnitId
pkgs_s) }
  where
    dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
    mod_graph :: ModuleGraph
mod_graph = HscEnv -> ModuleGraph
hsc_mod_graph HscEnv
hsc_env

    -- This code is used in `--make` mode to calculate the home package and unit dependencies
    -- for a set of modules.
    --
    -- It is significantly more efficient to use the shared transitive dependency
    -- calculation than to compute the transitive dependency set in the same manner as oneShot mode.

    -- It is also a matter of correctness to use the module graph so that dependencies between home units
    -- is resolved correctly.
    make_deps_loop :: (UniqDSet UnitId, Set.Set NodeKey) -> [ModNodeKeyWithUid] -> (UniqDSet UnitId, Set.Set NodeKey)
    make_deps_loop :: (UniqDSet UnitId, Set NodeKey)
-> [ModNodeKeyWithUid] -> (UniqDSet UnitId, Set NodeKey)
make_deps_loop (UniqDSet UnitId, Set NodeKey)
found [] = (UniqDSet UnitId, Set NodeKey)
found
    make_deps_loop found :: (UniqDSet UnitId, Set NodeKey)
found@(UniqDSet UnitId
found_units, Set NodeKey
found_mods) (ModNodeKeyWithUid
nk:[ModNodeKeyWithUid]
nexts)
      | ModNodeKeyWithUid -> NodeKey
NodeKey_Module ModNodeKeyWithUid
nk forall a. Ord a => a -> Set a -> Bool
`Set.member` Set NodeKey
found_mods = (UniqDSet UnitId, Set NodeKey)
-> [ModNodeKeyWithUid] -> (UniqDSet UnitId, Set NodeKey)
make_deps_loop (UniqDSet UnitId, Set NodeKey)
found [ModNodeKeyWithUid]
nexts
      | Bool
otherwise =
        case forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (ModNodeKeyWithUid -> NodeKey
NodeKey_Module ModNodeKeyWithUid
nk) (ModuleGraph -> Map NodeKey (Set NodeKey)
mgTransDeps ModuleGraph
mod_graph) of
            Just Set NodeKey
trans_deps ->
              let deps :: Set NodeKey
deps = forall a. Ord a => a -> Set a -> Set a
Set.insert (ModNodeKeyWithUid -> NodeKey
NodeKey_Module ModNodeKeyWithUid
nk) Set NodeKey
trans_deps
                  -- See #936 and the ghci.prog007 test for why we have to continue traversing through
                  -- boot modules.
                  todo_boot_mods :: [ModNodeKeyWithUid]
todo_boot_mods = [ModuleNameWithIsBoot -> UnitId -> ModNodeKeyWithUid
ModNodeKeyWithUid (forall mod. mod -> IsBootInterface -> GenWithIsBoot mod
GWIB ModuleName
mn IsBootInterface
NotBoot) UnitId
uid | NodeKey_Module (ModNodeKeyWithUid (GWIB ModuleName
mn IsBootInterface
IsBoot) UnitId
uid) <- forall a. Set a -> [a]
Set.toList Set NodeKey
trans_deps]
              in (UniqDSet UnitId, Set NodeKey)
-> [ModNodeKeyWithUid] -> (UniqDSet UnitId, Set NodeKey)
make_deps_loop (UniqDSet UnitId
found_units, Set NodeKey
deps forall a. Ord a => Set a -> Set a -> Set a
`Set.union` Set NodeKey
found_mods) ([ModNodeKeyWithUid]
todo_boot_mods forall a. [a] -> [a] -> [a]
++ [ModNodeKeyWithUid]
nexts)
            Maybe (Set NodeKey)
Nothing ->
              let (ModNodeKeyWithUid ModuleNameWithIsBoot
_ UnitId
uid) = ModNodeKeyWithUid
nk
              in (UniqDSet UnitId, Set NodeKey)
-> [ModNodeKeyWithUid] -> (UniqDSet UnitId, Set NodeKey)
make_deps_loop (forall a. Uniquable a => UniqDSet a -> a -> UniqDSet a
addOneToUniqDSet UniqDSet UnitId
found_units UnitId
uid, Set NodeKey
found_mods) [ModNodeKeyWithUid]
nexts

    mkNk :: Module -> ModNodeKeyWithUid
mkNk Module
m = ModuleNameWithIsBoot -> UnitId -> ModNodeKeyWithUid
ModNodeKeyWithUid (forall mod. mod -> IsBootInterface -> GenWithIsBoot mod
GWIB (forall unit. GenModule unit -> ModuleName
moduleName Module
m) IsBootInterface
NotBoot) (Module -> UnitId
moduleUnitId Module
m)
    (UniqDSet UnitId
init_pkg_set, Set NodeKey
all_deps) = (UniqDSet UnitId, Set NodeKey)
-> [ModNodeKeyWithUid] -> (UniqDSet UnitId, Set NodeKey)
make_deps_loop (forall a. UniqDSet a
emptyUniqDSet, forall a. Set a
Set.empty) forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map Module -> ModNodeKeyWithUid
mkNk (forall a. (a -> Bool) -> [a] -> [a]
filterOut Module -> Bool
isInteractiveModule [Module]
mods)

    all_home_mods :: [ModNodeKeyWithUid]
all_home_mods = [ModNodeKeyWithUid
with_uid | NodeKey_Module ModNodeKeyWithUid
with_uid <- forall a. Set a -> [a]
Set.toList Set NodeKey
all_deps]

    get_mod_info :: ModNodeKeyWithUid -> IO (UniqDSet UnitId, Maybe Module)
get_mod_info (ModNodeKeyWithUid ModuleNameWithIsBoot
gwib UnitId
uid) =
      case HomeUnitGraph -> UnitId -> ModuleName -> Maybe HomeModInfo
lookupHug (HscEnv -> HomeUnitGraph
hsc_HUG HscEnv
hsc_env) UnitId
uid (forall mod. GenWithIsBoot mod -> mod
gwib_mod ModuleNameWithIsBoot
gwib) of
        Just HomeModInfo
hmi ->
          let iface :: ModIface
iface = (HomeModInfo -> ModIface
hm_iface HomeModInfo
hmi)
              mmod :: IO (Maybe Module)
mmod = case forall (phase :: ModIfacePhase). ModIface_ phase -> HscSource
mi_hsc_src ModIface
iface of
                      HscSource
HsBootFile -> forall a. Module -> IO a
link_boot_mod_error (forall (phase :: ModIfacePhase). ModIface_ phase -> Module
mi_module ModIface
iface)
                      HscSource
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a
Just (forall (phase :: ModIfacePhase). ModIface_ phase -> Module
mi_module ModIface
iface)

          in (forall a. Uniquable a => [a] -> UniqDSet a
mkUniqDSet forall a b. (a -> b) -> a -> b
$ forall a. Set a -> [a]
Set.toList forall a b. (a -> b) -> a -> b
$ Dependencies -> Set UnitId
dep_direct_pkgs (forall (phase :: ModIfacePhase). ModIface_ phase -> Dependencies
mi_deps ModIface
iface),) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>  IO (Maybe Module)
mmod
        Maybe HomeModInfo
Nothing ->
          let err :: SDoc
err = String -> SDoc
text String
"getLinkDeps: Home module not loaded" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr (forall mod. GenWithIsBoot mod -> mod
gwib_mod ModuleNameWithIsBoot
gwib) SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr UnitId
uid
          in forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags SDoc
err))


       -- This code is used in one-shot mode to traverse downwards through the HPT
       -- to find all link dependencies.
       -- 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 Module         -- accum. module dependencies
                -> UniqDSet UnitId          -- accum. package dependencies
                -> IO ([Module], UniqDSet UnitId) -- result
    follow_deps :: [Module]
-> UniqDSet Module
-> UniqDSet UnitId
-> IO ([Module], UniqDSet UnitId)
follow_deps []     UniqDSet Module
acc_mods UniqDSet UnitId
acc_pkgs
        = forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. UniqDSet a -> [a]
uniqDSetToList UniqDSet Module
acc_mods, UniqDSet UnitId
acc_pkgs)
    follow_deps (Module
mod:[Module]
mods) UniqDSet Module
acc_mods UniqDSet UnitId
acc_pkgs
        = do
          MaybeErr SDoc ModIface
mb_iface <- forall a. SDoc -> HscEnv -> IfG a -> IO a
initIfaceCheck (String -> SDoc
text String
"getLinkDeps") HscEnv
hsc_env forall a b. (a -> b) -> a -> b
$
                        forall lcl.
SDoc -> Module -> WhereFrom -> IfM lcl (MaybeErr SDoc ModIface)
loadInterface SDoc
msg Module
mod (IsBootInterface -> WhereFrom
ImportByUser IsBootInterface
NotBoot)
          ModIface
iface <- case MaybeErr SDoc ModIface
mb_iface of
                    Maybes.Failed SDoc
err      -> forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags SDoc
err))
                    Maybes.Succeeded ModIface
iface -> forall (m :: * -> *) a. Monad m => a -> m a
return ModIface
iface

          forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ModIface -> IsBootInterface
mi_boot ModIface
iface forall a. Eq a => a -> a -> Bool
== IsBootInterface
IsBoot) forall a b. (a -> b) -> a -> b
$ forall a. Module -> IO a
link_boot_mod_error Module
mod

          let
            pkg :: Unit
pkg = forall unit. GenModule unit -> unit
moduleUnit Module
mod
            deps :: Dependencies
deps  = forall (phase :: ModIfacePhase). ModIface_ phase -> Dependencies
mi_deps ModIface
iface

            pkg_deps :: Set UnitId
pkg_deps = Dependencies -> Set UnitId
dep_direct_pkgs Dependencies
deps
            ([ModuleName]
boot_deps, [ModuleName]
mod_deps) = forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith (forall a. Set a -> [a]
Set.toList (Dependencies -> Set (UnitId, ModuleNameWithIsBoot)
dep_direct_mods Dependencies
deps)) forall a b. (a -> b) -> a -> b
$
              \case
                (UnitId
_, GWIB ModuleName
m IsBootInterface
IsBoot)  -> forall a b. a -> Either a b
Left ModuleName
m
                (UnitId
_, GWIB ModuleName
m IsBootInterface
NotBoot) -> forall a b. b -> Either a b
Right ModuleName
m

            mod_deps' :: [Module]
mod_deps' = case HscEnv -> Maybe HomeUnit
hsc_home_unit_maybe HscEnv
hsc_env of
                          Maybe HomeUnit
Nothing -> []
                          Just HomeUnit
home_unit -> forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. (forall a. Uniquable a => a -> UniqDSet a -> Bool
`elementOfUniqDSet` UniqDSet Module
acc_mods)) (forall a b. (a -> b) -> [a] -> [b]
map (HomeUnit -> ModuleName -> Module
mkHomeModule HomeUnit
home_unit) forall a b. (a -> b) -> a -> b
$ ([ModuleName]
boot_deps forall a. [a] -> [a] -> [a]
++ [ModuleName]
mod_deps))
            acc_mods' :: UniqDSet Module
acc_mods'  = case HscEnv -> Maybe HomeUnit
hsc_home_unit_maybe HscEnv
hsc_env of
                          Maybe HomeUnit
Nothing -> UniqDSet Module
acc_mods
                          Just HomeUnit
home_unit -> forall a. Uniquable a => UniqDSet a -> [a] -> UniqDSet a
addListToUniqDSet UniqDSet Module
acc_mods (Module
mod forall a. a -> [a] -> [a]
: forall a b. (a -> b) -> [a] -> [b]
map (HomeUnit -> ModuleName -> Module
mkHomeModule HomeUnit
home_unit) [ModuleName]
mod_deps)
            acc_pkgs' :: UniqDSet UnitId
acc_pkgs'  = forall a. Uniquable a => UniqDSet a -> [a] -> UniqDSet a
addListToUniqDSet UniqDSet UnitId
acc_pkgs (forall a. Set a -> [a]
Set.toList Set UnitId
pkg_deps)

          case HscEnv -> Maybe HomeUnit
hsc_home_unit_maybe HscEnv
hsc_env of
            Just HomeUnit
home_unit | HomeUnit -> Unit -> Bool
isHomeUnit HomeUnit
home_unit Unit
pkg ->  [Module]
-> UniqDSet Module
-> UniqDSet UnitId
-> IO ([Module], UniqDSet UnitId)
follow_deps ([Module]
mod_deps' forall a. [a] -> [a] -> [a]
++ [Module]
mods)
                                                                      UniqDSet Module
acc_mods' UniqDSet UnitId
acc_pkgs'
            Maybe HomeUnit
_ ->  [Module]
-> UniqDSet Module
-> UniqDSet UnitId
-> IO ([Module], UniqDSet UnitId)
follow_deps [Module]
mods UniqDSet Module
acc_mods (forall a. Uniquable a => UniqDSet a -> a -> UniqDSet a
addOneToUniqDSet UniqDSet UnitId
acc_pkgs' (Unit -> UnitId
toUnitId Unit
pkg))
        where
           msg :: SDoc
msg = String -> SDoc
text String
"need to link module" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr Module
mod SDoc -> SDoc -> SDoc
<+>
                  String -> SDoc
text String
"due to use of Template Haskell"



    link_boot_mod_error :: Module -> IO a
    link_boot_mod_error :: forall a. Module -> IO a
link_boot_mod_error Module
mod =
        forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags (
            String -> SDoc
text String
"module" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr Module
mod SDoc -> SDoc -> SDoc
<+>
            String -> SDoc
text String
"cannot be linked; it is only available as a boot module")))

    no_obj :: Outputable a => a -> IO b
    no_obj :: forall a b. Outputable a => a -> IO b
no_obj a
mod = forall a. DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
span forall a b. (a -> b) -> a -> b
$
                     String -> SDoc
text String
"cannot find object file for module " SDoc -> SDoc -> SDoc
<>
                        SDoc -> SDoc
quotes (forall a. Outputable a => a -> SDoc
ppr a
mod) SDoc -> SDoc -> SDoc
$$
                     SDoc
while_linking_expr

    while_linking_expr :: SDoc
while_linking_expr = String -> SDoc
text String
"while linking an interpreted expression"

        -- This one is a build-system bug

    get_linkable :: String -> Module -> IO Linkable
get_linkable String
osuf Module
mod      -- A home-package module
        | Just HomeModInfo
mod_info <- Module -> HomeUnitGraph -> Maybe HomeModInfo
lookupHugByModule Module
mod (HscEnv -> HomeUnitGraph
hsc_HUG HscEnv
hsc_env)
        = Linkable -> IO Linkable
adjust_linkable (forall a. HasCallStack => String -> Maybe a -> a
Maybes.expectJust String
"getLinkDeps" (HomeModInfo -> Maybe Linkable
hm_linkable HomeModInfo
mod_info))
        | Bool
otherwise
        = do    -- It's not in the HPT because we are in one shot mode,
                -- so use the Finder to get a ModLocation...
             case HscEnv -> Maybe HomeUnit
hsc_home_unit_maybe HscEnv
hsc_env of
              Maybe HomeUnit
Nothing -> forall a b. Outputable a => a -> IO b
no_obj Module
mod
              Just HomeUnit
home_unit -> do

                let fc :: FinderCache
fc = HscEnv -> FinderCache
hsc_FC HscEnv
hsc_env
                let dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
                let fopts :: FinderOpts
fopts = DynFlags -> FinderOpts
initFinderOpts DynFlags
dflags
                FindResult
mb_stuff <- FinderCache
-> FinderOpts -> HomeUnit -> ModuleName -> IO FindResult
findHomeModule FinderCache
fc FinderOpts
fopts HomeUnit
home_unit (forall unit. GenModule unit -> ModuleName
moduleName Module
mod)
                case FindResult
mb_stuff of
                  Found ModLocation
loc Module
mod -> ModLocation -> Module -> IO Linkable
found ModLocation
loc Module
mod
                  FindResult
_ -> forall a b. Outputable a => a -> IO b
no_obj (forall unit. GenModule unit -> ModuleName
moduleName Module
mod)
        where
            found :: ModLocation -> Module -> IO Linkable
found ModLocation
loc Module
mod = do {
                -- ...and then find the linkable for it
               Maybe Linkable
mb_lnk <- Module -> ModLocation -> IO (Maybe Linkable)
findObjectLinkableMaybe Module
mod ModLocation
loc ;
               case Maybe Linkable
mb_lnk of {
                  Maybe Linkable
Nothing  -> forall a b. Outputable a => a -> IO b
no_obj Module
mod ;
                  Just Linkable
lnk -> Linkable -> IO Linkable
adjust_linkable Linkable
lnk
              }}

            adjust_linkable :: Linkable -> IO Linkable
adjust_linkable Linkable
lnk
                | Just String
new_osuf <- Maybe String
replace_osuf = do
                        [Unlinked]
new_uls <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (String -> Unlinked -> IO Unlinked
adjust_ul String
new_osuf)
                                        (Linkable -> [Unlinked]
linkableUnlinked Linkable
lnk)
                        forall (m :: * -> *) a. Monad m => a -> m a
return Linkable
lnk{ linkableUnlinked :: [Unlinked]
linkableUnlinked=[Unlinked]
new_uls }
                | Bool
otherwise =
                        forall (m :: * -> *) a. Monad m => a -> m a
return Linkable
lnk

            adjust_ul :: String -> Unlinked -> IO Unlinked
adjust_ul String
new_osuf (DotO String
file) = do
                forall (m :: * -> *). (HasCallStack, Applicative m) => Bool -> m ()
massert (String
osuf forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` String
file)
                let file_base :: String
file_base = forall a. HasCallStack => Maybe a -> a
fromJust (String -> String -> Maybe String
stripExtension String
osuf String
file)
                    new_file :: String
new_file = String
file_base String -> String -> String
<.> String
new_osuf
                Bool
ok <- String -> IO Bool
doesFileExist String
new_file
                if (Bool -> Bool
not Bool
ok)
                   then forall a. DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
span forall a b. (a -> b) -> a -> b
$
                          String -> SDoc
text String
"cannot find object file "
                                SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
quotes (String -> SDoc
text String
new_file) SDoc -> SDoc -> SDoc
$$ SDoc
while_linking_expr
                   else forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Unlinked
DotO String
new_file)
            adjust_ul String
_ (DotA String
fp) = forall a. String -> a
panic (String
"adjust_ul DotA " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show String
fp)
            adjust_ul String
_ (DotDLL String
fp) = forall a. String -> a
panic (String
"adjust_ul DotDLL " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show String
fp)
            adjust_ul String
_ l :: Unlinked
l@(BCOs {}) = forall (m :: * -> *) a. Monad m => a -> m a
return Unlinked
l


{- **********************************************************************

              Loading a Decls statement

  ********************************************************************* -}

loadDecls :: Interp -> HscEnv -> SrcSpan -> CompiledByteCode -> IO ([(Name, ForeignHValue)], [Linkable], PkgsLoaded)
loadDecls :: Interp
-> HscEnv
-> SrcSpan
-> CompiledByteCode
-> IO ([(Name, ForeignHValue)], [Linkable], PkgsLoaded)
loadDecls Interp
interp HscEnv
hsc_env SrcSpan
span cbc :: CompiledByteCode
cbc@CompiledByteCode{[FFIInfo]
[UnlinkedBCO]
[RemotePtr ()]
Maybe ModBreaks
ItblEnv
bc_bcos :: CompiledByteCode -> [UnlinkedBCO]
bc_itbls :: CompiledByteCode -> ItblEnv
bc_ffis :: CompiledByteCode -> [FFIInfo]
bc_strs :: CompiledByteCode -> [RemotePtr ()]
bc_breaks :: CompiledByteCode -> Maybe ModBreaks
bc_breaks :: Maybe ModBreaks
bc_strs :: [RemotePtr ()]
bc_ffis :: [FFIInfo]
bc_itbls :: ItblEnv
bc_bcos :: [UnlinkedBCO]
..} = do
    -- Initialise the linker (if it's not been done already)
    Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env

    -- Take lock for the actual work.
    forall a. Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
modifyLoaderState Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls0 -> do
      -- Link the packages and modules required
      (LoaderState
pls, SuccessFlag
ok, [Linkable]
links_needed, PkgsLoaded
units_needed) <- Interp
-> HscEnv
-> LoaderState
-> SrcSpan
-> [Module]
-> IO (LoaderState, SuccessFlag, [Linkable], PkgsLoaded)
loadDependencies Interp
interp HscEnv
hsc_env LoaderState
pls0 SrcSpan
span [Module]
needed_mods
      if SuccessFlag -> Bool
failed SuccessFlag
ok
        then forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"")
        else do
          -- Link the expression itself
          let ie :: ItblEnv
ie = forall a. NameEnv a -> NameEnv a -> NameEnv a
plusNameEnv (LoaderState -> ItblEnv
itbl_env LoaderState
pls) ItblEnv
bc_itbls
              ce :: ClosureEnv
ce = LoaderState -> ClosureEnv
closure_env LoaderState
pls

          -- Link the necessary packages and linkables
          BCOOpts
bco_opts <- DynFlags -> IO BCOOpts
initBCOOpts (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env)
          [(Name, HValueRef)]
new_bindings <- BCOOpts
-> Interp
-> ItblEnv
-> ClosureEnv
-> [CompiledByteCode]
-> IO [(Name, HValueRef)]
linkSomeBCOs BCOOpts
bco_opts Interp
interp ItblEnv
ie ClosureEnv
ce [CompiledByteCode
cbc]
          [(Name, ForeignHValue)]
nms_fhvs <- Interp -> [(Name, HValueRef)] -> IO [(Name, ForeignHValue)]
makeForeignNamedHValueRefs Interp
interp [(Name, HValueRef)]
new_bindings
          let pls2 :: LoaderState
pls2 = LoaderState
pls { closure_env :: ClosureEnv
closure_env = ClosureEnv -> [(Name, ForeignHValue)] -> ClosureEnv
extendClosureEnv ClosureEnv
ce [(Name, ForeignHValue)]
nms_fhvs
                         , itbl_env :: ItblEnv
itbl_env    = ItblEnv
ie }
          forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls2, ([(Name, ForeignHValue)]
nms_fhvs, [Linkable]
links_needed, PkgsLoaded
units_needed))
  where
    free_names :: [Name]
free_names = forall a. UniqDSet a -> [a]
uniqDSetToList forall a b. (a -> b) -> a -> b
$
      forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (forall a. UniqDSet a -> UniqDSet a -> UniqDSet a
unionUniqDSets forall b c a. (b -> c) -> (a -> b) -> a -> c
. UnlinkedBCO -> UniqDSet Name
bcoFreeNames) forall a. UniqDSet a
emptyUniqDSet [UnlinkedBCO]
bc_bcos

    needed_mods :: [Module]
    needed_mods :: [Module]
needed_mods = [ HasDebugCallStack => Name -> Module
nameModule Name
n | Name
n <- [Name]
free_names,
                    Name -> Bool
isExternalName Name
n,       -- Names from other modules
                    Bool -> Bool
not (Name -> Bool
isWiredInName Name
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

  ********************************************************************* -}

loadModule :: Interp -> HscEnv -> Module -> IO ()
loadModule :: Interp -> HscEnv -> Module -> IO ()
loadModule Interp
interp HscEnv
hsc_env Module
mod = do
  Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env
  Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls -> do
    (LoaderState
pls', SuccessFlag
ok, [Linkable]
_, PkgsLoaded
_) <- Interp
-> HscEnv
-> LoaderState
-> SrcSpan
-> [Module]
-> IO (LoaderState, SuccessFlag, [Linkable], PkgsLoaded)
loadDependencies Interp
interp HscEnv
hsc_env LoaderState
pls SrcSpan
noSrcSpan [Module
mod]
    if SuccessFlag -> Bool
failed SuccessFlag
ok
      then forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"could not load module")
      else forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls'

{- **********************************************************************

                Link some linkables
        The linkables may consist of a mixture of
        byte-code modules and object modules

  ********************************************************************* -}

loadModuleLinkables :: Interp -> HscEnv -> LoaderState -> [Linkable] -> IO (LoaderState, SuccessFlag)
loadModuleLinkables :: Interp
-> HscEnv
-> LoaderState
-> [Linkable]
-> IO (LoaderState, SuccessFlag)
loadModuleLinkables Interp
interp HscEnv
hsc_env LoaderState
pls [Linkable]
linkables
  = forall a. IO a -> IO a
mask_ forall a b. (a -> b) -> a -> b
$ do  -- don't want to be interrupted by ^C in here

        let ([Linkable]
objs, [Linkable]
bcos) = forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Linkable -> Bool
isObjectLinkable
                              (forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Linkable -> [Linkable]
partitionLinkable [Linkable]
linkables)
        BCOOpts
bco_opts <- DynFlags -> IO BCOOpts
initBCOOpts (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env)

                -- Load objects first; they can't depend on BCOs
        (LoaderState
pls1, SuccessFlag
ok_flag) <- Interp
-> HscEnv
-> LoaderState
-> [Linkable]
-> IO (LoaderState, SuccessFlag)
loadObjects Interp
interp HscEnv
hsc_env LoaderState
pls [Linkable]
objs

        if SuccessFlag -> Bool
failed SuccessFlag
ok_flag then
                forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls1, SuccessFlag
Failed)
          else do
                LoaderState
pls2 <- BCOOpts -> Interp -> LoaderState -> [Linkable] -> IO LoaderState
dynLinkBCOs BCOOpts
bco_opts Interp
interp LoaderState
pls1 [Linkable]
bcos
                forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls2, SuccessFlag
Succeeded)


-- HACK to support f-x-dynamic in the interpreter; no other purpose
partitionLinkable :: Linkable -> [Linkable]
partitionLinkable :: Linkable -> [Linkable]
partitionLinkable Linkable
li
   = let li_uls :: [Unlinked]
li_uls = Linkable -> [Unlinked]
linkableUnlinked Linkable
li
         li_uls_obj :: [Unlinked]
li_uls_obj = forall a. (a -> Bool) -> [a] -> [a]
filter Unlinked -> Bool
isObject [Unlinked]
li_uls
         li_uls_bco :: [Unlinked]
li_uls_bco = forall a. (a -> Bool) -> [a] -> [a]
filter Unlinked -> Bool
isInterpretable [Unlinked]
li_uls
     in
         case ([Unlinked]
li_uls_obj, [Unlinked]
li_uls_bco) of
            (Unlinked
_:[Unlinked]
_, Unlinked
_:[Unlinked]
_) -> [Linkable
li {linkableUnlinked :: [Unlinked]
linkableUnlinked=[Unlinked]
li_uls_obj},
                           Linkable
li {linkableUnlinked :: [Unlinked]
linkableUnlinked=[Unlinked]
li_uls_bco}]
            ([Unlinked], [Unlinked])
_ -> [Linkable
li]

findModuleLinkable_maybe :: LinkableSet -> Module -> Maybe Linkable
findModuleLinkable_maybe :: LinkableSet -> Module -> Maybe Linkable
findModuleLinkable_maybe = forall a. ModuleEnv a -> Module -> Maybe a
lookupModuleEnv

linkableInSet :: Linkable -> LinkableSet -> Bool
linkableInSet :: Linkable -> LinkableSet -> Bool
linkableInSet Linkable
l LinkableSet
objs_loaded =
  case LinkableSet -> Module -> Maybe Linkable
findModuleLinkable_maybe LinkableSet
objs_loaded (Linkable -> Module
linkableModule Linkable
l) of
        Maybe Linkable
Nothing -> Bool
False
        Just Linkable
m  -> Linkable -> UTCTime
linkableTime Linkable
l forall a. Eq a => a -> a -> Bool
== Linkable -> UTCTime
linkableTime Linkable
m


{- **********************************************************************

                The object-code linker

  ********************************************************************* -}

-- | Load the object files and link them
--
-- If the interpreter uses dynamic-linking, build a shared library and load it.
-- Otherwise, use the RTS linker.
loadObjects
  :: Interp
  -> HscEnv
  -> LoaderState
  -> [Linkable]
  -> IO (LoaderState, SuccessFlag)
loadObjects :: Interp
-> HscEnv
-> LoaderState
-> [Linkable]
-> IO (LoaderState, SuccessFlag)
loadObjects Interp
interp HscEnv
hsc_env LoaderState
pls [Linkable]
objs = do
        let (LinkableSet
objs_loaded', [Linkable]
new_objs) = LinkableSet -> [Linkable] -> (LinkableSet, [Linkable])
rmDupLinkables (LoaderState -> LinkableSet
objs_loaded LoaderState
pls) [Linkable]
objs
            pls1 :: LoaderState
pls1                     = LoaderState
pls { objs_loaded :: LinkableSet
objs_loaded = LinkableSet
objs_loaded' }
            unlinkeds :: [Unlinked]
unlinkeds                = forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Linkable -> [Unlinked]
linkableUnlinked [Linkable]
new_objs
            wanted_objs :: [String]
wanted_objs              = forall a b. (a -> b) -> [a] -> [b]
map Unlinked -> String
nameOfObject [Unlinked]
unlinkeds

        if Interp -> Bool
interpreterDynamic Interp
interp
            then do LoaderState
pls2 <- Interp -> HscEnv -> LoaderState -> [String] -> IO LoaderState
dynLoadObjs Interp
interp HscEnv
hsc_env LoaderState
pls1 [String]
wanted_objs
                    forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls2, SuccessFlag
Succeeded)
            else do forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> String -> IO ()
loadObj Interp
interp) [String]
wanted_objs

                    -- Link them all together
                    SuccessFlag
ok <- Interp -> IO SuccessFlag
resolveObjs Interp
interp

                    -- If resolving failed, unload all our
                    -- object modules and carry on
                    if SuccessFlag -> Bool
succeeded SuccessFlag
ok then
                            forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls1, SuccessFlag
Succeeded)
                      else do
                            LoaderState
pls2 <- Interp -> [Linkable] -> LoaderState -> IO LoaderState
unload_wkr Interp
interp [] LoaderState
pls1
                            forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls2, SuccessFlag
Failed)


-- | Create a shared library containing the given object files and load it.
dynLoadObjs :: Interp -> HscEnv -> LoaderState -> [FilePath] -> IO LoaderState
dynLoadObjs :: Interp -> HscEnv -> LoaderState -> [String] -> IO LoaderState
dynLoadObjs Interp
_      HscEnv
_       LoaderState
pls                           []   = forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls
dynLoadObjs Interp
interp HscEnv
hsc_env pls :: LoaderState
pls@LoaderState{[(String, String)]
LinkableSet
PkgsLoaded
ItblEnv
ClosureEnv
temp_sos :: [(String, String)]
pkgs_loaded :: PkgsLoaded
objs_loaded :: LinkableSet
bcos_loaded :: LinkableSet
itbl_env :: ItblEnv
closure_env :: ClosureEnv
temp_sos :: LoaderState -> [(String, String)]
objs_loaded :: LoaderState -> LinkableSet
bcos_loaded :: LoaderState -> LinkableSet
pkgs_loaded :: LoaderState -> PkgsLoaded
itbl_env :: LoaderState -> ItblEnv
closure_env :: LoaderState -> ClosureEnv
..} [String]
objs = do
    let unit_env :: UnitEnv
unit_env = HscEnv -> UnitEnv
hsc_unit_env HscEnv
hsc_env
    let dflags :: DynFlags
dflags   = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
    let logger :: Logger
logger   = HscEnv -> Logger
hsc_logger HscEnv
hsc_env
    let tmpfs :: TmpFs
tmpfs    = HscEnv -> TmpFs
hsc_tmpfs HscEnv
hsc_env
    let platform :: Platform
platform = UnitEnv -> Platform
ue_platform UnitEnv
unit_env
    let minus_ls :: [String]
minus_ls = [ String
lib | Option (Char
'-':Char
'l':String
lib) <- DynFlags -> [Option]
ldInputs DynFlags
dflags ]
    let minus_big_ls :: [String]
minus_big_ls = [ String
lib | Option (Char
'-':Char
'L':String
lib) <- DynFlags -> [Option]
ldInputs DynFlags
dflags ]
    (String
soFile, String
libPath , String
libName) <-
      Logger
-> TmpFs
-> TempDir
-> TempFileLifetime
-> String
-> IO (String, String, String)
newTempLibName Logger
logger TmpFs
tmpfs (DynFlags -> TempDir
tmpDir DynFlags
dflags) TempFileLifetime
TFL_CurrentModule (Platform -> String
platformSOExt Platform
platform)
    let
        dflags2 :: DynFlags
dflags2 = DynFlags
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 :: [Option]
ldInputs =
                           forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\String
l -> [ String -> Option
Option (String
"-l" forall a. [a] -> [a] -> [a]
++ String
l) ])
                                     (forall a. Eq a => [a] -> [a]
nub forall a b. (a -> b) -> a -> b
$ forall a b. (a, b) -> b
snd forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(String, String)]
temp_sos)
                        forall a. [a] -> [a] -> [a]
++ forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\String
lp -> String -> Option
Option (String
"-L" forall a. [a] -> [a] -> [a]
++ String
lp)
                                          forall a. a -> [a] -> [a]
: if DynFlags -> OS -> Bool
useXLinkerRPath DynFlags
dflags (Platform -> OS
platformOS Platform
platform)
                                            then [ String -> Option
Option String
"-Xlinker"
                                                 , String -> Option
Option String
"-rpath"
                                                 , String -> Option
Option String
"-Xlinker"
                                                 , String -> Option
Option String
lp ]
                                            else [])
                                     (forall a. Eq a => [a] -> [a]
nub forall a b. (a -> b) -> a -> b
$ forall a b. (a, b) -> a
fst forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(String, String)]
temp_sos)
                        forall a. [a] -> [a] -> [a]
++ forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap
                             (\String
lp -> String -> Option
Option (String
"-L" forall a. [a] -> [a] -> [a]
++ String
lp)
                                  forall a. a -> [a] -> [a]
: if DynFlags -> OS -> Bool
useXLinkerRPath DynFlags
dflags (Platform -> OS
platformOS Platform
platform)
                                    then [ String -> Option
Option String
"-Xlinker"
                                         , String -> Option
Option String
"-rpath"
                                         , String -> Option
Option String
"-Xlinker"
                                         , String -> Option
Option String
lp ]
                                    else [])
                             [String]
minus_big_ls
                        -- See Note [-Xlinker -rpath vs -Wl,-rpath]
                        forall a. [a] -> [a] -> [a]
++ forall a b. (a -> b) -> [a] -> [b]
map (\String
l -> String -> Option
Option (String
"-l" forall a. [a] -> [a] -> [a]
++ String
l)) [String]
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.
                      targetWays_ :: Ways
targetWays_ = forall a. a -> Set a
Set.singleton Way
WayDyn,
                      outputFile_ :: Maybe String
outputFile_ = forall a. a -> Maybe a
Just String
soFile
                  }
    -- 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.
    Logger
-> TmpFs -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()
linkDynLib Logger
logger TmpFs
tmpfs DynFlags
dflags2 UnitEnv
unit_env [String]
objs (LoadedPkgInfo -> UnitId
loaded_pkg_uid forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall key elt. UniqDFM key elt -> [elt]
eltsUDFM PkgsLoaded
pkgs_loaded)

    -- if we got this far, extend the lifetime of the library file
    TmpFs -> TempFileLifetime -> [String] -> IO ()
changeTempFilesLifetime TmpFs
tmpfs TempFileLifetime
TFL_GhcSession [String
soFile]
    Maybe String
m <- Interp -> String -> IO (Maybe String)
loadDLL Interp
interp String
soFile
    case Maybe String
m of
        Maybe String
Nothing -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! LoaderState
pls { temp_sos :: [(String, String)]
temp_sos = (String
libPath, String
libName) forall a. a -> [a] -> [a]
: [(String, String)]
temp_sos }
        Just String
err -> forall a. String -> String -> IO a
linkFail String
msg String
err
  where
    msg :: String
msg = String
"GHC.Linker.Loader.dynLoadObjs: Loading temp shared object failed"

rmDupLinkables :: LinkableSet    -- Already loaded
               -> [Linkable]    -- New linkables
               -> (LinkableSet,  -- New loaded set (including new ones)
                   [Linkable])  -- New linkables (excluding dups)
rmDupLinkables :: LinkableSet -> [Linkable] -> (LinkableSet, [Linkable])
rmDupLinkables LinkableSet
already [Linkable]
ls
  = LinkableSet
-> [Linkable] -> [Linkable] -> (LinkableSet, [Linkable])
go LinkableSet
already [] [Linkable]
ls
  where
    go :: LinkableSet
-> [Linkable] -> [Linkable] -> (LinkableSet, [Linkable])
go LinkableSet
already [Linkable]
extras [] = (LinkableSet
already, [Linkable]
extras)
    go LinkableSet
already [Linkable]
extras (Linkable
l:[Linkable]
ls)
        | Linkable -> LinkableSet -> Bool
linkableInSet Linkable
l LinkableSet
already = LinkableSet
-> [Linkable] -> [Linkable] -> (LinkableSet, [Linkable])
go LinkableSet
already     [Linkable]
extras     [Linkable]
ls
        | Bool
otherwise               = LinkableSet
-> [Linkable] -> [Linkable] -> (LinkableSet, [Linkable])
go (forall a. ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv LinkableSet
already (Linkable -> Module
linkableModule Linkable
l) Linkable
l) (Linkable
lforall a. a -> [a] -> [a]
:[Linkable]
extras) [Linkable]
ls

{- **********************************************************************

                The byte-code linker

  ********************************************************************* -}


dynLinkBCOs :: BCOOpts -> Interp -> LoaderState -> [Linkable] -> IO LoaderState
dynLinkBCOs :: BCOOpts -> Interp -> LoaderState -> [Linkable] -> IO LoaderState
dynLinkBCOs BCOOpts
bco_opts Interp
interp LoaderState
pls [Linkable]
bcos = do

        let (LinkableSet
bcos_loaded', [Linkable]
new_bcos) = LinkableSet -> [Linkable] -> (LinkableSet, [Linkable])
rmDupLinkables (LoaderState -> LinkableSet
bcos_loaded LoaderState
pls) [Linkable]
bcos
            pls1 :: LoaderState
pls1                     = LoaderState
pls { bcos_loaded :: LinkableSet
bcos_loaded = LinkableSet
bcos_loaded' }
            unlinkeds :: [Unlinked]
            unlinkeds :: [Unlinked]
unlinkeds                = forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Linkable -> [Unlinked]
linkableUnlinked [Linkable]
new_bcos

            cbcs :: [CompiledByteCode]
            cbcs :: [CompiledByteCode]
cbcs      = forall a b. (a -> b) -> [a] -> [b]
map Unlinked -> CompiledByteCode
byteCodeOfObject [Unlinked]
unlinkeds


            ies :: [ItblEnv]
ies        = forall a b. (a -> b) -> [a] -> [b]
map CompiledByteCode -> ItblEnv
bc_itbls [CompiledByteCode]
cbcs
            gce :: ClosureEnv
gce       = LoaderState -> ClosureEnv
closure_env LoaderState
pls
            final_ie :: ItblEnv
final_ie  = forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr forall a. NameEnv a -> NameEnv a -> NameEnv a
plusNameEnv (LoaderState -> ItblEnv
itbl_env LoaderState
pls) [ItblEnv]
ies

        [(Name, HValueRef)]
names_and_refs <- BCOOpts
-> Interp
-> ItblEnv
-> ClosureEnv
-> [CompiledByteCode]
-> IO [(Name, HValueRef)]
linkSomeBCOs BCOOpts
bco_opts Interp
interp ItblEnv
final_ie ClosureEnv
gce [CompiledByteCode]
cbcs

        -- We only want to add the external ones to the ClosureEnv
        let ([(Name, HValueRef)]
to_add, [(Name, HValueRef)]
to_drop) = forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Name -> Bool
isExternalNameforall b c a. (b -> c) -> (a -> b) -> a -> c
.forall a b. (a, b) -> a
fst) [(Name, HValueRef)]
names_and_refs

        -- Immediately release any HValueRefs we're not going to add
        Interp -> [HValueRef] -> IO ()
freeHValueRefs Interp
interp (forall a b. (a -> b) -> [a] -> [b]
map forall a b. (a, b) -> b
snd [(Name, HValueRef)]
to_drop)
        -- Wrap finalizers on the ones we want to keep
        [(Name, ForeignHValue)]
new_binds <- Interp -> [(Name, HValueRef)] -> IO [(Name, ForeignHValue)]
makeForeignNamedHValueRefs Interp
interp [(Name, HValueRef)]
to_add

        forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
pls1 { closure_env :: ClosureEnv
closure_env = ClosureEnv -> [(Name, ForeignHValue)] -> ClosureEnv
extendClosureEnv ClosureEnv
gce [(Name, ForeignHValue)]
new_binds,
                      itbl_env :: ItblEnv
itbl_env    = ItblEnv
final_ie }

-- Link a bunch of BCOs and return references to their values
linkSomeBCOs :: BCOOpts
             -> Interp
             -> 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 BCO

linkSomeBCOs :: BCOOpts
-> Interp
-> ItblEnv
-> ClosureEnv
-> [CompiledByteCode]
-> IO [(Name, HValueRef)]
linkSomeBCOs BCOOpts
bco_opts Interp
interp ItblEnv
ie ClosureEnv
ce [CompiledByteCode]
mods = forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr forall {b}.
CompiledByteCode
-> ([(RemoteRef BreakArray, [UnlinkedBCO])] -> IO b)
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
-> IO b
fun [(RemoteRef BreakArray, [UnlinkedBCO])] -> IO [(Name, HValueRef)]
do_link [CompiledByteCode]
mods []
 where
  fun :: CompiledByteCode
-> ([(RemoteRef BreakArray, [UnlinkedBCO])] -> IO b)
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
-> IO b
fun CompiledByteCode{[FFIInfo]
[UnlinkedBCO]
[RemotePtr ()]
Maybe ModBreaks
ItblEnv
bc_breaks :: Maybe ModBreaks
bc_strs :: [RemotePtr ()]
bc_ffis :: [FFIInfo]
bc_itbls :: ItblEnv
bc_bcos :: [UnlinkedBCO]
bc_bcos :: CompiledByteCode -> [UnlinkedBCO]
bc_itbls :: CompiledByteCode -> ItblEnv
bc_ffis :: CompiledByteCode -> [FFIInfo]
bc_strs :: CompiledByteCode -> [RemotePtr ()]
bc_breaks :: CompiledByteCode -> Maybe ModBreaks
..} [(RemoteRef BreakArray, [UnlinkedBCO])] -> IO b
inner [(RemoteRef BreakArray, [UnlinkedBCO])]
accum =
    case Maybe ModBreaks
bc_breaks of
      Maybe ModBreaks
Nothing -> [(RemoteRef BreakArray, [UnlinkedBCO])] -> IO b
inner ((forall a. String -> a
panic String
"linkSomeBCOs: no break array", [UnlinkedBCO]
bc_bcos) forall a. a -> [a] -> [a]
: [(RemoteRef BreakArray, [UnlinkedBCO])]
accum)
      Just ModBreaks
mb -> forall a b. ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef (ModBreaks -> ForeignRef BreakArray
modBreaks_flags ModBreaks
mb) forall a b. (a -> b) -> a -> b
$ \RemoteRef BreakArray
breakarray ->
                   [(RemoteRef BreakArray, [UnlinkedBCO])] -> IO b
inner ((RemoteRef BreakArray
breakarray, [UnlinkedBCO]
bc_bcos) forall a. a -> [a] -> [a]
: [(RemoteRef BreakArray, [UnlinkedBCO])]
accum)

  do_link :: [(RemoteRef BreakArray, [UnlinkedBCO])] -> IO [(Name, HValueRef)]
do_link [] = forall (m :: * -> *) a. Monad m => a -> m a
return []
  do_link [(RemoteRef BreakArray, [UnlinkedBCO])]
mods = do
    let flat :: [(RemoteRef BreakArray, UnlinkedBCO)]
flat = [ (RemoteRef BreakArray
breakarray, UnlinkedBCO
bco) | (RemoteRef BreakArray
breakarray, [UnlinkedBCO]
bcos) <- [(RemoteRef BreakArray, [UnlinkedBCO])]
mods, UnlinkedBCO
bco <- [UnlinkedBCO]
bcos ]
        names :: [Name]
names = forall a b. (a -> b) -> [a] -> [b]
map (UnlinkedBCO -> Name
unlinkedBCOName forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a, b) -> b
snd) [(RemoteRef BreakArray, UnlinkedBCO)]
flat
        bco_ix :: NameEnv Int
bco_ix = forall a. [(Name, a)] -> NameEnv a
mkNameEnv (forall a b. [a] -> [b] -> [(a, b)]
zip [Name]
names [Int
0..])
    [ResolvedBCO]
resolved <- forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
sequence [ Interp
-> ItblEnv
-> ClosureEnv
-> NameEnv Int
-> RemoteRef BreakArray
-> UnlinkedBCO
-> IO ResolvedBCO
linkBCO Interp
interp ItblEnv
ie ClosureEnv
ce NameEnv Int
bco_ix RemoteRef BreakArray
breakarray UnlinkedBCO
bco
                         | (RemoteRef BreakArray
breakarray, UnlinkedBCO
bco) <- [(RemoteRef BreakArray, UnlinkedBCO)]
flat ]
    [HValueRef]
hvrefs <- Interp -> BCOOpts -> [ResolvedBCO] -> IO [HValueRef]
createBCOs Interp
interp BCOOpts
bco_opts [ResolvedBCO]
resolved
    forall (m :: * -> *) a. Monad m => a -> m a
return (forall a b. [a] -> [b] -> [(a, b)]
zip [Name]
names [HValueRef]
hvrefs)

-- | Useful to apply to the result of 'linkSomeBCOs'
makeForeignNamedHValueRefs
  :: Interp -> [(Name,HValueRef)] -> IO [(Name,ForeignHValue)]
makeForeignNamedHValueRefs :: Interp -> [(Name, HValueRef)] -> IO [(Name, ForeignHValue)]
makeForeignNamedHValueRefs Interp
interp [(Name, HValueRef)]
bindings =
  forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (\(Name
n, HValueRef
hvref) -> (Name
n,) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. Interp -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue Interp
interp HValueRef
hvref) [(Name, HValueRef)]
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
  :: Interp
  -> HscEnv
  -> [Linkable] -- ^ The linkables to *keep*.
  -> IO ()
unload :: Interp -> HscEnv -> [Linkable] -> IO ()
unload Interp
interp HscEnv
hsc_env [Linkable]
linkables
  = forall a. IO a -> IO a
mask_ forall a b. (a -> b) -> a -> b
$ do -- mask, so we're safe from Ctrl-C in here

        -- Initialise the linker (if it's not been done already)
        Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env

        LoaderState
new_pls
            <- forall a. Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
modifyLoaderState Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls -> do
                 LoaderState
pls1 <- Interp -> [Linkable] -> LoaderState -> IO LoaderState
unload_wkr Interp
interp [Linkable]
linkables LoaderState
pls
                 forall (m :: * -> *) a. Monad m => a -> m a
return (LoaderState
pls1, LoaderState
pls1)

        let logger :: Logger
logger = HscEnv -> Logger
hsc_logger HscEnv
hsc_env
        Logger -> Int -> SDoc -> IO ()
debugTraceMsg Logger
logger Int
3 forall a b. (a -> b) -> a -> b
$
          String -> SDoc
text String
"unload: retaining objs" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr (forall a. ModuleEnv a -> [a]
moduleEnvElts forall a b. (a -> b) -> a -> b
$ LoaderState -> LinkableSet
objs_loaded LoaderState
new_pls)
        Logger -> Int -> SDoc -> IO ()
debugTraceMsg Logger
logger Int
3 forall a b. (a -> b) -> a -> b
$
          String -> SDoc
text String
"unload: retaining bcos" SDoc -> SDoc -> SDoc
<+> forall a. Outputable a => a -> SDoc
ppr (forall a. ModuleEnv a -> [a]
moduleEnvElts forall a b. (a -> b) -> a -> b
$ LoaderState -> LinkableSet
bcos_loaded LoaderState
new_pls)
        forall (m :: * -> *) a. Monad m => a -> m a
return ()

unload_wkr
  :: Interp
  -> [Linkable]                -- stable linkables
  -> LoaderState
  -> IO LoaderState
-- Does the core unload business
-- (the wrapper blocks exceptions and deals with the LS get and put)

unload_wkr :: Interp -> [Linkable] -> LoaderState -> IO LoaderState
unload_wkr Interp
interp [Linkable]
keep_linkables pls :: LoaderState
pls@LoaderState{[(String, String)]
LinkableSet
PkgsLoaded
ItblEnv
ClosureEnv
temp_sos :: [(String, String)]
pkgs_loaded :: PkgsLoaded
objs_loaded :: LinkableSet
bcos_loaded :: LinkableSet
itbl_env :: ItblEnv
closure_env :: ClosureEnv
temp_sos :: LoaderState -> [(String, String)]
objs_loaded :: LoaderState -> LinkableSet
bcos_loaded :: LoaderState -> LinkableSet
pkgs_loaded :: LoaderState -> PkgsLoaded
itbl_env :: LoaderState -> ItblEnv
closure_env :: LoaderState -> ClosureEnv
..}  = do
  -- NB. careful strictness here to avoid keeping the old LS when
  -- we're unloading some code.  -fghci-leak-check with the tests in
  -- testsuite/ghci can detect space leaks here.

  let ([Linkable]
objs_to_keep', [Linkable]
bcos_to_keep') = forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Linkable -> Bool
isObjectLinkable [Linkable]
keep_linkables
      objs_to_keep :: LinkableSet
objs_to_keep = [Linkable] -> LinkableSet
mkLinkableSet [Linkable]
objs_to_keep'
      bcos_to_keep :: LinkableSet
bcos_to_keep = [Linkable] -> LinkableSet
mkLinkableSet [Linkable]
bcos_to_keep'

      discard :: LinkableSet -> Linkable -> Bool
discard LinkableSet
keep Linkable
l = Bool -> Bool
not (Linkable -> LinkableSet -> Bool
linkableInSet Linkable
l LinkableSet
keep)

      (LinkableSet
objs_to_unload, LinkableSet
remaining_objs_loaded) =
         forall a. (a -> Bool) -> ModuleEnv a -> (ModuleEnv a, ModuleEnv a)
partitionModuleEnv (LinkableSet -> Linkable -> Bool
discard LinkableSet
objs_to_keep) LinkableSet
objs_loaded
      (LinkableSet
bcos_to_unload, LinkableSet
remaining_bcos_loaded) =
         forall a. (a -> Bool) -> ModuleEnv a -> (ModuleEnv a, ModuleEnv a)
partitionModuleEnv (LinkableSet -> Linkable -> Bool
discard LinkableSet
bcos_to_keep) LinkableSet
bcos_loaded

      linkables_to_unload :: [Linkable]
linkables_to_unload = forall a. ModuleEnv a -> [a]
moduleEnvElts LinkableSet
objs_to_unload forall a. [a] -> [a] -> [a]
++ forall a. ModuleEnv a -> [a]
moduleEnvElts LinkableSet
bcos_to_unload

  forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Linkable -> IO ()
unloadObjs [Linkable]
linkables_to_unload

  -- If we unloaded any object files at all, we need to purge the cache
  -- of lookupSymbol results.
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (forall (t :: * -> *) a. Foldable t => t a -> Bool
null (forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (t :: * -> *) a. Foldable t => t a -> Bool
null forall b c a. (b -> c) -> (a -> b) -> a -> c
. Linkable -> [String]
linkableObjs) [Linkable]
linkables_to_unload))) forall a b. (a -> b) -> a -> b
$
    Interp -> IO ()
purgeLookupSymbolCache Interp
interp

  let -- 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 :: (Name, a) -> Bool
      keep_name :: forall a. (Name, a) -> Bool
keep_name (Name
n,a
_) = Name -> Bool
isExternalName Name
n Bool -> Bool -> Bool
&&
                        HasDebugCallStack => Name -> Module
nameModule Name
n forall a. Module -> ModuleEnv a -> Bool
`elemModuleEnv` LinkableSet
remaining_bcos_loaded

      itbl_env' :: ItblEnv
itbl_env'     = forall elt. (elt -> Bool) -> NameEnv elt -> NameEnv elt
filterNameEnv forall a. (Name, a) -> Bool
keep_name ItblEnv
itbl_env
      closure_env' :: ClosureEnv
closure_env'  = forall elt. (elt -> Bool) -> NameEnv elt -> NameEnv elt
filterNameEnv forall a. (Name, a) -> Bool
keep_name ClosureEnv
closure_env

      !new_pls :: LoaderState
new_pls = LoaderState
pls { itbl_env :: ItblEnv
itbl_env = ItblEnv
itbl_env',
                       closure_env :: ClosureEnv
closure_env = ClosureEnv
closure_env',
                       bcos_loaded :: LinkableSet
bcos_loaded = LinkableSet
remaining_bcos_loaded,
                       objs_loaded :: LinkableSet
objs_loaded = LinkableSet
remaining_objs_loaded }

  forall (m :: * -> *) a. Monad m => a -> m a
return LoaderState
new_pls
  where
    unloadObjs :: Linkable -> IO ()
    unloadObjs :: Linkable -> IO ()
unloadObjs Linkable
lnk
      | Interp -> Bool
interpreterDynamic Interp
interp = forall (m :: * -> *) a. Monad m => a -> m a
return ()
        -- We don't do any cleanup when linking objects with the
        -- dynamic linker.  Doing so introduces extra complexity for
        -- not much benefit.

      | Bool
otherwise
      = forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> String -> IO ()
unloadObj Interp
interp) [String
f | DotO String
f <- Linkable -> [Unlinked]
linkableUnlinked Linkable
lnk]
                -- 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)

showLS :: LibrarySpec -> String
showLS :: LibrarySpec -> String
showLS (Objects [String]
nms)  = String
"(static) [" forall a. [a] -> [a] -> [a]
++ forall a. [a] -> [[a]] -> [a]
intercalate String
", " [String]
nms forall a. [a] -> [a] -> [a]
++ String
"]"
showLS (Archive String
nm)   = String
"(static archive) " forall a. [a] -> [a] -> [a]
++ String
nm
showLS (DLL String
nm)       = String
"(dynamic) " forall a. [a] -> [a] -> [a]
++ String
nm
showLS (DLLPath String
nm)   = String
"(dynamic) " forall a. [a] -> [a] -> [a]
++ String
nm
showLS (Framework String
nm) = String
"(framework) " forall a. [a] -> [a] -> [a]
++ String
nm

-- | Load exactly the specified packages, and their dependents (unless of
-- course they are already loaded).  The dependents are loaded
-- automatically, and it doesn't matter what order you specify the input
-- packages.
--
loadPackages :: Interp -> HscEnv -> [UnitId] -> 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.

loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
loadPackages Interp
interp HscEnv
hsc_env [UnitId]
new_pkgs = do
  -- It's probably not safe to try to load packages concurrently, so we take
  -- a lock.
  Interp -> HscEnv -> IO ()
initLoaderState Interp
interp HscEnv
hsc_env
  Interp -> (LoaderState -> IO LoaderState) -> IO ()
modifyLoaderState_ Interp
interp forall a b. (a -> b) -> a -> b
$ \LoaderState
pls ->
    Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState
loadPackages' Interp
interp HscEnv
hsc_env [UnitId]
new_pkgs LoaderState
pls

loadPackages' :: Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState
loadPackages' :: Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState
loadPackages' Interp
interp HscEnv
hsc_env [UnitId]
new_pks LoaderState
pls = do
    PkgsLoaded
pkgs' <- PkgsLoaded -> [UnitId] -> IO PkgsLoaded
link (LoaderState -> PkgsLoaded
pkgs_loaded LoaderState
pls) [UnitId]
new_pks
    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! LoaderState
pls { pkgs_loaded :: PkgsLoaded
pkgs_loaded = PkgsLoaded
pkgs'
                  }
  where
     link :: PkgsLoaded -> [UnitId] -> IO PkgsLoaded
     link :: PkgsLoaded -> [UnitId] -> IO PkgsLoaded
link PkgsLoaded
pkgs [UnitId]
new_pkgs =
         forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM PkgsLoaded -> UnitId -> IO PkgsLoaded
link_one PkgsLoaded
pkgs [UnitId]
new_pkgs

     link_one :: PkgsLoaded -> UnitId -> IO PkgsLoaded
link_one PkgsLoaded
pkgs UnitId
new_pkg
        | UnitId
new_pkg forall key elt. Uniquable key => key -> UniqDFM key elt -> Bool
`elemUDFM` PkgsLoaded
pkgs   -- Already linked
        = forall (m :: * -> *) a. Monad m => a -> m a
return PkgsLoaded
pkgs

        | Just UnitInfo
pkg_cfg <- UnitState -> UnitId -> Maybe UnitInfo
lookupUnitId (HasDebugCallStack => HscEnv -> UnitState
hsc_units HscEnv
hsc_env) UnitId
new_pkg
        = do { let deps :: [UnitId]
deps = forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod -> [uid]
unitDepends UnitInfo
pkg_cfg
               -- Link dependents first
             ; PkgsLoaded
pkgs' <- PkgsLoaded -> [UnitId] -> IO PkgsLoaded
link PkgsLoaded
pkgs [UnitId]
deps
                -- Now link the package itself
             ; ([LibrarySpec]
hs_cls, [LibrarySpec]
extra_cls) <- Interp -> HscEnv -> UnitInfo -> IO ([LibrarySpec], [LibrarySpec])
loadPackage Interp
interp HscEnv
hsc_env UnitInfo
pkg_cfg
             ; let trans_deps :: UniqDSet UnitId
trans_deps = forall a. [UniqDSet a] -> UniqDSet a
unionManyUniqDSets [ forall a. Uniquable a => UniqDSet a -> a -> UniqDSet a
addOneToUniqDSet (LoadedPkgInfo -> UniqDSet UnitId
loaded_pkg_trans_deps LoadedPkgInfo
loaded_pkg_info) UnitId
dep_pkg
                                                   | UnitId
dep_pkg <- [UnitId]
deps
                                                   , Just LoadedPkgInfo
loaded_pkg_info <- forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall key elt.
Uniquable key =>
UniqDFM key elt -> key -> Maybe elt
lookupUDFM PkgsLoaded
pkgs' UnitId
dep_pkg)
                                                   ]
             ; forall (m :: * -> *) a. Monad m => a -> m a
return (forall key elt.
Uniquable key =>
UniqDFM key elt -> key -> elt -> UniqDFM key elt
addToUDFM PkgsLoaded
pkgs' UnitId
new_pkg (UnitId
-> [LibrarySpec]
-> [LibrarySpec]
-> UniqDSet UnitId
-> LoadedPkgInfo
LoadedPkgInfo UnitId
new_pkg [LibrarySpec]
hs_cls [LibrarySpec]
extra_cls UniqDSet UnitId
trans_deps)) }

        | Bool
otherwise
        = forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
CmdLineError (String
"unknown package: " forall a. [a] -> [a] -> [a]
++ FastString -> String
unpackFS (UnitId -> FastString
unitIdFS UnitId
new_pkg)))


loadPackage :: Interp -> HscEnv -> UnitInfo -> IO ([LibrarySpec], [LibrarySpec])
loadPackage :: Interp -> HscEnv -> UnitInfo -> IO ([LibrarySpec], [LibrarySpec])
loadPackage Interp
interp HscEnv
hsc_env UnitInfo
pkg
   = do
        let dflags :: DynFlags
dflags    = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
        let logger :: Logger
logger    = HscEnv -> Logger
hsc_logger HscEnv
hsc_env
            platform :: Platform
platform  = DynFlags -> Platform
targetPlatform DynFlags
dflags
            is_dyn :: Bool
is_dyn    = Interp -> Bool
interpreterDynamic Interp
interp
            dirs :: [String]
dirs | Bool
is_dyn    = forall a b. (a -> b) -> [a] -> [b]
map ShortText -> String
ST.unpack forall a b. (a -> b) -> a -> b
$ forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitLibraryDynDirs UnitInfo
pkg
                 | Bool
otherwise = forall a b. (a -> b) -> [a] -> [b]
map ShortText -> String
ST.unpack forall a b. (a -> b) -> a -> b
$ forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitLibraryDirs UnitInfo
pkg

        let hs_libs :: [String]
hs_libs   = forall a b. (a -> b) -> [a] -> [b]
map ShortText -> String
ST.unpack forall a b. (a -> b) -> a -> b
$ forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitLibraries UnitInfo
pkg
            -- The FFI GHCi import lib isn't needed as
            -- GHC.Linker.Loader + 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' :: [String]
hs_libs'  =  forall a. (a -> Bool) -> [a] -> [a]
filter (String
"HSffi" forall a. Eq a => a -> a -> Bool
/=) [String]
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.
            extdeplibs :: [String]
extdeplibs = forall a b. (a -> b) -> [a] -> [b]
map ShortText -> String
ST.unpack (if forall (t :: * -> *) a. Foldable t => t a -> Bool
null (forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitExtDepLibsGhc UnitInfo
pkg)
                                      then forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitExtDepLibsSys UnitInfo
pkg
                                      else forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitExtDepLibsGhc UnitInfo
pkg)
            linkerlibs :: [String]
linkerlibs = [ String
lib | Char
'-':Char
'l':String
lib <- (forall a b. (a -> b) -> [a] -> [b]
map ShortText -> String
ST.unpack forall a b. (a -> b) -> a -> b
$ forall srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo srcpkgid srcpkgname uid modulename mod
-> [ShortText]
Packages.unitLinkerOptions UnitInfo
pkg) ]
            extra_libs :: [String]
extra_libs = [String]
extdeplibs forall a. [a] -> [a] -> [a]
++ [String]
linkerlibs

        -- See Note [Fork/Exec Windows]
        [String]
gcc_paths <- Logger -> DynFlags -> OS -> IO [String]
getGCCPaths Logger
logger DynFlags
dflags (Platform -> OS
platformOS Platform
platform)
        [String]
dirs_env <- String -> [String] -> IO [String]
addEnvPaths String
"LIBRARY_PATH" [String]
dirs

        [LibrarySpec]
hs_classifieds
           <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Interp
-> HscEnv
-> Bool
-> [String]
-> [String]
-> String
-> IO LibrarySpec
locateLib Interp
interp HscEnv
hsc_env Bool
True  [String]
dirs_env [String]
gcc_paths) [String]
hs_libs'
        [LibrarySpec]
extra_classifieds
           <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Interp
-> HscEnv
-> Bool
-> [String]
-> [String]
-> String
-> IO LibrarySpec
locateLib Interp
interp HscEnv
hsc_env Bool
False [String]
dirs_env [String]
gcc_paths) [String]
extra_libs
        let classifieds :: [LibrarySpec]
classifieds = [LibrarySpec]
hs_classifieds forall a. [a] -> [a] -> [a]
++ [LibrarySpec]
extra_classifieds

        -- Complication: all the .so's must be loaded before any of the .o's.
        let known_dlls :: [String]
known_dlls = [ String
dll  | DLLPath String
dll    <- [LibrarySpec]
classifieds ]
#if defined(CAN_LOAD_DLL)
            dlls       = [ dll  | DLL dll        <- classifieds ]
#endif
            objs :: [String]
objs       = [ String
obj  | Objects [String]
objs    <- [LibrarySpec]
classifieds
                                , String
obj <- [String]
objs ]
            archs :: [String]
archs      = [ String
arch | Archive String
arch   <- [LibrarySpec]
classifieds ]

        -- Add directories to library search paths
        let dll_paths :: [String]
dll_paths  = forall a b. (a -> b) -> [a] -> [b]
map String -> String
takeDirectory [String]
known_dlls
            all_paths :: [String]
all_paths  = forall a. Eq a => [a] -> [a]
nub forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map String -> String
normalise forall a b. (a -> b) -> a -> b
$ [String]
dll_paths forall a. [a] -> [a] -> [a]
++ [String]
dirs
        [String]
all_paths_env <- String -> [String] -> IO [String]
addEnvPaths String
"LD_LIBRARY_PATH" [String]
all_paths
        [Ptr ()]
pathCache <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Interp -> String -> IO (Ptr ())
addLibrarySearchPath Interp
interp) [String]
all_paths_env

        Logger -> SDoc -> IO ()
maybePutSDoc Logger
logger
            (String -> SDoc
text String
"Loading unit " SDoc -> SDoc -> SDoc
<> UnitInfo -> SDoc
pprUnitInfoForUser UnitInfo
pkg SDoc -> SDoc -> SDoc
<> String -> SDoc
text String
" ... ")

#if defined(CAN_LOAD_DLL)
        loadFrameworks interp platform pkg
        -- See Note [Crash early load_dyn and locateLib]
        -- Crash early if can't load any of `known_dlls`
        mapM_ (load_dyn interp 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 interp hsc_env (not is_dyn) . platformSOName platform) dlls
#endif
        -- 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.
        forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> String -> IO ()
loadObj Interp
interp) [String]
objs
        forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> String -> IO ()
loadArchive Interp
interp) [String]
archs

        Logger -> String -> IO ()
maybePutStr Logger
logger String
"linking ... "
        SuccessFlag
ok <- Interp -> IO SuccessFlag
resolveObjs Interp
interp

        -- 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.
        forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Interp -> Ptr () -> IO Bool
removeLibrarySearchPath Interp
interp) forall a b. (a -> b) -> a -> b
$ forall a. [a] -> [a]
reverse [Ptr ()]
pathCache

        if SuccessFlag -> Bool
succeeded SuccessFlag
ok
           then do
             Logger -> String -> IO ()
maybePutStrLn Logger
logger String
"done."
             forall (m :: * -> *) a. Monad m => a -> m a
return ([LibrarySpec]
hs_classifieds, [LibrarySpec]
extra_classifieds)
           else let errmsg :: SDoc
errmsg = String -> SDoc
text String
"unable to load unit `"
                             SDoc -> SDoc -> SDoc
<> UnitInfo -> SDoc
pprUnitInfoForUser UnitInfo
pkg SDoc -> SDoc -> SDoc
<> String -> SDoc
text String
"'"
                 in forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
InstallationError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags SDoc
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.
-}

#if defined(CAN_LOAD_DLL)
-- 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 :: Interp -> HscEnv -> Bool -> FilePath -> IO ()
load_dyn interp hsc_env crash_early dll = do
  r <- loadDLL interp dll
  case r of
    Nothing  -> return ()
    Just err ->
      if crash_early
        then cmdLineErrorIO err
        else
          when (diag_wopt Opt_WarnMissedExtraSharedLib diag_opts)
            $ logMsg logger
                (mkMCDiagnostic diag_opts $ WarningWithFlag Opt_WarnMissedExtraSharedLib)
                  noSrcSpan $ withPprStyle defaultUserStyle (note err)
  where
    diag_opts = initDiagOpts (hsc_dflags hsc_env)
    logger = hsc_logger hsc_env
    note err = vcat $ map text
      [ 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 :: Interp -> Platform -> UnitInfo -> IO ()
loadFrameworks interp platform pkg
    = when (platformUsesFrameworks platform) $ mapM_ load frameworks
  where
    fw_dirs    = map ST.unpack $ Packages.unitExtDepFrameworkDirs pkg
    frameworks = map ST.unpack $ Packages.unitExtDepFrameworks pkg

    load fw = do  r <- loadFramework interp fw_dirs fw
                  case r of
                    Nothing  -> return ()
                    Just err -> cmdLineErrorIO ("can't load framework: "
                                                ++ fw ++ " (" ++ err ++ ")" )
#endif

-- 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
  :: Interp
  -> HscEnv
  -> Bool
  -> [FilePath]
  -> [FilePath]
  -> String
  -> IO LibrarySpec
locateLib :: Interp
-> HscEnv
-> Bool
-> [String]
-> [String]
-> String
-> IO LibrarySpec
locateLib Interp
interp HscEnv
hsc_env Bool
is_hs [String]
lib_dirs [String]
gcc_dirs String
lib0
  | Bool -> Bool
not Bool
is_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.
    --
  =
#if defined(CAN_LOAD_DLL)
    findDll   user `orElse`
#endif
    Bool -> IO (Maybe LibrarySpec)
tryImpLib Bool
user forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
#if defined(CAN_LOAD_DLL)
    findDll   gcc  `orElse`
    findSysDll     `orElse`
#endif
    Bool -> IO (Maybe LibrarySpec)
tryImpLib Bool
gcc  forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
findArchive    forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
tryGcc         forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO LibrarySpec
assumeDll

  | Bool
loading_dynamic_hs_libs -- search for .so libraries first.
  = IO (Maybe LibrarySpec)
findHSDll     forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
findDynObject forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO LibrarySpec
assumeDll

  | Bool
otherwise
    -- use HSfoo.{o,p_o} if it exists, otherwise fallback to libHSfoo{,_p}.a
  = IO (Maybe LibrarySpec)
findObject  forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
findArchive forall {m :: * -> *} {b}. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO LibrarySpec
assumeDll

   where
     dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
     logger :: Logger
logger = HscEnv -> Logger
hsc_logger HscEnv
hsc_env
     diag_opts :: DiagOpts
diag_opts = DynFlags -> DiagOpts
initDiagOpts DynFlags
dflags
     dirs :: [String]
dirs   = [String]
lib_dirs forall a. [a] -> [a] -> [a]
++ [String]
gcc_dirs
     gcc :: Bool
gcc    = Bool
False
     user :: Bool
user   = Bool
True

     -- Emulate ld's behavior of treating $LIB in `-l:$LIB` as a literal file
     -- name
     (String
lib, Bool
verbatim) = case String
lib0 of
       Char
':' : String
rest -> (String
rest, Bool
True)
       String
other      -> (String
other, Bool
False)

     obj_file :: String
obj_file
       | Bool
is_hs Bool -> Bool -> Bool
&& Bool
loading_profiled_hs_libs = String
lib String -> String -> String
<.> String
"p_o"
       | Bool
otherwise = String
lib String -> String -> String
<.> String
"o"
     dyn_obj_file :: String
dyn_obj_file = String
lib String -> String -> String
<.> String
"dyn_o"
     arch_files :: [String]
arch_files
       | Bool
verbatim = [String
lib]
       | Bool
otherwise = [ String
"lib" forall a. [a] -> [a] -> [a]
++ String
lib forall a. [a] -> [a] -> [a]
++ String
lib_tag String -> String -> String
<.> String
"a"
                     , String
lib String -> String -> String
<.> String
"a" -- native code has no lib_tag
                     , String
"lib" forall a. [a] -> [a] -> [a]
++ String
lib
                     , String
lib
                     ]
     lib_tag :: String
lib_tag = if Bool
is_hs Bool -> Bool -> Bool
&& Bool
loading_profiled_hs_libs then String
"_p" else String
""

     loading_profiled_hs_libs :: Bool
loading_profiled_hs_libs = Interp -> Bool
interpreterProfiled Interp
interp
     loading_dynamic_hs_libs :: Bool
loading_dynamic_hs_libs  = Interp -> Bool
interpreterDynamic  Interp
interp

     import_libs :: [String]
import_libs
       | Bool
verbatim = [String
lib]
       | Bool
otherwise = [ String
lib String -> String -> String
<.> String
"lib"
                     , String
"lib" forall a. [a] -> [a] -> [a]
++ String
lib String -> String -> String
<.> String
"lib"
                     , String
"lib" forall a. [a] -> [a] -> [a]
++ String
lib String -> String -> String
<.> String
"dll.a"
                     , String
lib String -> String -> String
<.> String
"dll.a"
                     ]

     hs_dyn_lib_name :: String
hs_dyn_lib_name = String
lib forall a. [a] -> [a] -> [a]
++ GhcNameVersion -> String
dynLibSuffix (DynFlags -> GhcNameVersion
ghcNameVersion DynFlags
dflags)
     hs_dyn_lib_file :: String
hs_dyn_lib_file = Platform -> String -> String
platformHsSOName Platform
platform String
hs_dyn_lib_name

#if defined(CAN_LOAD_DLL)
     so_name     = platformSOName platform lib
     lib_so_name = "lib" ++ so_name
     dyn_lib_file
       | verbatim && any (`isExtensionOf` lib) [".so", ".dylib", ".dll"]
       = lib

       | ArchX86_64 <- arch
       , OSSolaris2 <- os
       = "64" </> so_name

       | otherwise
        = so_name
#endif

     findObject :: IO (Maybe LibrarySpec)
findObject    = forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a -> b) -> a -> b
$ [String] -> LibrarySpec
Objects forall b c a. (b -> c) -> (a -> b) -> a -> c
. (forall a. a -> [a] -> [a]
:[]))  forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
obj_file
     findDynObject :: IO (Maybe LibrarySpec)
findDynObject = forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a -> b) -> a -> b
$ [String] -> LibrarySpec
Objects forall b c a. (b -> c) -> (a -> b) -> a -> c
. (forall a. a -> [a] -> [a]
:[]))  forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
dyn_obj_file
     findArchive :: IO (Maybe LibrarySpec)
findArchive   = let local :: String -> IO (Maybe LibrarySpec)
local String
name = forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
Archive) forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
name
                     in  forall a. [IO (Maybe a)] -> IO (Maybe a)
apply (forall a b. (a -> b) -> [a] -> [b]
map String -> IO (Maybe LibrarySpec)
local [String]
arch_files)
     findHSDll :: IO (Maybe LibrarySpec)
findHSDll     = forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
DLLPath) forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
hs_dyn_lib_file
#if defined(CAN_LOAD_DLL)
     findDll    re = let dirs' = if re == user then lib_dirs else gcc_dirs
                     in liftM (fmap DLLPath) $ findFile dirs' dyn_lib_file
     findSysDll    = fmap (fmap $ DLL . dropExtension . takeFileName) $
                        findSystemLibrary interp so_name
#endif
     tryGcc :: IO (Maybe LibrarySpec)
tryGcc        = let search :: String -> [String] -> IO (Maybe String)
search   = Logger -> DynFlags -> String -> [String] -> IO (Maybe String)
searchForLibUsingGcc Logger
logger DynFlags
dflags
#if defined(CAN_LOAD_DLL)
                         dllpath  = liftM (fmap DLLPath)
                         short    = dllpath $ search so_name lib_dirs
                         full     = dllpath $ search lib_so_name lib_dirs
                         dlls     = [short, full]
#endif
                         gcc :: String -> IO (Maybe LibrarySpec)
gcc String
name = forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
Archive) forall a b. (a -> b) -> a -> b
$ String -> [String] -> IO (Maybe String)
search String
name [String]
lib_dirs
                         files :: [String]
files    = [String]
import_libs forall a. [a] -> [a] -> [a]
++ [String]
arch_files
                         archives :: [IO (Maybe LibrarySpec)]
archives = forall a b. (a -> b) -> [a] -> [b]
map String -> IO (Maybe LibrarySpec)
gcc [String]
files
                     in forall a. [IO (Maybe a)] -> IO (Maybe a)
apply forall a b. (a -> b) -> a -> b
$
#if defined(CAN_LOAD_DLL)
                          dlls ++
#endif
                          [IO (Maybe LibrarySpec)]
archives
     tryImpLib :: Bool -> IO (Maybe LibrarySpec)
tryImpLib Bool
re = case OS
os of
                       OS
OSMinGW32 ->
                        let dirs' :: [String]
dirs' = if Bool
re forall a. Eq a => a -> a -> Bool
== Bool
user then [String]
lib_dirs else [String]
gcc_dirs
                            implib :: String -> IO (Maybe LibrarySpec)
implib String
name = forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
Archive) forall a b. (a -> b) -> a -> b
$
                                            [String] -> String -> IO (Maybe String)
findFile [String]
dirs' String
name
                        in forall a. [IO (Maybe a)] -> IO (Maybe a)
apply (forall a b. (a -> b) -> [a] -> [b]
map String -> IO (Maybe LibrarySpec)
implib [String]
import_libs)
                       OS
_         -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing

     -- TH Makes use of the interpreter so this failure is not obvious.
     -- So we are nice and warn/inform users why we fail before we do.
     -- But only for haskell libraries, as C libraries don't have a
     -- profiling/non-profiling distinction to begin with.
     assumeDll :: IO LibrarySpec
assumeDll
      | Bool
is_hs
      , Bool -> Bool
not Bool
loading_dynamic_hs_libs
      , Interp -> Bool
interpreterProfiled Interp
interp
      = do
          let diag :: MessageClass
diag = DiagOpts -> DiagnosticReason -> MessageClass
mkMCDiagnostic DiagOpts
diag_opts DiagnosticReason
WarningWithoutFlag
          Logger -> MessageClass -> SrcSpan -> SDoc -> IO ()
logMsg Logger
logger MessageClass
diag SrcSpan
noSrcSpan forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultErrStyle forall a b. (a -> b) -> a -> b
$
            String -> SDoc
text String
"Interpreter failed to load profiled static library" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
lib SDoc -> SDoc -> SDoc
<> Char -> SDoc
char Char
'.' SDoc -> SDoc -> SDoc
$$
              String -> SDoc
text String
" \tTrying dynamic library instead. If this fails try to rebuild" SDoc -> SDoc -> SDoc
<+>
              String -> SDoc
text String
"libraries with profiling support."
          forall (m :: * -> *) a. Monad m => a -> m a
return (String -> LibrarySpec
DLL String
lib)
      | Bool
otherwise = forall (m :: * -> *) a. Monad m => a -> m a
return (String -> LibrarySpec
DLL String
lib)
     infixr `orElse`
     m (Maybe b)
f orElse :: m (Maybe b) -> m b -> m b
`orElse` m b
g = m (Maybe b)
f forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall b a. b -> (a -> b) -> Maybe a -> b
maybe m b
g forall (m :: * -> *) a. Monad m => a -> m a
return

     apply :: [IO (Maybe a)] -> IO (Maybe a)
     apply :: forall a. [IO (Maybe a)] -> IO (Maybe a)
apply []     = forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
     apply (IO (Maybe a)
x:[IO (Maybe a)]
xs) = do Maybe a
x' <- IO (Maybe a)
x
                       if forall a. Maybe a -> Bool
isJust Maybe a
x'
                          then forall (m :: * -> *) a. Monad m => a -> m a
return Maybe a
x'
                          else forall a. [IO (Maybe a)] -> IO (Maybe a)
apply [IO (Maybe a)]
xs

     platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
#if defined(CAN_LOAD_DLL)
     arch = platformArch platform
#endif
     os :: OS
os = Platform -> OS
platformOS Platform
platform

searchForLibUsingGcc :: Logger -> DynFlags -> String -> [FilePath] -> IO (Maybe FilePath)
searchForLibUsingGcc :: Logger -> DynFlags -> String -> [String] -> IO (Maybe String)
searchForLibUsingGcc Logger
logger DynFlags
dflags String
so [String]
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.
   String
str <- Logger -> DynFlags -> [Option] -> IO String
askLd Logger
logger DynFlags
dflags (forall a b. (a -> b) -> [a] -> [b]
map (String -> String -> Option
FileOption String
"-B") [String]
dirs
                          forall a. [a] -> [a] -> [a]
++ [String -> Option
Option String
"--print-file-name", String -> Option
Option String
so])
   let file :: String
file = case String -> [String]
lines String
str of
                []  -> String
""
                String
l:[String]
_ -> String
l
   if (String
file forall a. Eq a => a -> a -> Bool
== String
so)
      then forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
      else do Bool
b <- String -> IO Bool
doesFileExist String
file -- file could be a folder (see #16063)
              forall (m :: * -> *) a. Monad m => a -> m a
return (if Bool
b then forall a. a -> Maybe a
Just String
file else forall a. Maybe a
Nothing)

-- | Retrieve the list of search directory GCC and the System use to find
--   libraries and components. See Note [Fork/Exec Windows].
getGCCPaths :: Logger -> DynFlags -> OS -> IO [FilePath]
getGCCPaths :: Logger -> DynFlags -> OS -> IO [String]
getGCCPaths Logger
logger DynFlags
dflags OS
os
  = case OS
os of
      OS
OSMinGW32 ->
        do [String]
gcc_dirs <- Logger -> DynFlags -> String -> IO [String]
getGccSearchDirectory Logger
logger DynFlags
dflags String
"libraries"
           [String]
sys_dirs <- IO [String]
getSystemDirectories
           forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. Eq a => [a] -> [a]
nub forall a b. (a -> b) -> a -> b
$ [String]
gcc_dirs forall a. [a] -> [a] -> [a]
++ [String]
sys_dirs
      OS
_         -> forall (m :: * -> *) a. Monad m => a -> m a
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.
{-# NOINLINE gccSearchDirCache #-}
gccSearchDirCache :: IORef [(String, [String])]
gccSearchDirCache :: IORef [(String, [String])]
gccSearchDirCache = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ forall a. a -> IO (IORef a)
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 :: Logger -> DynFlags -> String -> IO [FilePath]
getGccSearchDirectory :: Logger -> DynFlags -> String -> IO [String]
getGccSearchDirectory Logger
logger DynFlags
dflags String
key = do
    [(String, [String])]
cache <- forall a. IORef a -> IO a
readIORef IORef [(String, [String])]
gccSearchDirCache
    case forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup String
key [(String, [String])]
cache of
      Just [String]
x  -> forall (m :: * -> *) a. Monad m => a -> m a
return [String]
x
      Maybe [String]
Nothing -> do
        String
str <- Logger -> DynFlags -> [Option] -> IO String
askLd Logger
logger DynFlags
dflags [String -> Option
Option String
"--print-search-dirs"]
        let line :: String
line = forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
str
            name :: String
name = String
key forall a. [a] -> [a] -> [a]
++ String
": ="
        if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
line
          then forall (m :: * -> *) a. Monad m => a -> m a
return []
          else do let val :: [String]
val = String -> [String]
split forall a b. (a -> b) -> a -> b
$ String -> String -> String
find String
name String
line
                  [String]
dirs <- forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM String -> IO Bool
doesDirectoryExist [String]
val
                  forall a. IORef a -> (a -> a) -> IO ()
modifyIORef' IORef [(String, [String])]
gccSearchDirCache ((String
key, [String]
dirs)forall a. a -> [a] -> [a]
:)
                  forall (m :: * -> *) a. Monad m => a -> m a
return [String]
val
      where split :: FilePath -> [FilePath]
            split :: String -> [String]
split String
r = case forall a. (a -> Bool) -> [a] -> ([a], [a])
break (forall a. Eq a => a -> a -> Bool
==Char
';') String
r of
                        (String
s, []    ) -> [String
s]
                        (String
s, (Char
_:String
xs)) -> String
s forall a. a -> [a] -> [a]
: String -> [String]
split String
xs

            find :: String -> String -> String
            find :: String -> String -> String
find String
r String
x = let lst :: [String]
lst = String -> [String]
lines String
x
                           val :: [String]
val = forall a. (a -> Bool) -> [a] -> [a]
filter (String
r forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [String]
lst
                       in if forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
val
                             then []
                             else case forall a. (a -> Bool) -> [a] -> ([a], [a])
break (forall a. Eq a => a -> a -> Bool
==Char
'=') (forall a. [a] -> a
head [String]
val) of
                                     (String
_ , [])    -> []
                                     (String
_, (Char
_:String
xs)) -> String
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 :: IO [String]
getSystemDirectories = forall (m :: * -> *) a. Monad m => a -> m a
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 :: String -> [String] -> IO [String]
addEnvPaths String
name [String]
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).
       String
working_dir <- IO String
getCurrentDirectory
       Maybe String
values <- String -> IO (Maybe String)
lookupEnv String
name
       case Maybe String
values of
         Maybe String
Nothing  -> forall (m :: * -> *) a. Monad m => a -> m a
return [String]
list
         Just String
arr -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ [String]
list forall a. [a] -> [a] -> [a]
++ String -> String -> [String]
splitEnv String
working_dir String
arr
    where
      splitEnv :: FilePath -> String -> [String]
      splitEnv :: String -> String -> [String]
splitEnv String
working_dir String
value =
        case forall a. (a -> Bool) -> [a] -> ([a], [a])
break (forall a. Eq a => a -> a -> Bool
== Char
envListSep) String
value of
          (String
x, []    ) ->
            [if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
x then String
working_dir else String
x]
          (String
x, (Char
_:String
xs)) ->
            (if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
x then String
working_dir else String
x) forall a. a -> [a] -> [a]
: String -> String -> [String]
splitEnv String
working_dir String
xs
#if defined(mingw32_HOST_OS)
      envListSep = ';'
#else
      envListSep :: Char
envListSep = Char
':'
#endif

-- ----------------------------------------------------------------------------
-- Loading a dynamic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)


{- **********************************************************************

                Helper functions

  ********************************************************************* -}

maybePutSDoc :: Logger -> SDoc -> IO ()
maybePutSDoc :: Logger -> SDoc -> IO ()
maybePutSDoc Logger
logger SDoc
s
    = forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Logger -> Int -> Bool
logVerbAtLeast Logger
logger Int
2) forall a b. (a -> b) -> a -> b
$
          Logger -> MessageClass -> SrcSpan -> SDoc -> IO ()
logMsg Logger
logger
              MessageClass
MCInteractive
              SrcSpan
noSrcSpan
              forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultUserStyle SDoc
s

maybePutStr :: Logger -> String -> IO ()
maybePutStr :: Logger -> String -> IO ()
maybePutStr Logger
logger String
s = Logger -> SDoc -> IO ()
maybePutSDoc Logger
logger (String -> SDoc
text String
s)

maybePutStrLn :: Logger -> String -> IO ()
maybePutStrLn :: Logger -> String -> IO ()
maybePutStrLn Logger
logger String
s = Logger -> SDoc -> IO ()
maybePutSDoc Logger
logger (String -> SDoc
text String
s SDoc -> SDoc -> SDoc
<> String -> SDoc
text String
"\n")