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

--
--  (c) The University of Glasgow 2002-2006
--
-- | The dynamic linker for GHCi.
--
-- This module deals with the top-level issues of dynamic linking,
-- calling the object-code linker and the byte-code linker where
-- necessary.
module GHC.Runtime.Linker
   ( getHValue
   , showLinkerState
   , linkExpr
   , linkDecls
   , unload
   , withExtendedLinkEnv
   , extendLinkEnv
   , deleteFromLinkEnv
   , extendLoadedPkgs
   , linkPackages
   , initDynLinker
   , linkModule
   , linkCmdLineLibs
   , uninitializedLinker
   )
where

#include "GhclibHsVersions.h"

import GHC.Prelude

import GHC.Runtime.Interpreter
import GHC.Runtime.Interpreter.Types
import GHCi.RemoteTypes
import GHC.Iface.Load
import GHC.ByteCode.Linker
import GHC.ByteCode.Asm
import GHC.ByteCode.Types
import GHC.Tc.Utils.Monad
import GHC.Unit.State as Packages
import GHC.Driver.Phases
import GHC.Driver.Finder
import GHC.Driver.Types
import GHC.Driver.Ways
import GHC.Types.Name
import GHC.Types.Name.Env
import GHC.Unit.Module
import GHC.Data.List.SetOps
import GHC.Runtime.Linker.Types (DynLinker(..), PersistentLinkerState(..))
import GHC.Driver.Session
import GHC.Types.Basic
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.Misc
import GHC.Utils.Error
import GHC.Types.SrcLoc
import qualified GHC.Data.Maybe as Maybes
import GHC.Types.Unique.DSet
import GHC.Data.FastString
import GHC.Platform
import GHC.SysTools
import GHC.SysTools.FileCleanup

-- Standard libraries
import Control.Monad

import qualified Data.Set as Set
import Data.Char (isSpace)
import Data.Function ((&))
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

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

                        The Linker's state

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

{-
The persistent linker state *must* match the actual state of the
C dynamic linker at all times.

The MVar used to hold the PersistentLinkerState contains a Maybe
PersistentLinkerState. The MVar serves to ensure mutual exclusion between
multiple loaded copies of the GHC library. The Maybe may be Nothing to
indicate that the linker has not yet been initialised.

The PersistentLinkerState maps Names to actual closures (for
interpreted code only), for use during linking.
-}

uninitializedLinker :: IO DynLinker
uninitializedLinker :: IO DynLinker
uninitializedLinker =
  Maybe PersistentLinkerState
-> IO (MVar (Maybe PersistentLinkerState))
forall a. a -> IO (MVar a)
newMVar Maybe PersistentLinkerState
forall a. Maybe a
Nothing IO (MVar (Maybe PersistentLinkerState))
-> (MVar (Maybe PersistentLinkerState) -> IO DynLinker)
-> IO DynLinker
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (DynLinker -> IO DynLinker
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DynLinker -> IO DynLinker)
-> (MVar (Maybe PersistentLinkerState) -> DynLinker)
-> MVar (Maybe PersistentLinkerState)
-> IO DynLinker
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MVar (Maybe PersistentLinkerState) -> DynLinker
DynLinker)

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

modifyPLS_ :: DynLinker -> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ :: DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl PersistentLinkerState -> IO PersistentLinkerState
f =
  MVar (Maybe PersistentLinkerState)
-> (Maybe PersistentLinkerState
    -> IO (Maybe PersistentLinkerState))
-> IO ()
forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ (DynLinker -> MVar (Maybe PersistentLinkerState)
dl_mpls DynLinker
dl) ((PersistentLinkerState -> Maybe PersistentLinkerState)
-> IO PersistentLinkerState -> IO (Maybe PersistentLinkerState)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap PersistentLinkerState -> Maybe PersistentLinkerState
forall (f :: * -> *) a. Applicative f => a -> f a
pure (IO PersistentLinkerState -> IO (Maybe PersistentLinkerState))
-> (Maybe PersistentLinkerState -> IO PersistentLinkerState)
-> Maybe PersistentLinkerState
-> IO (Maybe PersistentLinkerState)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PersistentLinkerState -> IO PersistentLinkerState
f (PersistentLinkerState -> IO PersistentLinkerState)
-> (Maybe PersistentLinkerState -> PersistentLinkerState)
-> Maybe PersistentLinkerState
-> IO PersistentLinkerState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PersistentLinkerState
-> Maybe PersistentLinkerState -> PersistentLinkerState
forall a. a -> Maybe a -> a
fromMaybe PersistentLinkerState
forall a. a
uninitialised)

modifyPLS :: DynLinker -> (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS :: DynLinker
-> (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS DynLinker
dl PersistentLinkerState -> IO (PersistentLinkerState, a)
f =
  MVar (Maybe PersistentLinkerState)
-> (Maybe PersistentLinkerState
    -> IO (Maybe PersistentLinkerState, a))
-> IO a
forall a b. MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar (DynLinker -> MVar (Maybe PersistentLinkerState)
dl_mpls DynLinker
dl) ((PersistentLinkerState -> Maybe PersistentLinkerState)
-> IO (PersistentLinkerState, a)
-> IO (Maybe PersistentLinkerState, a)
forall (f :: * -> *) t a b.
Functor f =>
(t -> a) -> f (t, b) -> f (a, b)
fmapFst PersistentLinkerState -> Maybe PersistentLinkerState
forall (f :: * -> *) a. Applicative f => a -> f a
pure (IO (PersistentLinkerState, a)
 -> IO (Maybe PersistentLinkerState, a))
-> (Maybe PersistentLinkerState -> IO (PersistentLinkerState, a))
-> Maybe PersistentLinkerState
-> IO (Maybe PersistentLinkerState, a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PersistentLinkerState -> IO (PersistentLinkerState, a)
f (PersistentLinkerState -> IO (PersistentLinkerState, a))
-> (Maybe PersistentLinkerState -> PersistentLinkerState)
-> Maybe PersistentLinkerState
-> IO (PersistentLinkerState, a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PersistentLinkerState
-> Maybe PersistentLinkerState -> PersistentLinkerState
forall a. a -> Maybe a -> a
fromMaybe PersistentLinkerState
forall a. a
uninitialised)
  where fmapFst :: (t -> a) -> f (t, b) -> f (a, b)
fmapFst t -> a
f = ((t, b) -> (a, b)) -> f (t, b) -> f (a, b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(t
x, b
y) -> (t -> a
f t
x, b
y))

readPLS :: DynLinker -> IO PersistentLinkerState
readPLS :: DynLinker -> IO PersistentLinkerState
readPLS DynLinker
dl =
  ((Maybe PersistentLinkerState -> PersistentLinkerState)
-> IO (Maybe PersistentLinkerState) -> IO PersistentLinkerState
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (PersistentLinkerState
-> Maybe PersistentLinkerState -> PersistentLinkerState
forall a. a -> Maybe a -> a
fromMaybe PersistentLinkerState
forall a. a
uninitialised) (IO (Maybe PersistentLinkerState) -> IO PersistentLinkerState)
-> (MVar (Maybe PersistentLinkerState)
    -> IO (Maybe PersistentLinkerState))
-> MVar (Maybe PersistentLinkerState)
-> IO PersistentLinkerState
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MVar (Maybe PersistentLinkerState)
-> IO (Maybe PersistentLinkerState)
forall a. MVar a -> IO a
readMVar) (DynLinker -> MVar (Maybe PersistentLinkerState)
dl_mpls DynLinker
dl)

modifyMbPLS_
  :: DynLinker -> (Maybe PersistentLinkerState -> IO (Maybe PersistentLinkerState)) -> IO ()
modifyMbPLS_ :: DynLinker
-> (Maybe PersistentLinkerState
    -> IO (Maybe PersistentLinkerState))
-> IO ()
modifyMbPLS_ DynLinker
dl Maybe PersistentLinkerState -> IO (Maybe PersistentLinkerState)
f = MVar (Maybe PersistentLinkerState)
-> (Maybe PersistentLinkerState
    -> IO (Maybe PersistentLinkerState))
-> IO ()
forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ (DynLinker -> MVar (Maybe PersistentLinkerState)
dl_mpls DynLinker
dl) Maybe PersistentLinkerState -> IO (Maybe PersistentLinkerState)
f

emptyPLS :: PersistentLinkerState
emptyPLS :: PersistentLinkerState
emptyPLS = PersistentLinkerState :: ClosureEnv
-> ItblEnv
-> [Linkable]
-> [Linkable]
-> [UnitId]
-> [(String, String)]
-> PersistentLinkerState
PersistentLinkerState
   { closure_env :: ClosureEnv
closure_env = ClosureEnv
forall a. NameEnv a
emptyNameEnv
   , itbl_env :: ItblEnv
itbl_env    = ItblEnv
forall a. NameEnv a
emptyNameEnv
   , pkgs_loaded :: [UnitId]
pkgs_loaded = [UnitId]
init_pkgs
   , bcos_loaded :: [Linkable]
bcos_loaded = []
   , objs_loaded :: [Linkable]
objs_loaded = []
   , 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 :: [UnitId]
init_pkgs = [UnitId
rtsUnitId]

extendLoadedPkgs :: DynLinker -> [UnitId] -> IO ()
extendLoadedPkgs :: DynLinker -> [UnitId] -> IO ()
extendLoadedPkgs DynLinker
dl [UnitId]
pkgs =
  DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
s ->
      PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
s{ pkgs_loaded :: [UnitId]
pkgs_loaded = [UnitId]
pkgs [UnitId] -> [UnitId] -> [UnitId]
forall a. [a] -> [a] -> [a]
++ PersistentLinkerState -> [UnitId]
pkgs_loaded PersistentLinkerState
s }

extendLinkEnv :: DynLinker -> [(Name,ForeignHValue)] -> IO ()
extendLinkEnv :: DynLinker -> [(Name, ForeignHValue)] -> IO ()
extendLinkEnv DynLinker
dl [(Name, ForeignHValue)]
new_bindings =
  DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \pls :: PersistentLinkerState
pls@PersistentLinkerState{[(String, String)]
[UnitId]
[Linkable]
ClosureEnv
ItblEnv
temp_sos :: [(String, String)]
pkgs_loaded :: [UnitId]
objs_loaded :: [Linkable]
bcos_loaded :: [Linkable]
itbl_env :: ItblEnv
closure_env :: ClosureEnv
temp_sos :: PersistentLinkerState -> [(String, String)]
objs_loaded :: PersistentLinkerState -> [Linkable]
bcos_loaded :: PersistentLinkerState -> [Linkable]
pkgs_loaded :: PersistentLinkerState -> [UnitId]
itbl_env :: PersistentLinkerState -> ItblEnv
closure_env :: PersistentLinkerState -> ClosureEnv
..} -> do
    let new_ce :: ClosureEnv
new_ce = ClosureEnv -> [(Name, ForeignHValue)] -> ClosureEnv
extendClosureEnv ClosureEnv
closure_env [(Name, ForeignHValue)]
new_bindings
    PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState -> IO PersistentLinkerState)
-> PersistentLinkerState -> IO PersistentLinkerState
forall a b. (a -> b) -> a -> b
$! PersistentLinkerState
pls{ closure_env :: ClosureEnv
closure_env = ClosureEnv
new_ce }
    -- strictness is important for not retaining old copies of the pls

deleteFromLinkEnv :: DynLinker -> [Name] -> IO ()
deleteFromLinkEnv :: DynLinker -> [Name] -> IO ()
deleteFromLinkEnv DynLinker
dl [Name]
to_remove =
  DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls -> do
    let ce :: ClosureEnv
ce = PersistentLinkerState -> ClosureEnv
closure_env PersistentLinkerState
pls
    let new_ce :: ClosureEnv
new_ce = ClosureEnv -> [Name] -> ClosureEnv
forall a. NameEnv a -> [Name] -> NameEnv a
delListFromNameEnv ClosureEnv
ce [Name]
to_remove
    PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
pls{ closure_env :: ClosureEnv
closure_env = ClosureEnv
new_ce }

-- | Get the 'HValue' associated with the given name.
--
-- May cause loading the module that contains the name.
--
-- Throws a 'ProgramError' if loading fails or the name cannot be found.
getHValue :: HscEnv -> Name -> IO ForeignHValue
getHValue :: HscEnv -> Name -> IO ForeignHValue
getHValue HscEnv
hsc_env Name
name = do
  let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env
  HscEnv -> IO ()
initDynLinker HscEnv
hsc_env
  PersistentLinkerState
pls <- DynLinker
-> (PersistentLinkerState
    -> IO (PersistentLinkerState, PersistentLinkerState))
-> IO PersistentLinkerState
forall a.
DynLinker
-> (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS DynLinker
dl ((PersistentLinkerState
  -> IO (PersistentLinkerState, PersistentLinkerState))
 -> IO PersistentLinkerState)
-> (PersistentLinkerState
    -> IO (PersistentLinkerState, PersistentLinkerState))
-> IO PersistentLinkerState
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls -> do
           if (Name -> Bool
isExternalName Name
name) then do
             (PersistentLinkerState
pls', SuccessFlag
ok) <- HscEnv
-> PersistentLinkerState
-> SrcSpan
-> [Module]
-> IO (PersistentLinkerState, SuccessFlag)
linkDependencies HscEnv
hsc_env PersistentLinkerState
pls SrcSpan
noSrcSpan
                              [HasDebugCallStack => Name -> Module
Name -> Module
nameModule Name
name]
             if (SuccessFlag -> Bool
failed SuccessFlag
ok) then GhcException -> IO (PersistentLinkerState, PersistentLinkerState)
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"")
                            else (PersistentLinkerState, PersistentLinkerState)
-> IO (PersistentLinkerState, PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState
pls', PersistentLinkerState
pls')
            else
             (PersistentLinkerState, PersistentLinkerState)
-> IO (PersistentLinkerState, PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState
pls, PersistentLinkerState
pls)
  case ClosureEnv -> Name -> Maybe (Name, ForeignHValue)
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv (PersistentLinkerState -> ClosureEnv
closure_env PersistentLinkerState
pls) Name
name of
    Just (Name
_,ForeignHValue
aa) -> ForeignHValue -> IO ForeignHValue
forall (m :: * -> *) a. Monad m => a -> m a
return ForeignHValue
aa
    Maybe (Name, ForeignHValue)
Nothing
        -> ASSERT2(isExternalName name, ppr name)
           do let sym_to_find :: FastString
sym_to_find = Name -> String -> FastString
nameToCLabel Name
name String
"closure"
              Maybe HValueRef
m <- HscEnv -> String -> IO (Maybe HValueRef)
lookupClosure HscEnv
hsc_env (FastString -> String
unpackFS FastString
sym_to_find)
              case Maybe HValueRef
m of
                Just HValueRef
hvref -> HscEnv -> HValueRef -> IO ForeignHValue
forall a. HscEnv -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue HscEnv
hsc_env HValueRef
hvref
                Maybe HValueRef
Nothing -> String -> String -> IO ForeignHValue
forall a. String -> String -> IO a
linkFail String
"GHC.Runtime.Linker.getHValue"
                             (FastString -> String
unpackFS FastString
sym_to_find)

linkDependencies :: HscEnv -> PersistentLinkerState
                 -> SrcSpan -> [Module]
                 -> IO (PersistentLinkerState, SuccessFlag)
linkDependencies :: HscEnv
-> PersistentLinkerState
-> SrcSpan
-> [Module]
-> IO (PersistentLinkerState, SuccessFlag)
linkDependencies HscEnv
hsc_env PersistentLinkerState
pls SrcSpan
span [Module]
needed_mods = do
--   initDynLinker (hsc_dflags hsc_env) dl
   let hpt :: HomePackageTable
hpt = HscEnv -> HomePackageTable
hsc_HPT 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 <- HscEnv -> SrcSpan -> IO (Maybe String)
checkNonStdWay HscEnv
hsc_env SrcSpan
span

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

   -- Link the packages and modules required
   PersistentLinkerState
pls1 <- HscEnv
-> [UnitId] -> PersistentLinkerState -> IO PersistentLinkerState
linkPackages' HscEnv
hsc_env [UnitId]
pkgs PersistentLinkerState
pls
   HscEnv
-> PersistentLinkerState
-> [Linkable]
-> IO (PersistentLinkerState, SuccessFlag)
linkModules HscEnv
hsc_env PersistentLinkerState
pls1 [Linkable]
lnks


-- | Temporarily extend the linker state.

withExtendedLinkEnv :: (ExceptionMonad m) =>
                       DynLinker -> [(Name,ForeignHValue)] -> m a -> m a
withExtendedLinkEnv :: DynLinker -> [(Name, ForeignHValue)] -> m a -> m a
withExtendedLinkEnv DynLinker
dl [(Name, ForeignHValue)]
new_env m a
action
    = m () -> (() -> m ()) -> (() -> m a) -> m a
forall (m :: * -> *) a c b.
MonadMask m =>
m a -> (a -> m c) -> (a -> m b) -> m b
MC.bracket (IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ DynLinker -> [(Name, ForeignHValue)] -> IO ()
extendLinkEnv DynLinker
dl [(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 = IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ do
            DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls ->
                let cur :: ClosureEnv
cur = PersistentLinkerState -> ClosureEnv
closure_env PersistentLinkerState
pls
                    new :: ClosureEnv
new = ClosureEnv -> [Name] -> ClosureEnv
forall a. NameEnv a -> [Name] -> NameEnv a
delListFromNameEnv ClosureEnv
cur (((Name, ForeignHValue) -> Name)
-> [(Name, ForeignHValue)] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map (Name, ForeignHValue) -> Name
forall a b. (a, b) -> a
fst [(Name, ForeignHValue)]
new_env)
                in PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
pls{ closure_env :: ClosureEnv
closure_env = ClosureEnv
new }


-- | Display the persistent linker state.
showLinkerState :: DynLinker -> IO SDoc
showLinkerState :: DynLinker -> IO SDoc
showLinkerState DynLinker
dl
  = do PersistentLinkerState
pls <- DynLinker -> IO PersistentLinkerState
readPLS DynLinker
dl
       SDoc -> IO SDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (SDoc -> IO SDoc) -> SDoc -> IO SDoc
forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultDumpStyle
                 ([SDoc] -> SDoc
vcat [String -> SDoc
text String
"----- Linker state -----",
                        String -> SDoc
text String
"Pkgs:" SDoc -> SDoc -> SDoc
<+> [UnitId] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PersistentLinkerState -> [UnitId]
pkgs_loaded PersistentLinkerState
pls),
                        String -> SDoc
text String
"Objs:" SDoc -> SDoc -> SDoc
<+> [Linkable] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PersistentLinkerState -> [Linkable]
objs_loaded PersistentLinkerState
pls),
                        String -> SDoc
text String
"BCOs:" SDoc -> SDoc -> SDoc
<+> [Linkable] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PersistentLinkerState -> [Linkable]
bcos_loaded PersistentLinkerState
pls)])


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

                        Initialisation

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

-- | Initialise the dynamic linker.  This entails
--
--  a) Calling the C initialisation procedure,
--
--  b) Loading any packages specified on the command line,
--
--  c) Loading any packages specified on the command line, now held in the
--     @-l@ options in @v_Opt_l@,
--
--  d) Loading any @.o\/.dll@ files specified on the command line, now held
--     in @ldInputs@,
--
--  e) Loading any MacOS frameworks.
--
-- NOTE: This function is idempotent; if called more than once, it does
-- nothing.  This is useful in Template Haskell, where we call it before
-- trying to link.
--
initDynLinker :: HscEnv -> IO ()
initDynLinker :: HscEnv -> IO ()
initDynLinker HscEnv
hsc_env = do
  let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env
  DynLinker
-> (Maybe PersistentLinkerState
    -> IO (Maybe PersistentLinkerState))
-> IO ()
modifyMbPLS_ DynLinker
dl ((Maybe PersistentLinkerState -> IO (Maybe PersistentLinkerState))
 -> IO ())
-> (Maybe PersistentLinkerState
    -> IO (Maybe PersistentLinkerState))
-> IO ()
forall a b. (a -> b) -> a -> b
$ \Maybe PersistentLinkerState
pls -> do
    case Maybe PersistentLinkerState
pls of
      Just  PersistentLinkerState
_ -> Maybe PersistentLinkerState -> IO (Maybe PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe PersistentLinkerState
pls
      Maybe PersistentLinkerState
Nothing -> PersistentLinkerState -> Maybe PersistentLinkerState
forall a. a -> Maybe a
Just (PersistentLinkerState -> Maybe PersistentLinkerState)
-> IO PersistentLinkerState -> IO (Maybe PersistentLinkerState)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HscEnv -> IO PersistentLinkerState
reallyInitDynLinker HscEnv
hsc_env

reallyInitDynLinker :: HscEnv -> IO PersistentLinkerState
reallyInitDynLinker :: HscEnv -> IO PersistentLinkerState
reallyInitDynLinker HscEnv
hsc_env = do
  -- Initialise the linker state
  let dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
      pls0 :: PersistentLinkerState
pls0 = PersistentLinkerState
emptyPLS

  -- (a) initialise the C dynamic linker
  HscEnv -> IO ()
initObjLinker HscEnv
hsc_env

  -- (b) Load packages from the command-line (Note [preload packages])
  PersistentLinkerState
pls <- HscEnv
-> [UnitId] -> PersistentLinkerState -> IO PersistentLinkerState
linkPackages' HscEnv
hsc_env (UnitState -> [UnitId]
preloadUnits (DynFlags -> UnitState
unitState DynFlags
dflags)) PersistentLinkerState
pls0

  -- steps (c), (d) and (e)
  HscEnv -> PersistentLinkerState -> IO PersistentLinkerState
linkCmdLineLibs' HscEnv
hsc_env PersistentLinkerState
pls


linkCmdLineLibs :: HscEnv -> IO ()
linkCmdLineLibs :: HscEnv -> IO ()
linkCmdLineLibs HscEnv
hsc_env = do
  let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env
  HscEnv -> IO ()
initDynLinker HscEnv
hsc_env
  DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls -> do
    HscEnv -> PersistentLinkerState -> IO PersistentLinkerState
linkCmdLineLibs' HscEnv
hsc_env PersistentLinkerState
pls

linkCmdLineLibs' :: HscEnv -> PersistentLinkerState -> IO PersistentLinkerState
linkCmdLineLibs' :: HscEnv -> PersistentLinkerState -> IO PersistentLinkerState
linkCmdLineLibs' HscEnv
hsc_env PersistentLinkerState
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

      -- (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" String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
minus_ls_1
                       OS
_         -> [String]
minus_ls_1
      -- See Note [Fork/Exec Windows]
      [String]
gcc_paths <- DynFlags -> OS -> IO [String]
getGCCPaths DynFlags
dflags OS
os

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

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

      [LibrarySpec]
libspecs
        <- (String -> IO LibrarySpec) -> [String] -> IO [LibrarySpec]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (HscEnv -> Bool -> [String] -> [String] -> String -> IO LibrarySpec
locateLib 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 <- (String -> IO (Maybe LibrarySpec))
-> [String] -> IO [Maybe LibrarySpec]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (DynFlags -> String -> IO (Maybe LibrarySpec)
classifyLdInput DynFlags
dflags)
                                [ 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 = [Maybe LibrarySpec] -> [LibrarySpec]
forall a. [Maybe a] -> [a]
catMaybes [Maybe LibrarySpec]
classified_ld_inputs
                           [LibrarySpec] -> [LibrarySpec] -> [LibrarySpec]
forall a. [a] -> [a] -> [a]
++ [LibrarySpec]
libspecs
                           [LibrarySpec] -> [LibrarySpec] -> [LibrarySpec]
forall a. [a] -> [a] -> [a]
++ (String -> LibrarySpec) -> [String] -> [LibrarySpec]
forall a b. (a -> b) -> [a] -> [b]
map String -> LibrarySpec
Framework [String]
frameworks
      if [LibrarySpec] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LibrarySpec]
cmdline_lib_specs then PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
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)
                                String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
framework_paths
                               [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
lib_paths_base
                               [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [ String -> String
takeDirectory String
dll | DLLPath String
dll <- [LibrarySpec]
libspecs ]
                      in [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
normalise [String]
paths
      let lib_paths :: [String]
lib_paths = [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
lib_paths_base [String] -> [String] -> [String]
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 <- (String -> IO (Ptr ())) -> [String] -> IO [Ptr ()]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (HscEnv -> String -> IO (Ptr ())
addLibrarySearchPath HscEnv
hsc_env) [String]
all_paths_env

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

      DynFlags -> String -> IO ()
maybePutStr DynFlags
dflags String
"final link ... "
      SuccessFlag
ok <- HscEnv -> IO SuccessFlag
resolveObjs HscEnv
hsc_env

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

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

      PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
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 [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
accum) [LibrarySpec]
rest
    go accum :: [String]
accum@(String
_:[String]
_) [LibrarySpec]
rest = [String] -> LibrarySpec
Objects ([String] -> [String]
forall a. [a] -> [a]
reverse [String]
accum) LibrarySpec -> [LibrarySpec] -> [LibrarySpec]
forall a. a -> [a] -> [a]
: [String] -> [LibrarySpec] -> [LibrarySpec]
go [] [LibrarySpec]
rest
    go [] (LibrarySpec
spec:[LibrarySpec]
rest) = LibrarySpec
spec LibrarySpec -> [LibrarySpec] -> [LibrarySpec]
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 :: DynFlags -> FilePath -> IO (Maybe LibrarySpec)
classifyLdInput :: DynFlags -> String -> IO (Maybe LibrarySpec)
classifyLdInput DynFlags
dflags String
f
  | Platform -> String -> Bool
isObjectFilename Platform
platform String
f = Maybe LibrarySpec -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a. Monad m => a -> m a
return (LibrarySpec -> Maybe LibrarySpec
forall a. a -> Maybe a
Just ([String] -> LibrarySpec
Objects [String
f]))
  | Platform -> String -> Bool
isDynLibFilename Platform
platform String
f = Maybe LibrarySpec -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a. Monad m => a -> m a
return (LibrarySpec -> Maybe LibrarySpec
forall a. a -> Maybe a
Just (String -> LibrarySpec
DLLPath String
f))
  | Bool
otherwise          = do
        DynFlags -> WarnReason -> Severity -> SrcSpan -> SDoc -> IO ()
putLogMsg DynFlags
dflags WarnReason
NoReason Severity
SevInfo SrcSpan
noSrcSpan
            (SDoc -> IO ()) -> SDoc -> IO ()
forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultUserStyle
            (String -> SDoc
text (String
"Warning: ignoring unrecognised input `" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
f String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"'"))
        Maybe LibrarySpec -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe LibrarySpec
forall a. Maybe a
Nothing
    where platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags

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

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

    DLL String
dll_unadorned -> do
      Maybe String
maybe_errstr <- HscEnv -> String -> IO (Maybe String)
loadDLL HscEnv
hsc_env (Platform -> String -> String
mkSOName Platform
platform String
dll_unadorned)
      case Maybe String
maybe_errstr of
         Maybe String
Nothing -> DynFlags -> String -> IO ()
maybePutStrLn DynFlags
dflags String
"done"
         Just String
mm | Platform -> OS
platformOS Platform
platform OS -> OS -> Bool
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" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
dll_unadorned) String -> String -> String
<.> String
"so"
           Maybe String
err2 <- HscEnv -> String -> IO (Maybe String)
loadDLL HscEnv
hsc_env String
libfile
           case Maybe String
err2 of
             Maybe String
Nothing -> DynFlags -> String -> IO ()
maybePutStrLn DynFlags
dflags String
"done"
             Just String
_  -> String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
mm [String]
lib_paths LibrarySpec
lib_spec
      PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
pls

    DLLPath String
dll_path -> do
      do Maybe String
maybe_errstr <- HscEnv -> String -> IO (Maybe String)
loadDLL HscEnv
hsc_env String
dll_path
         case Maybe String
maybe_errstr of
            Maybe String
Nothing -> DynFlags -> String -> IO ()
maybePutStrLn DynFlags
dflags String
"done"
            Just String
mm -> String -> [String] -> LibrarySpec -> IO ()
preloadFailed String
mm [String]
lib_paths LibrarySpec
lib_spec
         PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
pls

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

  where
    dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags 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 DynFlags -> String -> IO ()
maybePutStr DynFlags
dflags String
"failed.\n"
            GhcException -> IO ()
forall a. GhcException -> IO a
throwGhcExceptionIO (GhcException -> IO ()) -> GhcException -> IO ()
forall a b. (a -> b) -> a -> b
$
              String -> GhcException
CmdLineError (
                    String
"user specified .o/.so/.DLL could not be loaded ("
                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
sys_errmsg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")\nWhilst trying to load:  "
                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ LibrarySpec -> String
showLS LibrarySpec
spec String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nAdditional directories searched:"
                    String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if [String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
paths then String
" (none)" else
                        String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"\n" ((String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String
"   "String -> String -> String
forall a. [a] -> [a] -> [a]
++) [String]
paths)))

    -- Not interested in the paths in the static case.
    preload_statics :: p -> [String] -> IO (Bool, PersistentLinkerState)
preload_statics p
_paths [String]
names
       = do Bool
b <- [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or ([Bool] -> Bool) -> IO [Bool] -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (String -> IO Bool) -> [String] -> IO [Bool]
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 (Bool, PersistentLinkerState) -> IO (Bool, PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
False, PersistentLinkerState
pls)
                     else if Bool
hostIsDynamic
                             then  do PersistentLinkerState
pls1 <- HscEnv
-> PersistentLinkerState -> [String] -> IO PersistentLinkerState
dynLoadObjs HscEnv
hsc_env PersistentLinkerState
pls [String]
names
                                      (Bool, PersistentLinkerState) -> IO (Bool, PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, PersistentLinkerState
pls1)
                             else  do (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (HscEnv -> String -> IO ()
loadObj HscEnv
hsc_env) [String]
names
                                      (Bool, PersistentLinkerState) -> IO (Bool, PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, PersistentLinkerState
pls)

    preload_static_archive :: p -> String -> IO Bool
preload_static_archive p
_paths String
name
       = do Bool
b <- String -> IO Bool
doesFileExist String
name
            if Bool -> Bool
not Bool
b then Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
                     else do if Bool
hostIsDynamic
                                 then GhcException -> IO ()
forall a. GhcException -> IO a
throwGhcExceptionIO (GhcException -> IO ()) -> GhcException -> IO ()
forall a b. (a -> b) -> a -> b
$
                                      String -> GhcException
CmdLineError String
dynamic_msg
                                 else HscEnv -> String -> IO ()
loadArchive HscEnv
hsc_env String
name
                             Bool -> IO Bool
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 ("
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name String -> String -> String
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

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

-- | Link a single expression, /including/ first linking packages and
-- modules that this expression depends on.
--
-- Raises an IO exception ('ProgramError') if it can't find a compiled
-- version of the dependents to link.
--
linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
linkExpr HscEnv
hsc_env SrcSpan
span UnlinkedBCO
root_ul_bco
  = do {
     -- Initialise the linker (if it's not been done already)
   ; HscEnv -> IO ()
initDynLinker HscEnv
hsc_env

     -- Extract the DynLinker value for passing into required places
   ; let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env

     -- Take lock for the actual work.
   ; DynLinker
-> (PersistentLinkerState
    -> IO (PersistentLinkerState, ForeignHValue))
-> IO ForeignHValue
forall a.
DynLinker
-> (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS DynLinker
dl ((PersistentLinkerState
  -> IO (PersistentLinkerState, ForeignHValue))
 -> IO ForeignHValue)
-> (PersistentLinkerState
    -> IO (PersistentLinkerState, ForeignHValue))
-> IO ForeignHValue
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls0 -> do {

     -- Link the packages and modules required
   ; (PersistentLinkerState
pls, SuccessFlag
ok) <- HscEnv
-> PersistentLinkerState
-> SrcSpan
-> [Module]
-> IO (PersistentLinkerState, SuccessFlag)
linkDependencies HscEnv
hsc_env PersistentLinkerState
pls0 SrcSpan
span [Module]
needed_mods
   ; if SuccessFlag -> Bool
failed SuccessFlag
ok then
        GhcException -> IO (PersistentLinkerState, ForeignHValue)
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"")
     else do {

     -- Link the expression itself
     let ie :: ItblEnv
ie = PersistentLinkerState -> ItblEnv
itbl_env PersistentLinkerState
pls
         ce :: ClosureEnv
ce = PersistentLinkerState -> ClosureEnv
closure_env PersistentLinkerState
pls

     -- Link the necessary packages and linkables

   ; let nobreakarray :: a
nobreakarray = String -> a
forall a. HasCallStack => String -> a
error String
"no break array"
         bco_ix :: NameEnv Int
bco_ix = [(Name, Int)] -> NameEnv Int
forall a. [(Name, a)] -> NameEnv a
mkNameEnv [(UnlinkedBCO -> Name
unlinkedBCOName UnlinkedBCO
root_ul_bco, Int
0)]
   ; ResolvedBCO
resolved <- HscEnv
-> ItblEnv
-> ClosureEnv
-> NameEnv Int
-> RemoteRef BreakArray
-> UnlinkedBCO
-> IO ResolvedBCO
linkBCO HscEnv
hsc_env ItblEnv
ie ClosureEnv
ce NameEnv Int
bco_ix RemoteRef BreakArray
forall a. a
nobreakarray UnlinkedBCO
root_ul_bco
   ; [HValueRef
root_hvref] <- HscEnv -> [ResolvedBCO] -> IO [HValueRef]
createBCOs HscEnv
hsc_env [ResolvedBCO
resolved]
   ; ForeignHValue
fhv <- HscEnv -> HValueRef -> IO ForeignHValue
forall a. HscEnv -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue HscEnv
hsc_env HValueRef
root_hvref
   ; (PersistentLinkerState, ForeignHValue)
-> IO (PersistentLinkerState, ForeignHValue)
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState
pls, ForeignHValue
fhv)
   }}}
   where
     free_names :: [Name]
free_names = UniqDSet Name -> [Name]
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
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 -> MsgDoc -> IO a
dieWith :: DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
span SDoc
msg = GhcException -> IO a
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags (Severity -> SrcSpan -> SDoc -> SDoc
mkLocMessage Severity
SevFatal SrcSpan
span SDoc
msg)))


checkNonStdWay :: HscEnv -> SrcSpan -> IO (Maybe FilePath)
checkNonStdWay :: HscEnv -> SrcSpan -> IO (Maybe String)
checkNonStdWay HscEnv
hsc_env SrcSpan
srcspan
  | Just (ExternalInterp {}) <- HscEnv -> Maybe Interp
hsc_interp HscEnv
hsc_env = Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
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.

  | Set Way
hostFullWays Set Way -> Set Way -> Bool
forall a. Eq a => a -> a -> Bool
== Set Way
targetFullWays = Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
    -- Only if we are compiling with the same ways as GHC is built
    -- with, can we dynamically load those object files. (see #3604)

  | DynFlags -> String
objectSuf (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env) String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
normalObjectSuffix Bool -> Bool -> Bool
&& Bool -> Bool
not (Set Way -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Set Way
targetFullWays)
  = DynFlags -> SrcSpan -> IO (Maybe String)
failNonStd (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env) SrcSpan
srcspan

  | Bool
otherwise = Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just (String
hostWayTag String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"o"))
  where
    targetFullWays :: Set Way
targetFullWays = (Way -> Bool) -> Set Way -> Set Way
forall a. (a -> Bool) -> Set a -> Set a
Set.filter (Bool -> Bool
not (Bool -> Bool) -> (Way -> Bool) -> Way -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Way -> Bool
wayRTSOnly) (DynFlags -> Set Way
ways (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env))
    hostWayTag :: String
hostWayTag = case Set Way -> String
waysTag Set Way
hostFullWays of
                  String
"" -> String
""
                  String
tag -> String
tag String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_"

normalObjectSuffix :: String
normalObjectSuffix :: String
normalObjectSuffix = Phase -> String
phaseInputExt Phase
StopLn

failNonStd :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
failNonStd :: DynFlags -> SrcSpan -> IO (Maybe String)
failNonStd DynFlags
dflags SrcSpan
srcspan = DynFlags -> SrcSpan -> SDoc -> IO (Maybe String)
forall a. DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
srcspan (SDoc -> IO (Maybe String)) -> SDoc -> IO (Maybe String)
forall a b. (a -> b) -> a -> b
$
  String -> SDoc
text String
"Cannot load" SDoc -> SDoc -> SDoc
<+> SDoc
compWay SDoc -> SDoc -> SDoc
<+>
     String -> SDoc
text String
"objects when GHC is built" SDoc -> SDoc -> SDoc
<+> SDoc
ghciWay SDoc -> SDoc -> SDoc
$$
  String -> SDoc
text String
"To fix this, either:" SDoc -> SDoc -> SDoc
$$
  String -> SDoc
text String
"  (1) Use -fexternal-interpreter, or" SDoc -> SDoc -> SDoc
$$
  String -> SDoc
text String
"  (2) Build the program twice: once" SDoc -> SDoc -> SDoc
<+>
                       SDoc
ghciWay SDoc -> SDoc -> SDoc
<> String -> SDoc
text String
", and then" SDoc -> SDoc -> SDoc
$$
  String -> SDoc
text String
"      with" SDoc -> SDoc -> SDoc
<+> SDoc
compWay SDoc -> SDoc -> SDoc
<+>
     String -> SDoc
text String
"using -osuf to set a different object file suffix."
    where compWay :: SDoc
compWay
            | Way
WayDyn Way -> Set Way -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` DynFlags -> Set Way
ways DynFlags
dflags = String -> SDoc
text String
"-dynamic"
            | Way
WayProf Way -> Set Way -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` DynFlags -> Set Way
ways DynFlags
dflags = String -> SDoc
text String
"-prof"
            | Bool
otherwise = String -> SDoc
text String
"normal"
          ghciWay :: SDoc
ghciWay
            | Bool
hostIsDynamic = String -> SDoc
text String
"with -dynamic"
            | Bool
hostIsProfiled = String -> SDoc
text String
"with -prof"
            | Bool
otherwise = String -> SDoc
text String
"the normal way"

getLinkDeps :: HscEnv -> HomePackageTable
            -> PersistentLinkerState
            -> Maybe FilePath                   -- replace object suffices?
            -> SrcSpan                          -- for error messages
            -> [Module]                         -- If you need these
            -> IO ([Linkable], [UnitId])     -- ... then link these first
-- Fails with an IO exception if it can't find enough files

getLinkDeps :: HscEnv
-> HomePackageTable
-> PersistentLinkerState
-> Maybe String
-> SrcSpan
-> [Module]
-> IO ([Linkable], [UnitId])
getLinkDeps HscEnv
hsc_env HomePackageTable
hpt PersistentLinkerState
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)
      ; ([ModuleName]
mods_s, [UnitId]
pkgs_s) <- [Module]
-> UniqDSet ModuleName
-> UniqDSet UnitId
-> IO ([ModuleName], [UnitId])
follow_deps ((Module -> Bool) -> [Module] -> [Module]
forall a. (a -> Bool) -> [a] -> [a]
filterOut Module -> Bool
isInteractiveModule [Module]
mods)
                                        UniqDSet ModuleName
forall a. UniqDSet a
emptyUniqDSet UniqDSet UnitId
forall a. UniqDSet a
emptyUniqDSet;

      ; let {
        -- 2.  Exclude ones already linked
        --      Main reason: avoid findModule calls in get_linkable
            mods_needed :: [ModuleName]
mods_needed = [ModuleName]
mods_s [ModuleName] -> [ModuleName] -> [ModuleName]
forall a. Ord a => [a] -> [a] -> [a]
`minusList` [ModuleName]
linked_mods     ;
            pkgs_needed :: [UnitId]
pkgs_needed = [UnitId]
pkgs_s [UnitId] -> [UnitId] -> [UnitId]
forall a. Ord a => [a] -> [a] -> [a]
`minusList` PersistentLinkerState -> [UnitId]
pkgs_loaded PersistentLinkerState
pls ;

            linked_mods :: [ModuleName]
linked_mods = (Linkable -> ModuleName) -> [Linkable] -> [ModuleName]
forall a b. (a -> b) -> [a] -> [b]
map (Module -> ModuleName
forall unit. GenModule unit -> ModuleName
moduleName(Module -> ModuleName)
-> (Linkable -> Module) -> Linkable -> ModuleName
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Linkable -> Module
linkableModule)
                                (PersistentLinkerState -> [Linkable]
objs_loaded PersistentLinkerState
pls [Linkable] -> [Linkable] -> [Linkable]
forall a. [a] -> [a] -> [a]
++ PersistentLinkerState -> [Linkable]
bcos_loaded PersistentLinkerState
pls)  }

        -- 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 <- (ModuleName -> IO Linkable) -> [ModuleName] -> IO [Linkable]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (String -> ModuleName -> IO Linkable
get_linkable String
osuf) [ModuleName]
mods_needed

      ; ([Linkable], [UnitId]) -> IO ([Linkable], [UnitId])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Linkable]
lnks_needed, [UnitId]
pkgs_needed) }
  where
    dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
    this_pkg :: Unit
this_pkg = DynFlags -> Unit
homeUnit DynFlags
dflags

        -- The ModIface contains the transitive closure of the module dependencies
        -- within the current package, *except* for boot modules: if we encounter
        -- a boot module, we have to find its real interface and discover the
        -- dependencies of that.  Hence we need to traverse the dependency
        -- tree recursively.  See bug #936, testcase ghci/prog007.
    follow_deps :: [Module]             -- modules to follow
                -> UniqDSet ModuleName         -- accum. module dependencies
                -> UniqDSet UnitId          -- accum. package dependencies
                -> IO ([ModuleName], [UnitId]) -- result
    follow_deps :: [Module]
-> UniqDSet ModuleName
-> UniqDSet UnitId
-> IO ([ModuleName], [UnitId])
follow_deps []     UniqDSet ModuleName
acc_mods UniqDSet UnitId
acc_pkgs
        = ([ModuleName], [UnitId]) -> IO ([ModuleName], [UnitId])
forall (m :: * -> *) a. Monad m => a -> m a
return (UniqDSet ModuleName -> [ModuleName]
forall a. UniqDSet a -> [a]
uniqDSetToList UniqDSet ModuleName
acc_mods, UniqDSet UnitId -> [UnitId]
forall a. UniqDSet a -> [a]
uniqDSetToList UniqDSet UnitId
acc_pkgs)
    follow_deps (Module
mod:[Module]
mods) UniqDSet ModuleName
acc_mods UniqDSet UnitId
acc_pkgs
        = do
          MaybeErr SDoc ModIface
mb_iface <- SDoc
-> HscEnv
-> IfG (MaybeErr SDoc ModIface)
-> IO (MaybeErr SDoc ModIface)
forall a. SDoc -> HscEnv -> IfG a -> IO a
initIfaceCheck (String -> SDoc
text String
"getLinkDeps") HscEnv
hsc_env (IfG (MaybeErr SDoc ModIface) -> IO (MaybeErr SDoc ModIface))
-> IfG (MaybeErr SDoc ModIface) -> IO (MaybeErr SDoc ModIface)
forall a b. (a -> b) -> a -> b
$
                        SDoc -> Module -> WhereFrom -> IfG (MaybeErr SDoc ModIface)
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      -> GhcException -> IO ModIface
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags SDoc
err))
                    Maybes.Succeeded ModIface
iface -> ModIface -> IO ModIface
forall (m :: * -> *) a. Monad m => a -> m a
return ModIface
iface

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

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

            pkg_deps :: [(UnitId, Bool)]
pkg_deps = Dependencies -> [(UnitId, Bool)]
dep_pkgs Dependencies
deps
            ([ModuleName]
boot_deps, [ModuleName]
mod_deps) = ((ModuleNameWithIsBoot -> Either ModuleName ModuleName)
 -> [ModuleNameWithIsBoot] -> ([ModuleName], [ModuleName]))
-> [ModuleNameWithIsBoot]
-> (ModuleNameWithIsBoot -> Either ModuleName ModuleName)
-> ([ModuleName], [ModuleName])
forall a b c. (a -> b -> c) -> b -> a -> c
flip (ModuleNameWithIsBoot -> Either ModuleName ModuleName)
-> [ModuleNameWithIsBoot] -> ([ModuleName], [ModuleName])
forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith (Dependencies -> [ModuleNameWithIsBoot]
dep_mods Dependencies
deps) ((ModuleNameWithIsBoot -> Either ModuleName ModuleName)
 -> ([ModuleName], [ModuleName]))
-> (ModuleNameWithIsBoot -> Either ModuleName ModuleName)
-> ([ModuleName], [ModuleName])
forall a b. (a -> b) -> a -> b
$
              \ (GWIB { gwib_mod :: forall mod. GenWithIsBoot mod -> mod
gwib_mod = ModuleName
m, gwib_isBoot :: forall mod. GenWithIsBoot mod -> IsBootInterface
gwib_isBoot = IsBootInterface
is_boot }) ->
                ModuleName
m ModuleName
-> (ModuleName -> Either ModuleName ModuleName)
-> Either ModuleName ModuleName
forall a b. a -> (a -> b) -> b
& case IsBootInterface
is_boot of
                  IsBootInterface
IsBoot -> ModuleName -> Either ModuleName ModuleName
forall a b. a -> Either a b
Left
                  IsBootInterface
NotBoot -> ModuleName -> Either ModuleName ModuleName
forall a b. b -> Either a b
Right

            boot_deps' :: [ModuleName]
boot_deps' = (ModuleName -> Bool) -> [ModuleName] -> [ModuleName]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (ModuleName -> Bool) -> ModuleName -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ModuleName -> UniqDSet ModuleName -> Bool
forall a. Uniquable a => a -> UniqDSet a -> Bool
`elementOfUniqDSet` UniqDSet ModuleName
acc_mods)) [ModuleName]
boot_deps
            acc_mods' :: UniqDSet ModuleName
acc_mods'  = UniqDSet ModuleName -> [ModuleName] -> UniqDSet ModuleName
forall a. Uniquable a => UniqDSet a -> [a] -> UniqDSet a
addListToUniqDSet UniqDSet ModuleName
acc_mods (Module -> ModuleName
forall unit. GenModule unit -> ModuleName
moduleName Module
mod ModuleName -> [ModuleName] -> [ModuleName]
forall a. a -> [a] -> [a]
: [ModuleName]
mod_deps)
            acc_pkgs' :: UniqDSet UnitId
acc_pkgs'  = UniqDSet UnitId -> [UnitId] -> UniqDSet UnitId
forall a. Uniquable a => UniqDSet a -> [a] -> UniqDSet a
addListToUniqDSet UniqDSet UnitId
acc_pkgs ([UnitId] -> UniqDSet UnitId) -> [UnitId] -> UniqDSet UnitId
forall a b. (a -> b) -> a -> b
$ ((UnitId, Bool) -> UnitId) -> [(UnitId, Bool)] -> [UnitId]
forall a b. (a -> b) -> [a] -> [b]
map (UnitId, Bool) -> UnitId
forall a b. (a, b) -> a
fst [(UnitId, Bool)]
pkg_deps
          --
          if Unit
pkg Unit -> Unit -> Bool
forall a. Eq a => a -> a -> Bool
/= Unit
this_pkg
             then [Module]
-> UniqDSet ModuleName
-> UniqDSet UnitId
-> IO ([ModuleName], [UnitId])
follow_deps [Module]
mods UniqDSet ModuleName
acc_mods (UniqDSet UnitId -> UnitId -> UniqDSet UnitId
forall a. Uniquable a => UniqDSet a -> a -> UniqDSet a
addOneToUniqDSet UniqDSet UnitId
acc_pkgs' (Unit -> UnitId
toUnitId Unit
pkg))
             else [Module]
-> UniqDSet ModuleName
-> UniqDSet UnitId
-> IO ([ModuleName], [UnitId])
follow_deps ((ModuleName -> Module) -> [ModuleName] -> [Module]
forall a b. (a -> b) -> [a] -> [b]
map (Unit -> ModuleName -> Module
forall u. u -> ModuleName -> GenModule u
mkModule Unit
this_pkg) [ModuleName]
boot_deps' [Module] -> [Module] -> [Module]
forall a. [a] -> [a] -> [a]
++ [Module]
mods)
                              UniqDSet ModuleName
acc_mods' UniqDSet UnitId
acc_pkgs'
        where
            msg :: SDoc
msg = String -> SDoc
text String
"need to link module" SDoc -> SDoc -> SDoc
<+> Module -> 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 :: a -> IO a
link_boot_mod_error a
mod =
        GhcException -> IO a
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags (
            String -> SDoc
text String
"module" SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
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 :: a -> IO b
no_obj a
mod = DynFlags -> SrcSpan -> SDoc -> IO b
forall a. DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
span (SDoc -> IO b) -> SDoc -> IO b
forall a b. (a -> b) -> a -> b
$
                     String -> SDoc
text String
"cannot find object file for module " SDoc -> SDoc -> SDoc
<>
                        SDoc -> SDoc
quotes (a -> SDoc
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 -> ModuleName -> IO Linkable
get_linkable String
osuf ModuleName
mod_name      -- A home-package module
        | Just HomeModInfo
mod_info <- HomePackageTable -> ModuleName -> Maybe HomeModInfo
lookupHpt HomePackageTable
hpt ModuleName
mod_name
        = Linkable -> IO Linkable
adjust_linkable (String -> Maybe Linkable -> 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...
             FindResult
mb_stuff <- HscEnv -> ModuleName -> IO FindResult
findHomeModule HscEnv
hsc_env ModuleName
mod_name
             case FindResult
mb_stuff of
                  Found ModLocation
loc Module
mod -> ModLocation -> Module -> IO Linkable
found ModLocation
loc Module
mod
                  FindResult
_ -> ModuleName -> IO Linkable
forall a a. Outputable a => a -> IO a
no_obj ModuleName
mod_name
        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  -> Module -> IO Linkable
forall a a. Outputable a => a -> IO a
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 <- (Unlinked -> IO Unlinked) -> [Unlinked] -> IO [Unlinked]
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)
                        Linkable -> IO Linkable
forall (m :: * -> *) a. Monad m => a -> m a
return Linkable
lnk{ linkableUnlinked :: [Unlinked]
linkableUnlinked=[Unlinked]
new_uls }
                | Bool
otherwise =
                        Linkable -> IO Linkable
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
                MASSERT(osuf `isSuffixOf` file)
                let file_base :: String
file_base = Maybe String -> String
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 DynFlags -> SrcSpan -> SDoc -> IO Unlinked
forall a. DynFlags -> SrcSpan -> SDoc -> IO a
dieWith DynFlags
dflags SrcSpan
span (SDoc -> IO Unlinked) -> SDoc -> IO Unlinked
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 Unlinked -> IO Unlinked
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Unlinked
DotO String
new_file)
            adjust_ul String
_ (DotA String
fp) = String -> IO Unlinked
forall a. String -> a
panic (String
"adjust_ul DotA " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
fp)
            adjust_ul String
_ (DotDLL String
fp) = String -> IO Unlinked
forall a. String -> a
panic (String
"adjust_ul DotDLL " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
fp)
            adjust_ul String
_ l :: Unlinked
l@(BCOs {}) = Unlinked -> IO Unlinked
forall (m :: * -> *) a. Monad m => a -> m a
return Unlinked
l



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

              Loading a Decls statement

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

linkDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO ()
linkDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO ()
linkDecls HscEnv
hsc_env SrcSpan
span cbc :: CompiledByteCode
cbc@CompiledByteCode{[RemotePtr ()]
[FFIInfo]
[UnlinkedBCO]
Maybe ModBreaks
ItblEnv
bc_strs :: CompiledByteCode -> [RemotePtr ()]
bc_itbls :: CompiledByteCode -> ItblEnv
bc_ffis :: CompiledByteCode -> [FFIInfo]
bc_breaks :: CompiledByteCode -> Maybe ModBreaks
bc_bcos :: CompiledByteCode -> [UnlinkedBCO]
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)
    HscEnv -> IO ()
initDynLinker HscEnv
hsc_env

    -- Extract the DynLinker for passing into required places
    let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env

    -- Take lock for the actual work.
    DynLinker
-> (PersistentLinkerState -> IO (PersistentLinkerState, ()))
-> IO ()
forall a.
DynLinker
-> (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS DynLinker
dl ((PersistentLinkerState -> IO (PersistentLinkerState, ()))
 -> IO ())
-> (PersistentLinkerState -> IO (PersistentLinkerState, ()))
-> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls0 -> do

    -- Link the packages and modules required
    (PersistentLinkerState
pls, SuccessFlag
ok) <- HscEnv
-> PersistentLinkerState
-> SrcSpan
-> [Module]
-> IO (PersistentLinkerState, SuccessFlag)
linkDependencies HscEnv
hsc_env PersistentLinkerState
pls0 SrcSpan
span [Module]
needed_mods
    if SuccessFlag -> Bool
failed SuccessFlag
ok
      then GhcException -> IO (PersistentLinkerState, ())
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"")
      else do

    -- Link the expression itself
    let ie :: ItblEnv
ie = ItblEnv -> ItblEnv -> ItblEnv
forall a. NameEnv a -> NameEnv a -> NameEnv a
plusNameEnv (PersistentLinkerState -> ItblEnv
itbl_env PersistentLinkerState
pls) ItblEnv
bc_itbls
        ce :: ClosureEnv
ce = PersistentLinkerState -> ClosureEnv
closure_env PersistentLinkerState
pls

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

    needed_mods :: [Module]
    needed_mods :: [Module]
needed_mods = [ HasDebugCallStack => Name -> Module
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

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

linkModule :: HscEnv -> Module -> IO ()
linkModule :: HscEnv -> Module -> IO ()
linkModule HscEnv
hsc_env Module
mod = do
  HscEnv -> IO ()
initDynLinker HscEnv
hsc_env
  let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env
  DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls -> do
    (PersistentLinkerState
pls', SuccessFlag
ok) <- HscEnv
-> PersistentLinkerState
-> SrcSpan
-> [Module]
-> IO (PersistentLinkerState, SuccessFlag)
linkDependencies HscEnv
hsc_env PersistentLinkerState
pls SrcSpan
noSrcSpan [Module
mod]
    if (SuccessFlag -> Bool
failed SuccessFlag
ok) then GhcException -> IO PersistentLinkerState
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
ProgramError String
"could not link module")
      else PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
pls'

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

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

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

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

        let ([Linkable]
objs, [Linkable]
bcos) = (Linkable -> Bool) -> [Linkable] -> ([Linkable], [Linkable])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Linkable -> Bool
isObjectLinkable
                              ((Linkable -> [Linkable]) -> [Linkable] -> [Linkable]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Linkable -> [Linkable]
partitionLinkable [Linkable]
linkables)

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

        if SuccessFlag -> Bool
failed SuccessFlag
ok_flag then
                (PersistentLinkerState, SuccessFlag)
-> IO (PersistentLinkerState, SuccessFlag)
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState
pls1, SuccessFlag
Failed)
          else do
                PersistentLinkerState
pls2 <- HscEnv
-> PersistentLinkerState -> [Linkable] -> IO PersistentLinkerState
dynLinkBCOs HscEnv
hsc_env PersistentLinkerState
pls1 [Linkable]
bcos
                (PersistentLinkerState, SuccessFlag)
-> IO (PersistentLinkerState, SuccessFlag)
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState
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 = (Unlinked -> Bool) -> [Unlinked] -> [Unlinked]
forall a. (a -> Bool) -> [a] -> [a]
filter Unlinked -> Bool
isObject [Unlinked]
li_uls
         li_uls_bco :: [Unlinked]
li_uls_bco = (Unlinked -> Bool) -> [Unlinked] -> [Unlinked]
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 :: [Linkable] -> Module -> Maybe Linkable
findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
findModuleLinkable_maybe [Linkable]
lis Module
mod
   = case [UTCTime -> Module -> [Unlinked] -> Linkable
LM UTCTime
time Module
nm [Unlinked]
us | LM UTCTime
time Module
nm [Unlinked]
us <- [Linkable]
lis, Module
nm Module -> Module -> Bool
forall a. Eq a => a -> a -> Bool
== Module
mod] of
        []   -> Maybe Linkable
forall a. Maybe a
Nothing
        [Linkable
li] -> Linkable -> Maybe Linkable
forall a. a -> Maybe a
Just Linkable
li
        [Linkable]
_    -> String -> SDoc -> Maybe Linkable
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"findModuleLinkable" (Module -> SDoc
forall a. Outputable a => a -> SDoc
ppr Module
mod)

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


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

                The object-code linker

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

dynLinkObjs :: HscEnv -> PersistentLinkerState -> [Linkable]
            -> IO (PersistentLinkerState, SuccessFlag)
dynLinkObjs :: HscEnv
-> PersistentLinkerState
-> [Linkable]
-> IO (PersistentLinkerState, SuccessFlag)
dynLinkObjs HscEnv
hsc_env PersistentLinkerState
pls [Linkable]
objs = do
        -- Load the object files and link them
        let ([Linkable]
objs_loaded', [Linkable]
new_objs) = [Linkable] -> [Linkable] -> ([Linkable], [Linkable])
rmDupLinkables (PersistentLinkerState -> [Linkable]
objs_loaded PersistentLinkerState
pls) [Linkable]
objs
            pls1 :: PersistentLinkerState
pls1                     = PersistentLinkerState
pls { objs_loaded :: [Linkable]
objs_loaded = [Linkable]
objs_loaded' }
            unlinkeds :: [Unlinked]
unlinkeds                = (Linkable -> [Unlinked]) -> [Linkable] -> [Unlinked]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Linkable -> [Unlinked]
linkableUnlinked [Linkable]
new_objs
            wanted_objs :: [String]
wanted_objs              = (Unlinked -> String) -> [Unlinked] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Unlinked -> String
nameOfObject [Unlinked]
unlinkeds

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

                    -- Link them all together
                    SuccessFlag
ok <- HscEnv -> IO SuccessFlag
resolveObjs HscEnv
hsc_env

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


dynLoadObjs :: HscEnv -> PersistentLinkerState -> [FilePath]
            -> IO PersistentLinkerState
dynLoadObjs :: HscEnv
-> PersistentLinkerState -> [String] -> IO PersistentLinkerState
dynLoadObjs HscEnv
_       PersistentLinkerState
pls                           []   = PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
pls
dynLoadObjs HscEnv
hsc_env pls :: PersistentLinkerState
pls@PersistentLinkerState{[(String, String)]
[UnitId]
[Linkable]
ClosureEnv
ItblEnv
temp_sos :: [(String, String)]
pkgs_loaded :: [UnitId]
objs_loaded :: [Linkable]
bcos_loaded :: [Linkable]
itbl_env :: ItblEnv
closure_env :: ClosureEnv
temp_sos :: PersistentLinkerState -> [(String, String)]
objs_loaded :: PersistentLinkerState -> [Linkable]
bcos_loaded :: PersistentLinkerState -> [Linkable]
pkgs_loaded :: PersistentLinkerState -> [UnitId]
itbl_env :: PersistentLinkerState -> ItblEnv
closure_env :: PersistentLinkerState -> ClosureEnv
..} [String]
objs = do
    let dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
    let platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
    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) <-
      DynFlags
-> TempFileLifetime -> String -> IO (String, String, String)
newTempLibName DynFlags
dflags TempFileLifetime
TFL_CurrentModule (Platform -> String
soExt 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 =
                           (String -> [Option]) -> [String] -> [Option]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\String
l -> [ String -> Option
Option (String
"-l" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
l) ])
                                     ([String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (String, String) -> String
forall a b. (a, b) -> b
snd ((String, String) -> String) -> [(String, String)] -> [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(String, String)]
temp_sos)
                        [Option] -> [Option] -> [Option]
forall a. [a] -> [a] -> [a]
++ (String -> [Option]) -> [String] -> [Option]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\String
lp -> String -> Option
Option (String
"-L" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
lp)
                                          Option -> [Option] -> [Option]
forall a. a -> [a] -> [a]
: if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_RPath DynFlags
dflags
                                            then [ String -> Option
Option String
"-Xlinker"
                                                 , String -> Option
Option String
"-rpath"
                                                 , String -> Option
Option String
"-Xlinker"
                                                 , String -> Option
Option String
lp ]
                                            else [])
                                     ([String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (String, String) -> String
forall a b. (a, b) -> a
fst ((String, String) -> String) -> [(String, String)] -> [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(String, String)]
temp_sos)
                        [Option] -> [Option] -> [Option]
forall a. [a] -> [a] -> [a]
++ (String -> [Option]) -> [String] -> [Option]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap
                             (\String
lp -> String -> Option
Option (String
"-L" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
lp)
                                  Option -> [Option] -> [Option]
forall a. a -> [a] -> [a]
: if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_RPath DynFlags
dflags
                                    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]
                        [Option] -> [Option] -> [Option]
forall a. [a] -> [a] -> [a]
++ (String -> Option) -> [String] -> [Option]
forall a b. (a -> b) -> [a] -> [b]
map (\String
l -> String -> Option
Option (String
"-l" String -> String -> String
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.
                      ways :: Set Way
ways = Way -> Set Way
forall a. a -> Set a
Set.singleton Way
WayDyn,
                      outputFile :: Maybe String
outputFile = String -> Maybe String
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.
    DynFlags -> [String] -> [UnitId] -> IO ()
linkDynLib DynFlags
dflags2 [String]
objs [UnitId]
pkgs_loaded

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

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

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

                The byte-code linker

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


dynLinkBCOs :: HscEnv -> PersistentLinkerState -> [Linkable]
            -> IO PersistentLinkerState
dynLinkBCOs :: HscEnv
-> PersistentLinkerState -> [Linkable] -> IO PersistentLinkerState
dynLinkBCOs HscEnv
hsc_env PersistentLinkerState
pls [Linkable]
bcos = do

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

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


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

        [(Name, HValueRef)]
names_and_refs <- HscEnv
-> ItblEnv
-> ClosureEnv
-> [CompiledByteCode]
-> IO [(Name, HValueRef)]
linkSomeBCOs HscEnv
hsc_env 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) = ((Name, HValueRef) -> Bool)
-> [(Name, HValueRef)]
-> ([(Name, HValueRef)], [(Name, HValueRef)])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Name -> Bool
isExternalName(Name -> Bool)
-> ((Name, HValueRef) -> Name) -> (Name, HValueRef) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Name, HValueRef) -> Name
forall a b. (a, b) -> a
fst) [(Name, HValueRef)]
names_and_refs

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

        PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
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 :: HscEnv
             -> ItblEnv
             -> ClosureEnv
             -> [CompiledByteCode]
             -> IO [(Name,HValueRef)]
                        -- The returned HValueRefs are associated 1-1 with
                        -- the incoming unlinked BCOs.  Each gives the
                        -- value of the corresponding unlinked BCO

linkSomeBCOs :: HscEnv
-> ItblEnv
-> ClosureEnv
-> [CompiledByteCode]
-> IO [(Name, HValueRef)]
linkSomeBCOs HscEnv
hsc_env ItblEnv
ie ClosureEnv
ce [CompiledByteCode]
mods = (CompiledByteCode
 -> ([(RemoteRef BreakArray, [UnlinkedBCO])]
     -> IO [(Name, HValueRef)])
 -> [(RemoteRef BreakArray, [UnlinkedBCO])]
 -> IO [(Name, HValueRef)])
-> ([(RemoteRef BreakArray, [UnlinkedBCO])]
    -> IO [(Name, HValueRef)])
-> [CompiledByteCode]
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
-> IO [(Name, HValueRef)]
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr CompiledByteCode
-> ([(RemoteRef BreakArray, [UnlinkedBCO])]
    -> IO [(Name, HValueRef)])
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
-> IO [(Name, HValueRef)]
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{[RemotePtr ()]
[FFIInfo]
[UnlinkedBCO]
Maybe ModBreaks
ItblEnv
bc_breaks :: Maybe ModBreaks
bc_strs :: [RemotePtr ()]
bc_ffis :: [FFIInfo]
bc_itbls :: ItblEnv
bc_bcos :: [UnlinkedBCO]
bc_strs :: CompiledByteCode -> [RemotePtr ()]
bc_itbls :: CompiledByteCode -> ItblEnv
bc_ffis :: CompiledByteCode -> [FFIInfo]
bc_breaks :: CompiledByteCode -> Maybe ModBreaks
bc_bcos :: CompiledByteCode -> [UnlinkedBCO]
..} [(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 ((String -> RemoteRef BreakArray
forall a. String -> a
panic String
"linkSomeBCOs: no break array", [UnlinkedBCO]
bc_bcos) (RemoteRef BreakArray, [UnlinkedBCO])
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
forall a. a -> [a] -> [a]
: [(RemoteRef BreakArray, [UnlinkedBCO])]
accum)
      Just ModBreaks
mb -> ForeignRef BreakArray -> (RemoteRef BreakArray -> IO b) -> IO b
forall a b. ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef (ModBreaks -> ForeignRef BreakArray
modBreaks_flags ModBreaks
mb) ((RemoteRef BreakArray -> IO b) -> IO b)
-> (RemoteRef BreakArray -> IO b) -> IO b
forall a b. (a -> b) -> a -> b
$ \RemoteRef BreakArray
breakarray ->
                   [(RemoteRef BreakArray, [UnlinkedBCO])] -> IO b
inner ((RemoteRef BreakArray
breakarray, [UnlinkedBCO]
bc_bcos) (RemoteRef BreakArray, [UnlinkedBCO])
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
-> [(RemoteRef BreakArray, [UnlinkedBCO])]
forall a. a -> [a] -> [a]
: [(RemoteRef BreakArray, [UnlinkedBCO])]
accum)

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

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

        -- Extract DynLinker for passing into required places
        let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env

        PersistentLinkerState
new_pls
            <- DynLinker
-> (PersistentLinkerState
    -> IO (PersistentLinkerState, PersistentLinkerState))
-> IO PersistentLinkerState
forall a.
DynLinker
-> (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS DynLinker
dl ((PersistentLinkerState
  -> IO (PersistentLinkerState, PersistentLinkerState))
 -> IO PersistentLinkerState)
-> (PersistentLinkerState
    -> IO (PersistentLinkerState, PersistentLinkerState))
-> IO PersistentLinkerState
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls -> do
                 PersistentLinkerState
pls1 <- HscEnv
-> [Linkable] -> PersistentLinkerState -> IO PersistentLinkerState
unload_wkr HscEnv
hsc_env [Linkable]
linkables PersistentLinkerState
pls
                 (PersistentLinkerState, PersistentLinkerState)
-> IO (PersistentLinkerState, PersistentLinkerState)
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState
pls1, PersistentLinkerState
pls1)

        let dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
        DynFlags -> Int -> SDoc -> IO ()
debugTraceMsg DynFlags
dflags Int
3 (SDoc -> IO ()) -> SDoc -> IO ()
forall a b. (a -> b) -> a -> b
$
          String -> SDoc
text String
"unload: retaining objs" SDoc -> SDoc -> SDoc
<+> [Linkable] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PersistentLinkerState -> [Linkable]
objs_loaded PersistentLinkerState
new_pls)
        DynFlags -> Int -> SDoc -> IO ()
debugTraceMsg DynFlags
dflags Int
3 (SDoc -> IO ()) -> SDoc -> IO ()
forall a b. (a -> b) -> a -> b
$
          String -> SDoc
text String
"unload: retaining bcos" SDoc -> SDoc -> SDoc
<+> [Linkable] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (PersistentLinkerState -> [Linkable]
bcos_loaded PersistentLinkerState
new_pls)
        () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

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

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

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

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

      ([Linkable]
objs_to_unload, [Linkable]
remaining_objs_loaded) =
         (Linkable -> Bool) -> [Linkable] -> ([Linkable], [Linkable])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition ([Linkable] -> Linkable -> Bool
discard [Linkable]
objs_to_keep) [Linkable]
objs_loaded
      ([Linkable]
bcos_to_unload, [Linkable]
remaining_bcos_loaded) =
         (Linkable -> Bool) -> [Linkable] -> ([Linkable], [Linkable])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition ([Linkable] -> Linkable -> Bool
discard [Linkable]
bcos_to_keep) [Linkable]
bcos_loaded

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

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

  let !bcos_retained :: ModuleSet
bcos_retained = [Module] -> ModuleSet
mkModuleSet ([Module] -> ModuleSet) -> [Module] -> ModuleSet
forall a b. (a -> b) -> a -> b
$ (Linkable -> Module) -> [Linkable] -> [Module]
forall a b. (a -> b) -> [a] -> [b]
map Linkable -> Module
linkableModule [Linkable]
remaining_bcos_loaded

      -- Note that we want to remove all *local*
      -- (i.e. non-isExternal) names too (these are the
      -- temporary bindings from the command line).
      keep_name :: (Name, b) -> Bool
keep_name (Name
n,b
_) = Name -> Bool
isExternalName Name
n Bool -> Bool -> Bool
&&
                        HasDebugCallStack => Name -> Module
Name -> Module
nameModule Name
n Module -> ModuleSet -> Bool
`elemModuleSet` ModuleSet
bcos_retained

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

      !new_pls :: PersistentLinkerState
new_pls = PersistentLinkerState
pls { itbl_env :: ItblEnv
itbl_env = ItblEnv
itbl_env',
                       closure_env :: ClosureEnv
closure_env = ClosureEnv
closure_env',
                       bcos_loaded :: [Linkable]
bcos_loaded = [Linkable]
remaining_bcos_loaded,
                       objs_loaded :: [Linkable]
objs_loaded = [Linkable]
remaining_objs_loaded }

  PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return PersistentLinkerState
new_pls
  where
    unloadObjs :: Linkable -> IO ()
    unloadObjs :: Linkable -> IO ()
unloadObjs Linkable
lnk
        -- The RTS's PEi386 linker currently doesn't support unloading.
      | Bool
isWindowsHost = () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

      | Bool
hostIsDynamic = () -> IO ()
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
      = (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (HscEnv -> String -> IO ()
unloadObj HscEnv
hsc_env) [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)

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

                Loading packages

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

data LibrarySpec
   = Objects [FilePath] -- Full path names of set of .o files, including trailing .o
                        -- We allow batched loading to ensure that cyclic symbol
                        -- references can be resolved (see #13786).
                        -- For dynamic objects only, try to find the object
                        -- file in all the directories specified in
                        -- v_Library_paths before giving up.

   | Archive FilePath   -- Full path name of a .a file, including trailing .a

   | DLL String         -- "Unadorned" name of a .DLL/.so
                        --  e.g.    On unix     "qt"  denotes "libqt.so"
                        --          On Windows  "burble"  denotes "burble.DLL" or "libburble.dll"
                        --  loadDLL is platform-specific and adds the lib/.so/.DLL
                        --  suffixes platform-dependently

   | DLLPath FilePath   -- Absolute or relative pathname to a dynamic library
                        -- (ends with .dll or .so).

   | Framework String   -- Only used for darwin, but does no harm

instance Outputable LibrarySpec where
  ppr :: LibrarySpec -> SDoc
ppr (Objects [String]
objs) = String -> SDoc
text String
"Objects" SDoc -> SDoc -> SDoc
<+> [String] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [String]
objs
  ppr (Archive String
a) = String -> SDoc
text String
"Archive" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
a
  ppr (DLL String
s) = String -> SDoc
text String
"DLL" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
s
  ppr (DLLPath String
f) = String -> SDoc
text String
"DLLPath" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
f
  ppr (Framework String
s) = String -> SDoc
text String
"Framework" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
s

-- If this package is already part of the GHCi binary, we'll already
-- have the right DLLs for this package loaded, so don't try to
-- load them again.
--
-- But on Win32 we must load them 'again'; doing so is a harmless no-op
-- as far as the loader is concerned, but it does initialise the list
-- of DLL handles that rts/Linker.c maintains, and that in turn is
-- used by lookupSymbol.  So we must call addDLL for each library
-- just to get the DLL handle into the list.
partOfGHCi :: [PackageName]
partOfGHCi :: [PackageName]
partOfGHCi
 | Bool
isWindowsHost Bool -> Bool -> Bool
|| Bool
isDarwinHost = []
 | Bool
otherwise = (String -> PackageName) -> [String] -> [PackageName]
forall a b. (a -> b) -> [a] -> [b]
map (FastString -> PackageName
PackageName (FastString -> PackageName)
-> (String -> FastString) -> String -> PackageName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> FastString
mkFastString)
                   [String
"base", String
"template-haskell", String
"editline"]

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

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

linkPackages :: HscEnv -> [UnitId] -> IO ()
linkPackages HscEnv
hsc_env [UnitId]
new_pkgs = do
  -- It's probably not safe to try to load packages concurrently, so we take
  -- a lock.
  HscEnv -> IO ()
initDynLinker HscEnv
hsc_env
  let dl :: DynLinker
dl = HscEnv -> DynLinker
hsc_dynLinker HscEnv
hsc_env
  DynLinker
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ DynLinker
dl ((PersistentLinkerState -> IO PersistentLinkerState) -> IO ())
-> (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
forall a b. (a -> b) -> a -> b
$ \PersistentLinkerState
pls -> do
    HscEnv
-> [UnitId] -> PersistentLinkerState -> IO PersistentLinkerState
linkPackages' HscEnv
hsc_env [UnitId]
new_pkgs PersistentLinkerState
pls

linkPackages' :: HscEnv -> [UnitId] -> PersistentLinkerState
             -> IO PersistentLinkerState
linkPackages' :: HscEnv
-> [UnitId] -> PersistentLinkerState -> IO PersistentLinkerState
linkPackages' HscEnv
hsc_env [UnitId]
new_pks PersistentLinkerState
pls = do
    [UnitId]
pkgs' <- [UnitId] -> [UnitId] -> IO [UnitId]
link (PersistentLinkerState -> [UnitId]
pkgs_loaded PersistentLinkerState
pls) [UnitId]
new_pks
    PersistentLinkerState -> IO PersistentLinkerState
forall (m :: * -> *) a. Monad m => a -> m a
return (PersistentLinkerState -> IO PersistentLinkerState)
-> PersistentLinkerState -> IO PersistentLinkerState
forall a b. (a -> b) -> a -> b
$! PersistentLinkerState
pls { pkgs_loaded :: [UnitId]
pkgs_loaded = [UnitId]
pkgs' }
  where
     dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
     pkgstate :: UnitState
pkgstate = DynFlags -> UnitState
unitState DynFlags
dflags

     link :: [UnitId] -> [UnitId] -> IO [UnitId]
     link :: [UnitId] -> [UnitId] -> IO [UnitId]
link [UnitId]
pkgs [UnitId]
new_pkgs =
         ([UnitId] -> UnitId -> IO [UnitId])
-> [UnitId] -> [UnitId] -> IO [UnitId]
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM [UnitId] -> UnitId -> IO [UnitId]
link_one [UnitId]
pkgs [UnitId]
new_pkgs

     link_one :: [UnitId] -> UnitId -> IO [UnitId]
link_one [UnitId]
pkgs UnitId
new_pkg
        | UnitId
new_pkg UnitId -> [UnitId] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [UnitId]
pkgs   -- Already linked
        = [UnitId] -> IO [UnitId]
forall (m :: * -> *) a. Monad m => a -> m a
return [UnitId]
pkgs

        | Just UnitInfo
pkg_cfg <- UnitState -> UnitId -> Maybe UnitInfo
lookupUnitId UnitState
pkgstate UnitId
new_pkg
        = do {  -- Link dependents first
               [UnitId]
pkgs' <- [UnitId] -> [UnitId] -> IO [UnitId]
link [UnitId]
pkgs (UnitInfo -> [UnitId]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [uid]
unitDepends UnitInfo
pkg_cfg)
                -- Now link the package itself
             ; HscEnv -> UnitInfo -> IO ()
linkPackage HscEnv
hsc_env UnitInfo
pkg_cfg
             ; [UnitId] -> IO [UnitId]
forall (m :: * -> *) a. Monad m => a -> m a
return (UnitId
new_pkg UnitId -> [UnitId] -> [UnitId]
forall a. a -> [a] -> [a]
: [UnitId]
pkgs') }

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


linkPackage :: HscEnv -> UnitInfo -> IO ()
linkPackage :: HscEnv -> UnitInfo -> IO ()
linkPackage HscEnv
hsc_env UnitInfo
pkg
   = do
        let dflags :: DynFlags
dflags    = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
            platform :: Platform
platform  = DynFlags -> Platform
targetPlatform DynFlags
dflags
            is_dyn :: Bool
is_dyn    = Interp -> Bool
interpreterDynamic (HscEnv -> Interp
hscInterp HscEnv
hsc_env)
            dirs :: [String]
dirs | Bool
is_dyn    = UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitLibraryDynDirs UnitInfo
pkg
                 | Bool
otherwise = UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitLibraryDirs UnitInfo
pkg

        let hs_libs :: [String]
hs_libs   =  UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitLibraries UnitInfo
pkg
            -- The FFI GHCi import lib isn't needed as
            -- GHC.Runtime.Linker + 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'  =  (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
"HSffi" String -> String -> Bool
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.
            extra_libs :: [String]
extra_libs =
                      (if [String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitExtDepLibsGhc UnitInfo
pkg)
                            then UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitExtDepLibsSys UnitInfo
pkg
                            else UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitExtDepLibsGhc UnitInfo
pkg)
                      [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [ String
lib | Char
'-':Char
'l':String
lib <- UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitLinkerOptions UnitInfo
pkg ]
        -- See Note [Fork/Exec Windows]
        [String]
gcc_paths <- DynFlags -> OS -> IO [String]
getGCCPaths DynFlags
dflags (Platform -> OS
platformOS Platform
platform)
        [String]
dirs_env <- String -> [String] -> IO [String]
addEnvPaths String
"LIBRARY_PATH" [String]
dirs

        [LibrarySpec]
hs_classifieds
           <- (String -> IO LibrarySpec) -> [String] -> IO [LibrarySpec]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (HscEnv -> Bool -> [String] -> [String] -> String -> IO LibrarySpec
locateLib HscEnv
hsc_env Bool
True  [String]
dirs_env [String]
gcc_paths) [String]
hs_libs'
        [LibrarySpec]
extra_classifieds
           <- (String -> IO LibrarySpec) -> [String] -> IO [LibrarySpec]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (HscEnv -> Bool -> [String] -> [String] -> String -> IO LibrarySpec
locateLib HscEnv
hsc_env Bool
False [String]
dirs_env [String]
gcc_paths) [String]
extra_libs
        let classifieds :: [LibrarySpec]
classifieds = [LibrarySpec]
hs_classifieds [LibrarySpec] -> [LibrarySpec] -> [LibrarySpec]
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 ]
            dlls :: [String]
dlls       = [ String
dll  | DLL String
dll        <- [LibrarySpec]
classifieds ]
            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  = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
takeDirectory [String]
known_dlls
            all_paths :: [String]
all_paths  = [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
normalise ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
dll_paths [String] -> [String] -> [String]
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 <- (String -> IO (Ptr ())) -> [String] -> IO [Ptr ()]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (HscEnv -> String -> IO (Ptr ())
addLibrarySearchPath HscEnv
hsc_env) [String]
all_paths_env

        DynFlags -> String -> IO ()
maybePutStr DynFlags
dflags
            (String
"Loading package " String -> String -> String
forall a. [a] -> [a] -> [a]
++ UnitInfo -> String
forall u. GenUnitInfo u -> String
unitPackageIdString UnitInfo
pkg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" ... ")

        -- See comments with partOfGHCi
#if defined(CAN_LOAD_DLL)
        when (unitPackageName pkg `notElem` partOfGHCi) $ do
            loadFrameworks hsc_env platform pkg
            -- See Note [Crash early load_dyn and locateLib]
            -- Crash early if can't load any of `known_dlls`
            mapM_ (load_dyn hsc_env True) known_dlls
            -- For remaining `dlls` crash early only when there is surely
            -- no package's DLL around ... (not is_dyn)
            mapM_ (load_dyn hsc_env (not is_dyn) . mkSOName 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.
        (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (HscEnv -> String -> IO ()
loadObj HscEnv
hsc_env) [String]
objs
        (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (HscEnv -> String -> IO ()
loadArchive HscEnv
hsc_env) [String]
archs

        DynFlags -> String -> IO ()
maybePutStr DynFlags
dflags String
"linking ... "
        SuccessFlag
ok <- HscEnv -> IO SuccessFlag
resolveObjs HscEnv
hsc_env

        -- DLLs are loaded, reset the search paths
        -- Import libraries will be loaded via loadArchive so only
        -- reset the DLL search path after all archives are loaded
        -- as well.
        (Ptr () -> IO Bool) -> [Ptr ()] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (HscEnv -> Ptr () -> IO Bool
removeLibrarySearchPath HscEnv
hsc_env) ([Ptr ()] -> IO ()) -> [Ptr ()] -> IO ()
forall a b. (a -> b) -> a -> b
$ [Ptr ()] -> [Ptr ()]
forall a. [a] -> [a]
reverse [Ptr ()]
pathCache

        if SuccessFlag -> Bool
succeeded SuccessFlag
ok
           then DynFlags -> String -> IO ()
maybePutStrLn DynFlags
dflags String
"done."
           else let errmsg :: String
errmsg = String
"unable to load package `"
                             String -> String -> String
forall a. [a] -> [a] -> [a]
++ UnitInfo -> String
forall u. GenUnitInfo u -> String
unitPackageIdString UnitInfo
pkg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"'"
                 in GhcException -> IO ()
forall a. GhcException -> IO a
throwGhcExceptionIO (String -> GhcException
InstallationError String
errmsg)

{-
Note [Crash early load_dyn and locateLib]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a package is "normal" (exposes it's code from more than zero Haskell
modules, unlike e.g. that in ghcilink004) and is built "dyn" way, then
it has it's code compiled and linked into the DLL, which GHCi linker picks
when loading the package's code (see the big comment in the beginning of
`locateLib`).

When loading DLLs, GHCi linker simply calls the system's `dlopen` or
`LoadLibrary` APIs. This is quite different from the case when GHCi linker
loads an object file or static library. When loading an object file or static
library GHCi linker parses them and resolves all symbols "manually".
These object file or static library may reference some external symbols
defined in some external DLLs. And GHCi should know which these
external DLLs are.

But when GHCi loads a DLL, it's the *system* linker who manages all
the necessary dependencies, and it is able to load this DLL not having
any extra info. Thus we don't *have to* crash in this case even if we
are unable to load any supposed dependencies explicitly.

Suppose during GHCi session a client of the package wants to
`foreign import` a symbol which isn't exposed by the package DLL, but
is exposed by such an external (dependency) DLL.
If the DLL isn't *explicitly* loaded because `load_dyn` failed to do
this, then the client code eventually crashes because the GHCi linker
isn't able to locate this symbol (GHCi linker maintains a list of
explicitly loaded DLLs it looks into when trying to find a symbol).

This is why we still should try to load all the dependency DLLs
even though we know that the system linker loads them implicitly when
loading the package DLL.

Why we still keep the `crash_early` opportunity then not allowing such
a permissive behaviour for any DLLs? Well, we, perhaps, improve a user
experience in some cases slightly.

But if it happens there exist other corner cases where our current
usage of `crash_early` flag is overly restrictive, we may lift the
restriction very easily.
-}

-- we have already searched the filesystem; the strings passed to load_dyn
-- can be passed directly to loadDLL.  They are either fully-qualified
-- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so").  In the latter case,
-- loadDLL is going to search the system paths to find the library.
load_dyn :: HscEnv -> Bool -> FilePath -> IO ()
load_dyn :: HscEnv -> Bool -> String -> IO ()
load_dyn HscEnv
hsc_env Bool
crash_early String
dll = do
  Maybe String
r <- HscEnv -> String -> IO (Maybe String)
loadDLL HscEnv
hsc_env String
dll
  case Maybe String
r of
    Maybe String
Nothing  -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    Just String
err ->
      if Bool
crash_early
        then String -> IO ()
forall a. String -> IO a
cmdLineErrorIO String
err
        else let dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env in
          Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (WarningFlag -> DynFlags -> Bool
wopt WarningFlag
Opt_WarnMissedExtraSharedLib DynFlags
dflags)
            (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> WarnReason -> Severity -> SrcSpan -> SDoc -> IO ()
putLogMsg DynFlags
dflags
                (WarningFlag -> WarnReason
Reason WarningFlag
Opt_WarnMissedExtraSharedLib) Severity
SevWarning
                  SrcSpan
noSrcSpan (SDoc -> IO ()) -> SDoc -> IO ()
forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultUserStyle (String -> SDoc
note String
err)
  where
    note :: String -> SDoc
note String
err = [SDoc] -> SDoc
vcat ([SDoc] -> SDoc) -> [SDoc] -> SDoc
forall a b. (a -> b) -> a -> b
$ (String -> SDoc) -> [String] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map String -> SDoc
text
      [ String
err
      , String
"It's OK if you don't want to use symbols from it directly."
      , String
"(the package DLL is loaded by the system linker"
      , String
" which manages dependencies by itself)." ]

loadFrameworks :: HscEnv -> Platform -> UnitInfo -> IO ()
loadFrameworks :: HscEnv -> Platform -> UnitInfo -> IO ()
loadFrameworks HscEnv
hsc_env Platform
platform UnitInfo
pkg
    = Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Platform -> Bool
platformUsesFrameworks Platform
platform) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> IO ()
load [String]
frameworks
  where
    fw_dirs :: [String]
fw_dirs    = UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitExtDepFrameworkDirs UnitInfo
pkg
    frameworks :: [String]
frameworks = UnitInfo -> [String]
forall compid srcpkgid srcpkgname uid modulename mod.
GenericUnitInfo compid srcpkgid srcpkgname uid modulename mod
-> [String]
Packages.unitExtDepFrameworks UnitInfo
pkg

    load :: String -> IO ()
load String
fw = do  Maybe String
r <- HscEnv -> [String] -> String -> IO (Maybe String)
loadFramework HscEnv
hsc_env [String]
fw_dirs String
fw
                  case Maybe String
r of
                    Maybe String
Nothing  -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                    Just String
err -> String -> IO ()
forall a. String -> IO a
cmdLineErrorIO (String
"can't load framework: "
                                                String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
fw String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
err String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")" )

-- Try to find an object file for a given library in the given paths.
-- If it isn't present, we assume that addDLL in the RTS can find it,
-- which generally means that it should be a dynamic library in the
-- standard system search path.
-- For GHCi we tend to prefer dynamic libraries over static ones as
-- they are easier to load and manage, have less overhead.
locateLib :: HscEnv -> Bool -> [FilePath] -> [FilePath] -> String
          -> IO LibrarySpec
locateLib :: HscEnv -> Bool -> [String] -> [String] -> String -> IO LibrarySpec
locateLib HscEnv
hsc_env Bool
is_hs [String]
lib_dirs [String]
gcc_dirs String
lib
  | 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 IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
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  IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
forall (m :: * -> *) b. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
findArchive    IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
forall (m :: * -> *) b. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
tryGcc         IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
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     IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
forall (m :: * -> *) b. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
findDynObject IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
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  IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
forall (m :: * -> *) b. Monad m => m (Maybe b) -> m b -> m b
`orElse`
    IO (Maybe LibrarySpec)
findArchive IO (Maybe LibrarySpec) -> IO LibrarySpec -> IO LibrarySpec
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
     interp :: Interp
interp = HscEnv -> Interp
hscInterp HscEnv
hsc_env
     dirs :: [String]
dirs   = [String]
lib_dirs [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
gcc_dirs
     gcc :: Bool
gcc    = Bool
False
     user :: Bool
user   = Bool
True

     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 = [ String
"lib" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
lib String -> String -> String
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" String -> String -> String
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  = [ String
lib String -> String -> String
<.> String
"lib"           , String
"lib" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
lib String -> String -> String
<.> String
"lib"
                    , String
"lib" String -> String -> String
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 String -> String -> String
forall a. [a] -> [a] -> [a]
++ Char
'-'Char -> String -> String
forall a. a -> [a] -> [a]
:DynFlags -> String
programName DynFlags
dflags String -> String -> String
forall a. [a] -> [a] -> [a]
++ DynFlags -> String
projectVersion DynFlags
dflags
     hs_dyn_lib_file :: String
hs_dyn_lib_file = Platform -> String -> String
mkHsSOName Platform
platform String
hs_dyn_lib_name

     so_name :: String
so_name     = Platform -> String -> String
mkSOName Platform
platform String
lib
     lib_so_name :: String
lib_so_name = String
"lib" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
so_name
     dyn_lib_file :: String
dyn_lib_file = case (Arch
arch, OS
os) of
                             (Arch
ArchX86_64, OS
OSSolaris2) -> String
"64" String -> String -> String
</> String
so_name
                             (Arch, OS)
_ -> String
so_name

     findObject :: IO (Maybe LibrarySpec)
findObject    = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec)
-> (String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall a b. (a -> b) -> a -> b
$ [String] -> LibrarySpec
Objects ([String] -> LibrarySpec)
-> (String -> [String]) -> String -> LibrarySpec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> [String] -> [String]
forall a. a -> [a] -> [a]
:[]))  (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
obj_file
     findDynObject :: IO (Maybe LibrarySpec)
findDynObject = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec)
-> (String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall a b. (a -> b) -> a -> b
$ [String] -> LibrarySpec
Objects ([String] -> LibrarySpec)
-> (String -> [String]) -> String -> LibrarySpec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> [String] -> [String]
forall a. a -> [a] -> [a]
:[]))  (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
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 = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
Archive) (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
name
                     in  [IO (Maybe LibrarySpec)] -> IO (Maybe LibrarySpec)
forall a. [IO (Maybe a)] -> IO (Maybe a)
apply ((String -> IO (Maybe LibrarySpec))
-> [String] -> [IO (Maybe LibrarySpec)]
forall a b. (a -> b) -> [a] -> [b]
map String -> IO (Maybe LibrarySpec)
local [String]
arch_files)
     findHSDll :: IO (Maybe LibrarySpec)
findHSDll     = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
DLLPath) (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs String
hs_dyn_lib_file
     findDll :: Bool -> IO (Maybe LibrarySpec)
findDll    Bool
re = let dirs' :: [String]
dirs' = if Bool
re Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
user then [String]
lib_dirs else [String]
gcc_dirs
                     in (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
DLLPath) (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ [String] -> String -> IO (Maybe String)
findFile [String]
dirs' String
dyn_lib_file
     findSysDll :: IO (Maybe LibrarySpec)
findSysDll    = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec)
-> (String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall a b. (a -> b) -> a -> b
$ String -> LibrarySpec
DLL (String -> LibrarySpec)
-> (String -> String) -> String -> LibrarySpec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
dropExtension (String -> String) -> (String -> String) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
takeFileName) (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$
                        HscEnv -> String -> IO (Maybe String)
findSystemLibrary HscEnv
hsc_env String
so_name
     tryGcc :: IO (Maybe LibrarySpec)
tryGcc        = let search :: String -> [String] -> IO (Maybe String)
search   = DynFlags -> String -> [String] -> IO (Maybe String)
searchForLibUsingGcc DynFlags
dflags
                         dllpath :: IO (Maybe String) -> IO (Maybe LibrarySpec)
dllpath  = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
DLLPath)
                         short :: IO (Maybe LibrarySpec)
short    = IO (Maybe String) -> IO (Maybe LibrarySpec)
dllpath (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ String -> [String] -> IO (Maybe String)
search String
so_name [String]
lib_dirs
                         full :: IO (Maybe LibrarySpec)
full     = IO (Maybe String) -> IO (Maybe LibrarySpec)
dllpath (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ String -> [String] -> IO (Maybe String)
search String
lib_so_name [String]
lib_dirs
                         gcc :: String -> IO (Maybe LibrarySpec)
gcc String
name = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
Archive) (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$ String -> [String] -> IO (Maybe String)
search String
name [String]
lib_dirs
                         files :: [String]
files    = [String]
import_libs [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
arch_files
                         dlls :: [IO (Maybe LibrarySpec)]
dlls     = [IO (Maybe LibrarySpec)
short, IO (Maybe LibrarySpec)
full]
                         archives :: [IO (Maybe LibrarySpec)]
archives = (String -> IO (Maybe LibrarySpec))
-> [String] -> [IO (Maybe LibrarySpec)]
forall a b. (a -> b) -> [a] -> [b]
map String -> IO (Maybe LibrarySpec)
gcc [String]
files
                     in [IO (Maybe LibrarySpec)] -> IO (Maybe LibrarySpec)
forall a. [IO (Maybe a)] -> IO (Maybe a)
apply ([IO (Maybe LibrarySpec)] -> IO (Maybe LibrarySpec))
-> [IO (Maybe LibrarySpec)] -> IO (Maybe LibrarySpec)
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 Bool -> Bool -> Bool
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 = (Maybe String -> Maybe LibrarySpec)
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> LibrarySpec) -> Maybe String -> Maybe LibrarySpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> LibrarySpec
Archive) (IO (Maybe String) -> IO (Maybe LibrarySpec))
-> IO (Maybe String) -> IO (Maybe LibrarySpec)
forall a b. (a -> b) -> a -> b
$
                                            [String] -> String -> IO (Maybe String)
findFile [String]
dirs' String
name
                        in [IO (Maybe LibrarySpec)] -> IO (Maybe LibrarySpec)
forall a. [IO (Maybe a)] -> IO (Maybe a)
apply ((String -> IO (Maybe LibrarySpec))
-> [String] -> [IO (Maybe LibrarySpec)]
forall a b. (a -> b) -> [a] -> [b]
map String -> IO (Maybe LibrarySpec)
implib [String]
import_libs)
                       OS
_         -> Maybe LibrarySpec -> IO (Maybe LibrarySpec)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe LibrarySpec
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
          DynFlags -> SDoc -> IO ()
warningMsg DynFlags
dflags
            (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.")
          LibrarySpec -> IO LibrarySpec
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> LibrarySpec
DLL String
lib)
      | Bool
otherwise = LibrarySpec -> IO LibrarySpec
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 m (Maybe b) -> (Maybe b -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= m b -> (b -> m b) -> Maybe b -> m b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe m b
g b -> m b
forall (m :: * -> *) a. Monad m => a -> m a
return

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

     platform :: Platform
platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
     arch :: Arch
arch = Platform -> Arch
platformArch Platform
platform
     os :: OS
os = Platform -> OS
platformOS Platform
platform

searchForLibUsingGcc :: DynFlags -> String -> [FilePath] -> IO (Maybe FilePath)
searchForLibUsingGcc :: DynFlags -> String -> [String] -> IO (Maybe String)
searchForLibUsingGcc 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 <- DynFlags -> [Option] -> IO String
askLd DynFlags
dflags ((String -> Option) -> [String] -> [Option]
forall a b. (a -> b) -> [a] -> [b]
map (String -> String -> Option
FileOption String
"-B") [String]
dirs
                          [Option] -> [Option] -> [Option]
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 String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
so)
      then Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
      else do Bool
b <- String -> IO Bool
doesFileExist String
file -- file could be a folder (see #16063)
              Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (if Bool
b then String -> Maybe String
forall a. a -> Maybe a
Just String
file else Maybe String
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 :: DynFlags -> OS -> IO [FilePath]
getGCCPaths :: DynFlags -> OS -> IO [String]
getGCCPaths DynFlags
dflags OS
os
  = case OS
os of
      OS
OSMinGW32 ->
        do [String]
gcc_dirs <- DynFlags -> String -> IO [String]
getGccSearchDirectory DynFlags
dflags String
"libraries"
           [String]
sys_dirs <- IO [String]
getSystemDirectories
           [String] -> IO [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> IO [String]) -> [String] -> IO [String]
forall a b. (a -> b) -> a -> b
$ [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
gcc_dirs [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
sys_dirs
      OS
_         -> [String] -> IO [String]
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 = IO (IORef [(String, [String])]) -> IORef [(String, [String])]
forall a. IO a -> a
unsafePerformIO (IO (IORef [(String, [String])]) -> IORef [(String, [String])])
-> IO (IORef [(String, [String])]) -> IORef [(String, [String])]
forall a b. (a -> b) -> a -> b
$ [(String, [String])] -> IO (IORef [(String, [String])])
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 :: DynFlags -> String -> IO [FilePath]
getGccSearchDirectory :: DynFlags -> String -> IO [String]
getGccSearchDirectory DynFlags
dflags String
key = do
    [(String, [String])]
cache <- IORef [(String, [String])] -> IO [(String, [String])]
forall a. IORef a -> IO a
readIORef IORef [(String, [String])]
gccSearchDirCache
    case String -> [(String, [String])] -> Maybe [String]
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup String
key [(String, [String])]
cache of
      Just [String]
x  -> [String] -> IO [String]
forall (m :: * -> *) a. Monad m => a -> m a
return [String]
x
      Maybe [String]
Nothing -> do
        String
str <- DynFlags -> [Option] -> IO String
askLd DynFlags
dflags [String -> Option
Option String
"--print-search-dirs"]
        let line :: String
line = (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
str
            name :: String
name = String
key String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": ="
        if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
line
          then [String] -> IO [String]
forall (m :: * -> *) a. Monad m => a -> m a
return []
          else do let val :: [String]
val = String -> [String]
split (String -> [String]) -> String -> [String]
forall a b. (a -> b) -> a -> b
$ String -> String -> String
find String
name String
line
                  [String]
dirs <- (String -> IO Bool) -> [String] -> IO [String]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM String -> IO Bool
doesDirectoryExist [String]
val
                  IORef [(String, [String])]
-> ([(String, [String])] -> [(String, [String])]) -> IO ()
forall a. IORef a -> (a -> a) -> IO ()
modifyIORef' IORef [(String, [String])]
gccSearchDirCache ((String
key, [String]
dirs)(String, [String]) -> [(String, [String])] -> [(String, [String])]
forall a. a -> [a] -> [a]
:)
                  [String] -> IO [String]
forall (m :: * -> *) a. Monad m => a -> m a
return [String]
val
      where split :: FilePath -> [FilePath]
            split :: String -> [String]
split String
r = case (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
';') String
r of
                        (String
s, []    ) -> [String
s]
                        (String
s, (Char
_:String
xs)) -> String
s String -> [String] -> [String]
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 = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
r String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [String]
lst
                       in if [String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
val
                             then []
                             else case (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
'=') ([String] -> String
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 = [String] -> IO [String]
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  -> [String] -> IO [String]
forall (m :: * -> *) a. Monad m => a -> m a
return [String]
list
         Just String
arr -> [String] -> IO [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> IO [String]) -> [String] -> IO [String]
forall a b. (a -> b) -> a -> b
$ [String]
list [String] -> [String] -> [String]
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 (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
envListSep) String
value of
          (String
x, []    ) ->
            [if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
x then String
working_dir else String
x]
          (String
x, (Char
_:String
xs)) ->
            (if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
x then String
working_dir else String
x) String -> [String] -> [String]
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)

{-
Note [macOS Big Sur dynamic libraries]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

macOS Big Sur makes the following change to how frameworks are shipped
with the OS:

> New in macOS Big Sur 11 beta, the system ships with a built-in
> dynamic linker cache of all system-provided libraries.  As part of
> this change, copies of dynamic libraries are no longer present on
> the filesystem.  Code that attempts to check for dynamic library
> presence by looking for a file at a path or enumerating a directory
> will fail.  Instead, check for library presence by attempting to
> dlopen() the path, which will correctly check for the library in the
> cache. (62986286)

(https://developer.apple.com/documentation/macos-release-notes/macos-big-sur-11-beta-release-notes/)

Therefore, the previous method of checking whether a library exists
before attempting to load it makes GHC.Runtime.Linker.loadFramework
fail to find frameworks installed at /System/Library/Frameworks.
Instead, any attempt to load a framework at runtime, such as by
passing -framework OpenGL to runghc or running code loading such a
framework with GHCi, fails with a 'not found' message.

GHC.Runtime.Linker.loadFramework now opportunistically loads the
framework libraries without checking for their existence first,
failing only if all attempts to load a given framework from any of the
various possible locations fail.  See also #18446, which this change
addresses.
-}

-- Darwin / MacOS X only: load a framework
-- a framework is a dynamic library packaged inside a directory of the same
-- name. They are searched for in different paths than normal libraries.
loadFramework :: HscEnv -> [FilePath] -> FilePath -> IO (Maybe String)
loadFramework :: HscEnv -> [String] -> String -> IO (Maybe String)
loadFramework HscEnv
hsc_env [String]
extraPaths String
rootname
   = do { Either IOException String
either_dir <- IO String -> IO (Either IOException String)
forall a. IO a -> IO (Either IOException a)
tryIO IO String
getHomeDirectory
        ; let homeFrameworkPath :: [String]
homeFrameworkPath = case Either IOException String
either_dir of
                                  Left IOException
_ -> []
                                  Right String
dir -> [String
dir String -> String -> String
</> String
"Library/Frameworks"]
              ps :: [String]
ps = [String]
extraPaths [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
homeFrameworkPath [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
defaultFrameworkPaths
        ; Maybe [String]
errs <- [String] -> [String] -> IO (Maybe [String])
findLoadDLL [String]
ps []
        ; Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe String -> IO (Maybe String))
-> Maybe String -> IO (Maybe String)
forall a b. (a -> b) -> a -> b
$ ([String] -> String) -> Maybe [String] -> Maybe String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", ") Maybe [String]
errs
        }
   where
     fwk_file :: String
fwk_file = String
rootname String -> String -> String
<.> String
"framework" String -> String -> String
</> String
rootname

     -- sorry for the hardcoded paths, I hope they won't change anytime soon:
     defaultFrameworkPaths :: [String]
defaultFrameworkPaths = [String
"/Library/Frameworks", String
"/System/Library/Frameworks"]

     -- Try to call loadDLL for each candidate path.
     --
     -- See Note [macOS Big Sur dynamic libraries]
     findLoadDLL :: [String] -> [String] -> IO (Maybe [String])
findLoadDLL [] [String]
errs =
       -- Tried all our known library paths, but dlopen()
       -- has no built-in paths for frameworks: give up
       Maybe [String] -> IO (Maybe [String])
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe [String] -> IO (Maybe [String]))
-> Maybe [String] -> IO (Maybe [String])
forall a b. (a -> b) -> a -> b
$ [String] -> Maybe [String]
forall a. a -> Maybe a
Just [String]
errs
     findLoadDLL (String
p:[String]
ps) [String]
errs =
       do { Maybe String
dll <- HscEnv -> String -> IO (Maybe String)
loadDLL HscEnv
hsc_env (String
p String -> String -> String
</> String
fwk_file)
          ; case Maybe String
dll of
              Maybe String
Nothing  -> Maybe [String] -> IO (Maybe [String])
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe [String]
forall a. Maybe a
Nothing
              Just String
err -> [String] -> [String] -> IO (Maybe [String])
findLoadDLL [String]
ps ((String
p String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
": " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
err)String -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
errs)
          }

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

                Helper functions

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

maybePutStr :: DynFlags -> String -> IO ()
maybePutStr :: DynFlags -> String -> IO ()
maybePutStr DynFlags
dflags String
s
    = Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
          DynFlags -> WarnReason -> Severity -> SrcSpan -> SDoc -> IO ()
putLogMsg DynFlags
dflags
              WarnReason
NoReason
              Severity
SevInteractive
              SrcSpan
noSrcSpan
              (SDoc -> IO ()) -> SDoc -> IO ()
forall a b. (a -> b) -> a -> b
$ PprStyle -> SDoc -> SDoc
withPprStyle PprStyle
defaultUserStyle (String -> SDoc
text String
s)

maybePutStrLn :: DynFlags -> String -> IO ()
maybePutStrLn :: DynFlags -> String -> IO ()
maybePutStrLn DynFlags
dflags String
s = DynFlags -> String -> IO ()
maybePutStr DynFlags
dflags (String
s String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n")