Skip to content

Commit 4ff9329

Browse files
angermanMarge Bot
authored andcommitted
[macOS] improved runpath handling
In b592bd9 we started using -dead_strip_dylib on macOS when lining dynamic libraries and binaries. The underlying reason being the Load Command Size Limit in macOS Sierra (10.14) and later. GHC will produce @rpath/libHS... dependency entries together with a corresponding RPATH entry pointing to the location of the libHS... library. Thus for every library we produce two Load Commands. One to specify the dependent library, and one with the path where to find it. This makes relocating libraries and binaries easier, as we just need to update the RPATH entry with the install_name_tool. The dynamic linker will then subsitute each @rpath with the RPATH entries it finds in the libraries load commands or the environement, when looking up @rpath relative libraries. -dead_strip_dylibs intructs the linker to drop unused libraries. This in turn help us reduce the number of referenced libraries, and subsequently the size of the load commands. This however does not remove the RPATH entries. Subsequently we can end up (in extreme cases) with only a single @rpath/libHS... entry, but 100s or more RPATH entries in the Load Commands. This patch rectifies this (slighly unorthodox) by passing *no* -rpath arguments to the linker at link time, but -headerpad 8000. The headerpad argument is in hexadecimal and the maxium 32k of the load command size. This tells the linker to pad the load command section enough for us to inject the RPATHs later. We then proceed to link the library or binary with -dead_strip_dylibs, and *after* the linking inspect the library to find the left over (non-dead-stripped) dependencies (using otool). We find the corresponding RPATHs for each @rpath relative dependency, and inject them into the library or binary using the install_name_tool. Thus achieving a deadstripped dylib (and rpaths) build product. We can not do this in GHC, without starting to reimplement a dynamic linker as we do not know which symbols and subsequently libraries are necessary. Commissioned-by: Mercury Technologies, Inc. (mercury.com)
1 parent d4bc9f0 commit 4ff9329

16 files changed

Lines changed: 245 additions & 23 deletions

File tree

‎aclocal.m4‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,18 @@ AC_DEFUN([FP_SETTINGS],
602602
else
603603
SettingsOptCommand="$OptCmd"
604604
fi
605+
if test -z "$OtoolCmd"
606+
then
607+
SettingsOtoolCommand="otool"
608+
else
609+
SettingsOtoolCommand="$OtoolCmd"
610+
fi
611+
if test -z "$InstallNameToolCmd"
612+
then
613+
SettingsInstallNameToolCommand="install_name_tool"
614+
else
615+
SettingsInstallNameToolCommand="$InstallNameToolCmd"
616+
fi
605617
SettingsCCompilerFlags="$CONF_CC_OPTS_STAGE2"
606618
SettingsCxxCompilerFlags="$CONF_CXX_OPTS_STAGE2"
607619
SettingsCCompilerLinkFlags="$CONF_GCC_LINKER_OPTS_STAGE2"
@@ -621,6 +633,8 @@ AC_DEFUN([FP_SETTINGS],
621633
AC_SUBST(SettingsMergeObjectsFlags)
622634
AC_SUBST(SettingsArCommand)
623635
AC_SUBST(SettingsRanlibCommand)
636+
AC_SUBST(SettingsOtoolCommand)
637+
AC_SUBST(SettingsInstallNameToolCommand)
624638
AC_SUBST(SettingsDllWrapCommand)
625639
AC_SUBST(SettingsWindresCommand)
626640
AC_SUBST(SettingsLibtoolCommand)

‎compiler/GHC/Driver/Pipeline.hs‎

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,56 @@ compileEmptyStub dflags hsc_env basename location mod_name = do
394394

395395
-- ---------------------------------------------------------------------------
396396
-- Link
397-
397+
--
398+
-- Note [Dynamic linking on macOS]
399+
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
400+
--
401+
-- Since macOS Sierra (10.14), the dynamic system linker enforces
402+
-- a limit on the Load Commands. Specifically the Load Command Size
403+
-- Limit is at 32K (32768). The Load Commands contain the install
404+
-- name, dependencies, runpaths, and a few other commands. We however
405+
-- only have control over the install name, dependencies and runpaths.
406+
--
407+
-- The install name is the name by which this library will be
408+
-- referenced. This is such that we do not need to bake in the full
409+
-- absolute location of the library, and can move the library around.
410+
--
411+
-- The dependency commands contain the install names from of referenced
412+
-- libraries. Thus if a libraries install name is @rpath/libHS...dylib,
413+
-- that will end up as the dependency.
414+
--
415+
-- Finally we have the runpaths, which informs the linker about the
416+
-- directories to search for the referenced dependencies.
417+
--
418+
-- The system linker can do recursive linking, however using only the
419+
-- direct dependencies conflicts with ghc's ability to inline across
420+
-- packages, and as such would end up with unresolved symbols.
421+
--
422+
-- Thus we will pass the full dependency closure to the linker, and then
423+
-- ask the linker to remove any unused dynamic libraries (-dead_strip_dylibs).
424+
--
425+
-- We still need to add the relevant runpaths, for the dynamic linker to
426+
-- lookup the referenced libraries though. The linker (ld64) does not
427+
-- have any option to dead strip runpaths; which makes sense as runpaths
428+
-- can be used for dependencies of dependencies as well.
429+
--
430+
-- The solution we then take in GHC is to not pass any runpaths to the
431+
-- linker at link time, but inject them after the linking. For this to
432+
-- work we'll need to ask the linker to create enough space in the header
433+
-- to add more runpaths after the linking (-headerpad 8000).
434+
--
435+
-- After the library has been linked by $LD (usually ld64), we will use
436+
-- otool to inspect the libraries left over after dead stripping, compute
437+
-- the relevant runpaths, and inject them into the linked product using
438+
-- the install_name_tool command.
439+
--
440+
-- This strategy should produce the smallest possible set of load commands
441+
-- while still retaining some form of relocatability via runpaths.
442+
--
443+
-- The only way I can see to reduce the load command size further would be
444+
-- by shortening the library names, or start putting libraries into the same
445+
-- folders, such that one runpath would be sufficient for multiple/all
446+
-- libraries.
398447
link :: GhcLink -- interactive or batch
399448
-> DynFlags -- dynamic flags
400449
-> Bool -- attempt linking in batch mode?
@@ -1787,9 +1836,12 @@ linkBinary' staticLink dflags o_files dep_units = do
17871836

17881837
rc_objs <- maybeCreateManifest dflags output_fn
17891838

1790-
let link = if staticLink
1791-
then GHC.SysTools.runLibtool
1792-
else GHC.SysTools.runLink
1839+
let link dflags args | staticLink = GHC.SysTools.runLibtool dflags args
1840+
| platformOS platform == OSDarwin
1841+
= GHC.SysTools.runLink dflags args >> GHC.SysTools.runInjectRPaths dflags pkg_lib_paths output_fn
1842+
| otherwise
1843+
= GHC.SysTools.runLink dflags args
1844+
17931845
link dflags (
17941846
map GHC.SysTools.Option verbFlags
17951847
++ [ GHC.SysTools.Option "-o"
@@ -1856,7 +1908,13 @@ linkBinary' staticLink dflags o_files dep_units = do
18561908
++ pkg_link_opts
18571909
++ pkg_framework_opts
18581910
++ (if platformOS platform == OSDarwin
1859-
then [ "-Wl,-dead_strip_dylibs" ]
1911+
-- dead_strip_dylibs, will remove unused dylibs, and thus save
1912+
-- space in the load commands. The -headerpad is necessary so
1913+
-- that we can inject more @rpath's later for the left over
1914+
-- libraries during runInjectRpaths phase.
1915+
--
1916+
-- See Note [Dynamic linking on macOS].
1917+
then [ "-Wl,-dead_strip_dylibs", "-Wl,-headerpad,8000" ]
18601918
else [])
18611919
))
18621920

‎compiler/GHC/Driver/Session.hs‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ module GHC.Driver.Session (
145145
versionedAppDir, versionedFilePath,
146146
extraGccViaCFlags, globalPackageDatabasePath,
147147
pgm_L, pgm_P, pgm_F, pgm_c, pgm_a, pgm_l, pgm_lm, pgm_dll, pgm_T,
148-
pgm_windres, pgm_libtool, pgm_ar, pgm_ranlib, pgm_lo, pgm_lc,
149-
pgm_lcc, pgm_i,
148+
pgm_windres, pgm_libtool, pgm_ar, pgm_otool, pgm_install_name_tool,
149+
pgm_ranlib, pgm_lo, pgm_lc, pgm_lcc, pgm_i,
150150
opt_L, opt_P, opt_F, opt_c, opt_cxx, opt_a, opt_l, opt_lm, opt_i,
151151
opt_P_signature,
152152
opt_windres, opt_lo, opt_lc, opt_lcc,
@@ -885,6 +885,10 @@ pgm_lcc :: DynFlags -> (String,[Option])
885885
pgm_lcc dflags = toolSettings_pgm_lcc $ toolSettings dflags
886886
pgm_ar :: DynFlags -> String
887887
pgm_ar dflags = toolSettings_pgm_ar $ toolSettings dflags
888+
pgm_otool :: DynFlags -> String
889+
pgm_otool dflags = toolSettings_pgm_otool $ toolSettings dflags
890+
pgm_install_name_tool :: DynFlags -> String
891+
pgm_install_name_tool dflags = toolSettings_pgm_install_name_tool $ toolSettings dflags
888892
pgm_ranlib :: DynFlags -> String
889893
pgm_ranlib dflags = toolSettings_pgm_ranlib $ toolSettings dflags
890894
pgm_lo :: DynFlags -> (String,[Option])
@@ -2267,6 +2271,10 @@ dynamic_flags_deps = [
22672271
$ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_libtool = f }
22682272
, make_ord_flag defFlag "pgmar"
22692273
$ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_ar = f }
2274+
, make_ord_flag defFlag "pgmotool"
2275+
$ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_otool = f}
2276+
, make_ord_flag defFlag "pgminstall_name_tool"
2277+
$ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_install_name_tool = f}
22702278
, make_ord_flag defFlag "pgmranlib"
22712279
$ hasArg $ \f -> alterToolSettings $ \s -> s { toolSettings_pgm_ranlib = f }
22722280

@@ -3780,7 +3788,6 @@ defaultFlags settings
37803788
Opt_OmitYields,
37813789
Opt_PrintBindContents,
37823790
Opt_ProfCountEntries,
3783-
Opt_RPath,
37843791
Opt_SharedImplib,
37853792
Opt_SimplPreInlining,
37863793
Opt_VersionMacros
@@ -3791,6 +3798,8 @@ defaultFlags settings
37913798

37923799
++ default_PIC platform
37933800

3801+
++ default_RPath platform
3802+
37943803
++ concatMap (wayGeneralFlags platform) (defaultWays settings)
37953804
++ validHoleFitDefaults
37963805

@@ -3831,6 +3840,29 @@ default_PIC platform =
38313840
-- information.
38323841
_ -> []
38333842

3843+
3844+
-- We usually want to use RPath, except on macOS (OSDarwin). On recent macOS
3845+
-- versions the number of load commands we can embed in a dynamic library is
3846+
-- restricted. Hence since b592bd98ff2 we rely on -dead_strip_dylib to only
3847+
-- link the needed dylibs instead of linking the full dependency closure.
3848+
--
3849+
-- If we split the library linking into injecting -rpath and -l @rpath/...
3850+
-- components, we will reduce the number of libraries we link, however we will
3851+
-- still inject one -rpath entry for each library, independent of their use.
3852+
-- That is, we even inject -rpath values for libraries that we dead_strip in
3853+
-- the end. As such we can run afoul of the load command size limit simply
3854+
-- by polluting the load commands with RPATH entries.
3855+
--
3856+
-- Thus, we disable Opt_RPath by default on OSDarwin. The savvy user can always
3857+
-- enable it with -use-rpath if they so wish.
3858+
--
3859+
-- See Note [Dynamic linking on macOS]
3860+
3861+
default_RPath :: Platform -> [GeneralFlag]
3862+
default_RPath platform | platformOS platform == OSDarwin = []
3863+
default_RPath _ = [Opt_RPath]
3864+
3865+
38343866
-- General flags that are switched on/off when other general flags are switched
38353867
-- on
38363868
impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)]

‎compiler/GHC/Runtime/Linker.hs‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -929,20 +929,22 @@ dynLoadObjs hsc_env pls@PersistentLinkerState{..} objs = do
929929
ldInputs =
930930
concatMap (\l -> [ Option ("-l" ++ l) ])
931931
(nub $ snd <$> temp_sos)
932-
++ concatMap (\lp -> [ Option ("-L" ++ lp)
933-
, Option "-Xlinker"
934-
, Option "-rpath"
935-
, Option "-Xlinker"
936-
, Option lp ])
932+
++ concatMap (\lp -> Option ("-L" ++ lp)
933+
: if gopt Opt_RPath dflags
934+
then [ Option "-Xlinker"
935+
, Option "-rpath"
936+
, Option "-Xlinker"
937+
, Option lp ]
938+
else [])
937939
(nub $ fst <$> temp_sos)
938940
++ concatMap
939-
(\lp ->
940-
[ Option ("-L" ++ lp)
941-
, Option "-Xlinker"
942-
, Option "-rpath"
943-
, Option "-Xlinker"
944-
, Option lp
945-
])
941+
(\lp -> Option ("-L" ++ lp)
942+
: if gopt Opt_RPath dflags
943+
then [ Option "-Xlinker"
944+
, Option "-rpath"
945+
, Option "-Xlinker"
946+
, Option lp ]
947+
else [])
946948
minus_big_ls
947949
-- See Note [-Xlinker -rpath vs -Wl,-rpath]
948950
++ map (\l -> Option ("-l" ++ l)) minus_ls,

‎compiler/GHC/Settings.hs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ module GHC.Settings
3434
, sPgm_windres
3535
, sPgm_libtool
3636
, sPgm_ar
37+
, sPgm_otool
38+
, sPgm_install_name_tool
3739
, sPgm_ranlib
3840
, sPgm_lo
3941
, sPgm_lc
@@ -107,6 +109,8 @@ data ToolSettings = ToolSettings
107109
, toolSettings_pgm_windres :: String
108110
, toolSettings_pgm_libtool :: String
109111
, toolSettings_pgm_ar :: String
112+
, toolSettings_pgm_otool :: String
113+
, toolSettings_pgm_install_name_tool :: String
110114
, toolSettings_pgm_ranlib :: String
111115
, -- | LLVM: opt llvm optimiser
112116
toolSettings_pgm_lo :: (String, [Option])
@@ -216,6 +220,10 @@ sPgm_libtool :: Settings -> String
216220
sPgm_libtool = toolSettings_pgm_libtool . sToolSettings
217221
sPgm_ar :: Settings -> String
218222
sPgm_ar = toolSettings_pgm_ar . sToolSettings
223+
sPgm_otool :: Settings -> String
224+
sPgm_otool = toolSettings_pgm_otool . sToolSettings
225+
sPgm_install_name_tool :: Settings -> String
226+
sPgm_install_name_tool = toolSettings_pgm_install_name_tool . sToolSettings
219227
sPgm_ranlib :: Settings -> String
220228
sPgm_ranlib = toolSettings_pgm_ranlib . sToolSettings
221229
sPgm_lo :: Settings -> (String, [Option])

‎compiler/GHC/Settings/IO.hs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ initSettings top_dir = do
115115
windres_path <- getToolSetting "windres command"
116116
libtool_path <- getToolSetting "libtool command"
117117
ar_path <- getToolSetting "ar command"
118+
otool_path <- getToolSetting "otool command"
119+
install_name_tool_path <- getToolSetting "install_name_tool command"
118120
ranlib_path <- getToolSetting "ranlib command"
119121

120122
-- TODO this side-effect doesn't belong here. Reading and parsing the settings
@@ -191,6 +193,8 @@ initSettings top_dir = do
191193
, toolSettings_pgm_windres = windres_path
192194
, toolSettings_pgm_libtool = libtool_path
193195
, toolSettings_pgm_ar = ar_path
196+
, toolSettings_pgm_otool = otool_path
197+
, toolSettings_pgm_install_name_tool = install_name_tool_path
194198
, toolSettings_pgm_ranlib = ranlib_path
195199
, toolSettings_pgm_lo = (lo_prog,[])
196200
, toolSettings_pgm_lc = (lc_prog,[])

‎compiler/GHC/SysTools.hs‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,10 @@ linkDynLib dflags0 o_files dep_packages
261261
| ( osElfTarget (platformOS (targetPlatform dflags)) ||
262262
osMachOTarget (platformOS (targetPlatform dflags)) ) &&
263263
dynLibLoader dflags == SystemDependent &&
264-
WayDyn `Set.member` ways dflags
264+
-- Only if we want dynamic libraries
265+
WayDyn `Set.member` ways dflags &&
266+
-- Only use RPath if we explicitly asked for it
267+
gopt Opt_RPath dflags
265268
= ["-L" ++ l, "-Xlinker", "-rpath", "-Xlinker", l]
266269
-- See Note [-Xlinker -rpath vs -Wl,-rpath]
267270
| otherwise = ["-L" ++ l]
@@ -386,8 +389,15 @@ linkDynLib dflags0 o_files dep_packages
386389
++ map Option pkg_lib_path_opts
387390
++ map Option pkg_link_opts
388391
++ map Option pkg_framework_opts
389-
++ [ Option "-Wl,-dead_strip_dylibs" ]
392+
-- dead_strip_dylibs, will remove unused dylibs, and thus save
393+
-- space in the load commands. The -headerpad is necessary so
394+
-- that we can inject more @rpath's later for the leftover
395+
-- libraries in the runInjectRpaths phase below.
396+
--
397+
-- See Note [Dynamic linking on macOS]
398+
++ [ Option "-Wl,-dead_strip_dylibs", Option "-Wl,-headerpad,8000" ]
390399
)
400+
runInjectRPaths dflags pkg_lib_paths output_fn
391401
_ -> do
392402
-------------------------------------------------------------------
393403
-- Making a DSO

‎compiler/GHC/SysTools/Tasks.hs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ import GHC.CmmToLlvm.Base (LlvmVersion, llvmVersionStr, supportedLlvmVersion, pa
2828
import GHC.SysTools.Process
2929
import GHC.SysTools.Info
3030

31+
import Control.Monad (join, forM, filterM)
32+
import System.Directory (doesFileExist)
33+
import System.FilePath ((</>))
34+
3135
{-
3236
************************************************************************
3337
* *
@@ -237,6 +241,41 @@ figureLlvmVersion dflags = traceToolCommand dflags "llc" $ do
237241
return Nothing)
238242

239243

244+
-- | On macOS we rely on the linkers @-dead_strip_dylibs@ flag to remove unused
245+
-- libraries from the dynamic library. We do this to reduce the number of load
246+
-- commands that end up in the dylib, and has been limited to 32K (32768) since
247+
-- macOS Sierra (10.14).
248+
--
249+
-- @-dead_strip_dylibs@ does not dead strip @-rpath@ entries, as such passing
250+
-- @-l@ and @-rpath@ to the linker will result in the unnecesasry libraries not
251+
-- being included in the load commands, however the @-rpath@ entries are all
252+
-- forced to be included. This can lead to 100s of @-rpath@ entries being
253+
-- included when only a handful of libraries end up being truely linked.
254+
--
255+
-- Thus after building the library, we run a fixup phase where we inject the
256+
-- @-rpath@ for each found library (in the given library search paths) into the
257+
-- dynamic library through @-add_rpath@.
258+
--
259+
-- See Note [Dynamic linking on macOS]
260+
runInjectRPaths :: DynFlags -> [FilePath] -> FilePath -> IO ()
261+
runInjectRPaths dflags lib_paths dylib = do
262+
info <- lines <$> askOtool dflags Nothing [Option "-L", Option dylib]
263+
-- filter the output for only the libraries. And then drop the @rpath prefix.
264+
let libs = fmap (drop 7) $ filter (isPrefixOf "@rpath") $ fmap (head.words) $ info
265+
-- find any pre-existing LC_PATH items
266+
info <- fmap words.lines <$> askOtool dflags Nothing [Option "-l", Option dylib]
267+
let paths = concatMap f info
268+
where f ("path":p:_) = [p]
269+
f _ = []
270+
lib_paths' = [ p | p <- lib_paths, not (p `elem` paths) ]
271+
-- only find those rpaths, that aren't already in the library.
272+
rpaths <- nub.sort.join <$> forM libs (\f -> filterM (\l -> doesFileExist (l </> f)) lib_paths')
273+
-- inject the rpaths
274+
case rpaths of
275+
[] -> return ()
276+
_ -> runInstallNameTool dflags $ map Option $ "-add_rpath":(intersperse "-add_rpath" rpaths) ++ [dylib]
277+
278+
240279
runLink :: DynFlags -> [Option] -> IO ()
241280
runLink dflags args = traceToolCommand dflags "linker" $ do
242281
-- See Note [Run-time linker info]
@@ -329,6 +368,17 @@ runAr dflags cwd args = traceToolCommand dflags "ar" $ do
329368
let ar = pgm_ar dflags
330369
runSomethingFiltered dflags id "Ar" ar args cwd Nothing
331370

371+
askOtool :: DynFlags -> Maybe FilePath -> [Option] -> IO String
372+
askOtool dflags mb_cwd args = do
373+
let otool = pgm_otool dflags
374+
runSomethingWith dflags "otool" otool args $ \real_args ->
375+
readCreateProcessWithExitCode' (proc otool real_args){ cwd = mb_cwd }
376+
377+
runInstallNameTool :: DynFlags -> [Option] -> IO ()
378+
runInstallNameTool dflags args = do
379+
let tool = pgm_install_name_tool dflags
380+
runSomethingFiltered dflags id "Install Name Tool" tool args Nothing Nothing
381+
332382
runRanlib :: DynFlags -> [Option] -> IO ()
333383
runRanlib dflags args = traceToolCommand dflags "ranlib" $ do
334384
let ranlib = pgm_ranlib dflags

0 commit comments

Comments
 (0)