Magnus pushed to branch wip/mangoiv/improve-linker-discovery at Glasgow Haskell Compiler / GHC

Commits:

9 changed files:

Changes:

  • distrib/configure.ac.in
    ... ... @@ -175,7 +175,11 @@ AC_SUBST([CmmCPPSupportsG0])
    175 175
     
    
    176 176
     dnl ** Which ld to use?
    
    177 177
     dnl --------------------------------------------------------------
    
    178
    -FIND_LD([$target],[GccUseLdOpt])
    
    178
    +dnl currently if you pass $LD=foo, merge objs command will be set to $(which foo)
    
    179
    +dnl which is not required by GHC and also wrong.
    
    180
    +BINDIST_DETERMINE_LINKER([$target],[GccUseLdOpt])
    
    181
    +dnl at this point, we should have set LD in all cases, so FIND_MERGE_OBJECTS command can
    
    182
    +dnl go off and do it's thing
    
    179 183
     FIND_MERGE_OBJECTS()
    
    180 184
     CONF_GCC_LINKER_OPTS_STAGE1="$CONF_GCC_LINKER_OPTS_STAGE1 $GccUseLdOpt"
    
    181 185
     CONF_GCC_LINKER_OPTS_STAGE2="$CONF_GCC_LINKER_OPTS_STAGE2 $GccUseLdOpt"
    
    ... ... @@ -427,6 +431,7 @@ checkMake380 make
    427 431
     checkMake380 gmake
    
    428 432
     
    
    429 433
     # Toolchain target files
    
    434
    +USER_LD="$LD"
    
    430 435
     FIND_GHC_TOOLCHAIN_BIN([YES])
    
    431 436
     PREP_TARGET_FILE
    
    432 437
     FIND_GHC_TOOLCHAIN([.])
    

  • m4/bindist_determine_linker.m4
    1
    +# BINDIST_DETERMINE_LINKER
    
    2
    +# ------------------------
    
    3
    +#
    
    4
    +# This is used to determine the linker within the bindists configure
    
    5
    +#
    
    6
    +# Notes:
    
    7
    +# - usually, linking works by invoking $CC
    
    8
    +# - objects are merged using $LD directly
    
    9
    +# - $LD is a configure variable and is meaningless to $CC
    
    10
    +# - gcc only knows linker *flavours*, it cannot use paths
    
    11
    +#   which means that the linker path should not be an absolute path
    
    12
    +# - clang konws --ld-path which means that it can be passed that
    
    13
    +#   flag and also merge objs can be an absolute path
    
    14
    +#
    
    15
    +# Algorithm:
    
    16
    +# if $LD is set
    
    17
    +#    then if $CC accepts --ld-path=$(which $LD)
    
    18
    +#            then set --ld-path=$(which $LD), MergeObjsCommand=$(which $LD)
    
    19
    +#            else if $CC accepts --fuse-ld=$LD ($LD is a linker flavour, not an absolute path)
    
    20
    +#                    then set -fuse-ld=$LD, MergeObjsCommand=$LD (not $(which ld))
    
    21
    +#                    else Reject with
    
    22
    +#                            "$LD is not compatible with $CC you chose. This means that $LD is either
    
    23
    +#                             an unsupported linker flavour or your $CC does not support absolute linker
    
    24
    +#                             paths"
    
    25
    +#    else if --disable-ld-override is set or $target is macos
    
    26
    +#            then if $CC accepts --ld-path=$(which ld)
    
    27
    +#                    then set --ld-path=$(which ld), set MergeObjsCommand=$(which ld)
    
    28
    +#                    else set *no* flag (equivalent to --fuse-ld=ld, if you will), set MergeObjsCommand=ld
    
    29
    +#            else if $CC accepts --ld-path=$(which ld.lld)
    
    30
    +#                    then set --ld-path=$(which ld.lld), MergeObjsCommand=$(which ld.lld)
    
    31
    +#                    else if $CC accepts -fuse-ld=lld
    
    32
    +#                            then set -fuse-ld=lld, MergeObjsCommand=ld.lld
    
    33
    +#                            else set *no* flag (equivalent to --fuse-ld=ld), set MergeObjsCommand=ld
    
    34
    +#
    
    35
    +# $1 = the platform
    
    36
    +# $2 = the variable to set with GHC options to configure gcc to use the chosen linker
    
    37
    +#
    
    38
    +AC_DEFUN([BINDIST_DETERMINE_LINKER],[
    
    39
    +    AC_ARG_ENABLE(ld-override,
    
    40
    +      [AS_HELP_STRING([--disable-ld-override],
    
    41
    +        [Prevent GHC from overriding the default linker used by gcc. If ld-override is enabled GHC will try to tell gcc to use whichever linker is selected by the LD environment variable. [default=override enabled]])],
    
    42
    +      [],
    
    43
    +      [enable_ld_override=yes])
    
    44
    +
    
    45
    +  AC_REQUIRE([AC_PROG_CC])
    
    46
    +  AC_REQUIRE([AC_CANONICAL_TARGET])
    
    47
    +
    
    48
    +  check_ld_path() {
    
    49
    +       AC_MSG_CHECKING([whether C compiler supports --ld-path=[$]1])
    
    50
    +       ld_path="[$]1"
    
    51
    +       echo 'int main(void) { return 0; }' > conftest.c
    
    52
    +       if $CC -o conftest.o "--ld-path=$ld_path" $LDFLAGS conftest.c > /dev/null 2>&1
    
    53
    +       then
    
    54
    +           AC_MSG_RESULT([yes])
    
    55
    +           ld_path_ok=yes
    
    56
    +       else
    
    57
    +           AC_MSG_RESULT([no])
    
    58
    +           ld_path_ok=no
    
    59
    +       fi
    
    60
    +       rm -f conftest.c conftest.o
    
    61
    +  }
    
    62
    +
    
    63
    +  check_fuse_ld() {
    
    64
    +    AC_MSG_CHECKING([whether C compiler supports -fuse-ld=[$]1])
    
    65
    +    ld="[$]1"
    
    66
    +    echo 'int main(void) {return 0;}' > conftest.c
    
    67
    +    if $CC -o conftest.o -fuse-ld=[$]1 $LDFLAGS conftest.c > /dev/null 2>&1
    
    68
    +    then
    
    69
    +        AC_MSG_RESULT([yes])
    
    70
    +        fuse_ld_ok=yes
    
    71
    +    else
    
    72
    +        AC_MSG_RESULT([no])
    
    73
    +        fuse_ld_ok=no
    
    74
    +    fi
    
    75
    +    rm -f conftest.c conftest.o
    
    76
    +  }
    
    77
    +
    
    78
    +  try_set_linker_to() {
    
    79
    +    AC_MSG_CHECKING([whether linker can be set to [$]1])
    
    80
    +    tmp_ld=[$]1
    
    81
    +    ld_path_ok="no"
    
    82
    +    if test "z$tmp_ld" != "z" && check_ld_path "$tmp_ld" && test "x$ld_path_ok" = "xyes";
    
    83
    +       then $2="--ld-path=$tmp_ld"
    
    84
    +            AC_CHECK_TARGET_TOOL([LD], [$tmp_ld])
    
    85
    +            linker_set_successfully=yes
    
    86
    +       else # --ld-path does not work or $LD cannot be resolved to an absolute path
    
    87
    +            fuse_ld_ok=no
    
    88
    +            if check_fuse_ld "$tmp_ld"  && test "x$fuse_ld_ok" = "xyes";
    
    89
    +               then $2="-fuse-ld=$tmp_ld"
    
    90
    +                    AC_CHECK_TARGET_TOOL([LD], [$tmp_ld])
    
    91
    +                    linker_set_successfully=yes
    
    92
    +               else AC_MSG_WARN(["$tmp_ld could not be set via either '--ld-path' or '-fuse-ld"])
    
    93
    +                    linker_set_successfully=no
    
    94
    +            fi
    
    95
    +    fi
    
    96
    +  }
    
    97
    +
    
    98
    +  # we are lenient when $LD=ld and just act as if $LD wasn't set and 
    
    99
    +  # enable-ld-override is off
    
    100
    +  if test "z$LD" != "z" && test "z$LD" != "zld";
    
    101
    +     then linker_set_successfully=no
    
    102
    +          try_set_linker_to "$LD"
    
    103
    +          if test "z$linker_set_successfully" != "zyes";
    
    104
    +             then AC_MSG_FAILURE([ $tmp_ld is an invalid linker. If your C compiler accepts the '--ld-path' flag,
    
    105
    +                  \$LD can be either of an executable name that is in \$PATH *or* a path to an executable.
    
    106
    +                  If your C compiler only supports the '--fuse-ld' flag, \$LD can only be one of the linker flavours supported
    
    107
    +                  by it. Mind that if your C compiler supports '--ld-path', 'configure' will always prefer using an absolute path
    
    108
    +                  to your linker as that is less error-prone.])
    
    109
    +          fi
    
    110
    +
    
    111
    +     else # $LD is not set -- we will do the ld-override non-sense
    
    112
    +          if test "x$enable_ld_override" = "xyes" && test "z$LD" != "zld" && case "$1" in
    
    113
    +                    *-darwin) false ;; # don't do the ld override thing on macos
    
    114
    +                    *) true ;;
    
    115
    +                  esac;
    
    116
    +             then
    
    117
    +                  AC_MSG_NOTICE(["enable ld override was set and no more specific linker was chosen by setting \$LD, trying to find best possible linker"])
    
    118
    +                  try_set_linker_to "lld"
    
    119
    +                  if test "z$linker_set_successfully" != "zyes";
    
    120
    +                     then # ... bail out, just use ld in path
    
    121
    +                          $2=""
    
    122
    +                          AC_CHECK_TARGET_TOOL([LD], [ld])
    
    123
    +                  fi
    
    124
    +             else # ld override is not set and $LD not set either
    
    125
    +                  $2=""
    
    126
    +                  AC_CHECK_TARGET_TOOL([LD], [ld])
    
    127
    +          fi
    
    128
    +  fi
    
    129
    +
    
    130
    +  AC_MSG_NOTICE([linker discovery set $2 set to $$2])
    
    131
    +
    
    132
    +  CHECK_LD_COPY_BUG([$1])
    
    133
    +])

  • m4/find_merge_objects.m4
    ... ... @@ -22,7 +22,6 @@ AC_DEFUN([CHECK_MERGE_OBJECTS],[
    22 22
     ])
    
    23 23
     
    
    24 24
     AC_DEFUN([FIND_MERGE_OBJECTS],[
    
    25
    -    AC_REQUIRE([FIND_LD])
    
    26 25
     
    
    27 26
         if test -z ${MergeObjsCmd+x}; then
    
    28 27
             AC_MSG_NOTICE([Setting cmd])
    

  • utils/ghc-toolchain/exe/Main.hs
    1 1
     {-# LANGUAGE NamedFieldPuns #-}
    
    2 2
     {-# LANGUAGE LambdaCase #-}
    
    3 3
     {-# LANGUAGE TypeApplications #-}
    
    4
    +{-# LANGUAGE ScopedTypeVariables #-}
    
    5
    +{-# LANGUAGE ViewPatterns #-}
    
    4 6
     
    
    5 7
     module Main where
    
    6 8
     
    
    ... ... @@ -11,7 +13,7 @@ import System.Exit
    11 13
     import System.Console.GetOpt
    
    12 14
     import System.Environment
    
    13 15
     import System.FilePath ((</>))
    
    14
    -import qualified System.IO (readFile, writeFile)
    
    16
    +import qualified System.IO (writeFile, readFile')
    
    15 17
     
    
    16 18
     import GHC.Platform.ArchOS
    
    17 19
     
    
    ... ... @@ -33,6 +35,10 @@ import GHC.Toolchain.Tools.MergeObjs
    33 35
     import GHC.Toolchain.Tools.Readelf
    
    34 36
     import GHC.Toolchain.NormaliseTriple (normaliseTriple)
    
    35 37
     import Text.Read (readMaybe)
    
    38
    +import System.IO (hPutStrLn, stderr)
    
    39
    +import Control.Exception (try, IOException, catch, displayException)
    
    40
    +import GHC.Stack (HasCallStack)
    
    41
    +import Data.Foldable (traverse_)
    
    36 42
     
    
    37 43
     data Opts = Opts
    
    38 44
         { optTriple    :: Maybe String
    
    ... ... @@ -72,6 +78,8 @@ data Opts = Opts
    72 78
         , optTablesNextToCode :: Maybe Bool
    
    73 79
         , optUseLibFFIForAdjustors :: Maybe Bool
    
    74 80
         , optLdOverride :: Maybe Bool
    
    81
    +      -- ^ whether or not to not use ld in $PATH and instead search for a
    
    82
    +      --   linker that GHC deems "better"
    
    75 83
         , optVerbosity :: Int
    
    76 84
         , optKeepTemp  :: Bool
    
    77 85
         }
    
    ... ... @@ -200,7 +208,7 @@ options =
    200 208
         [ enableDisable "unregisterised" "unregisterised backend" _optUnregisterised
    
    201 209
         , enableDisable "tables-next-to-code" "info-tables-next-to-code optimisation" _optTablesNextToCode
    
    202 210
         , enableDisable "libffi-adjustors" "the use of libffi for adjustors, even on platforms which have support for more efficient, native adjustor implementations." _optUseLibFFIForAdjustors
    
    203
    -    , enableDisable "ld-override" "override gcc's default linker" _optLdOvveride
    
    211
    +    , enableDisable "ld-override" "search for a more efficient linker than your default linker" _optLdOvveride
    
    204 212
         , enableDisable "locally-executable" "the use of a target prefix which will be added to all tool names when searching for toolchain components" _optLocallyExecutable
    
    205 213
         , enableDisable "dwarf-unwind" "Enable DWARF unwinding support in the runtime system via elfutils' libdw" _optDwarfUnwind
    
    206 214
         ] ++
    
    ... ... @@ -280,12 +288,11 @@ options =
    280 288
             "The output path for the generated target toolchain configuration"
    
    281 289
     
    
    282 290
     formatOpts :: [OptDescr (FormatOpts -> FormatOpts)]
    
    283
    -formatOpts = [
    
    284
    -    (Option ['o'] ["output"] (ReqArg (set _formatOptOutput) "OUTPUT")
    
    291
    +formatOpts =
    
    292
    +    [ (Option ['o'] ["output"] (ReqArg (set _formatOptOutput) "OUTPUT")
    
    285 293
             "The output path for the formatted target toolchain configuration")
    
    286 294
         , (Option ['i'] ["input"] (ReqArg (set _formatOptInput) "INPUT")
    
    287
    -        "The target file to format")
    
    288
    -    ]
    
    295
    +        "The target file to format") ]
    
    289 296
     
    
    290 297
     validateOpts :: Opts -> [String]
    
    291 298
     validateOpts opts = mconcat
    
    ... ... @@ -297,30 +304,38 @@ main :: IO ()
    297 304
     main = do
    
    298 305
         argv <- getArgs
    
    299 306
         case argv of
    
    300
    -      ("format": args) -> doFormat args
    
    307
    +      ("format" : args) -> doFormat args
    
    301 308
           _ -> doConfigure argv
    
    302 309
     
    
    303 310
     -- The format mode is very useful for normalising paths and newlines on windows.
    
    304
    -doFormat :: [String] -> IO ()
    
    311
    +doFormat :: HasCallStack => [String] -> IO ()
    
    305 312
     doFormat args = do
    
    306 313
       let (opts0, _nonopts, errs) = getOpt RequireOrder formatOpts args
    
    307 314
       case errs of
    
    308 315
         [] -> do
    
    309 316
           let opts = foldr (.) id opts0 emptyFormatOpts
    
    310
    -      tgtFile <- System.IO.readFile (view _formatOptInput opts)
    
    311
    -      case readMaybe @Target tgtFile of
    
    312
    -        Nothing -> error $ "Failed to read a valid Target value from " ++ view _formatOptInput opts ++ ":\n" ++ tgtFile
    
    313
    -        Just tgt -> do
    
    317
    +      tgtFile <- try @IOException $ System.IO.readFile' (view _formatOptInput opts)
    
    318
    +      case tgtFile of
    
    319
    +        Right (readMaybe @Target -> Just tgt) -> do
    
    314 320
               let file = formatOptOutput opts
    
    315 321
               System.IO.writeFile file (show tgt)
    
    322
    +            `catch` \(e :: IOException) -> do
    
    323
    +              hPutStrLn stderr $ "Failed to write the formatted Target file to" ++ file ++ ". Writing caused the following IOException:\n"
    
    324
    +                ++ displayException e
    
    325
    +        Right contents -> do
    
    326
    +          hPutStrLn stderr $ "Failed to read a valid Target value from " ++ view _formatOptInput opts ++ "invalid file was:\n" ++ contents
    
    327
    +          exitWith (ExitFailure 1)
    
    328
    +        Left reason -> do
    
    329
    +          hPutStrLn stderr $ "Failed to read a valid Target value from " ++ view _formatOptInput opts ++ ", because an IOException occured:\n" ++ displayException reason
    
    330
    +          exitWith (ExitFailure 1)
    
    316 331
         _ -> do
    
    317
    -      mapM_ putStrLn errs
    
    318
    -      putStrLn $ usageInfo "ghc-toolchain" formatOpts
    
    332
    +      mapM_ (hPutStrLn stderr) errs
    
    333
    +      hPutStrLn stderr $ usageInfo "ghc-toolchain" formatOpts
    
    319 334
           exitWith (ExitFailure 1)
    
    320 335
     
    
    321 336
     
    
    322 337
     
    
    323
    -doConfigure :: [String] -> IO ()
    
    338
    +doConfigure :: HasCallStack => [String] -> IO ()
    
    324 339
     doConfigure args = do
    
    325 340
         let (opts0, _nonopts, parseErrs) = getOpt RequireOrder options args
    
    326 341
         let opts = foldr (.) id opts0 emptyOpts
    
    ... ... @@ -329,18 +344,22 @@ doConfigure args = do
    329 344
               let env = Env { verbosity = optVerbosity opts
    
    330 345
                             , targetPrefix = case optTargetPrefix opts of
    
    331 346
                                                Just prefix -> Just prefix
    
    347
    +                                           -- TODO: why is this `fromMaybe (error _)`? that seems wrong (ah okay, because that would already mean that `errs` is not null; seems bad that we have this here though)
    
    332 348
                                                Nothing -> Just $ fromMaybe (error "undefined triple") (optTriple opts) ++ "-"
    
    333 349
                             , keepTemp = optKeepTemp opts
    
    334 350
                             , canLocallyExecute = fromMaybe True (optLocallyExecutable opts)
    
    335 351
                             , logContexts = []
    
    336 352
                             }
    
    337 353
               r <- runM env (run opts)
    
    354
    +            `catch` \(e :: IOException) -> pure $ Left [Error {errorLogContexts = [], errorMessage = displayException e}]
    
    338 355
               case r of
    
    339
    -            Left err -> print err >> exitWith (ExitFailure 2)
    
    356
    +            Left errs -> do
    
    357
    +              traverse_ (hPutStrLn stderr . formatError) errs
    
    358
    +              exitWith (ExitFailure 1)
    
    340 359
                 Right () -> return ()
    
    341 360
           errs -> do
    
    342
    -        mapM_ putStrLn errs
    
    343
    -        putStrLn $ usageInfo "ghc-toolchain" options
    
    361
    +        mapM_ (hPutStrLn stderr) errs
    
    362
    +        hPutStrLn stderr $ usageInfo "ghc-toolchain" options
    
    344 363
             exitWith (ExitFailure 1)
    
    345 364
     
    
    346 365
     run :: Opts -> M ()
    
    ... ... @@ -449,15 +468,15 @@ mkTarget opts = do
    449 468
           cc0 <- findBasicCc (optCc opts)
    
    450 469
           parseTriple cc0 normalised_triple
    
    451 470
     
    
    452
    -    cc0 <- findCc archOs tgtLlvmTarget (optCc opts)
    
    471
    +    cc <- findCc archOs tgtLlvmTarget (optCc opts)
    
    453 472
         cxx <- findCxx archOs tgtLlvmTarget (optCxx opts)
    
    454
    -    cpp <- findCpp (optCpp opts) cc0
    
    455
    -    hsCpp <- findHsCpp (optHsCpp opts) cc0
    
    473
    +    cpp <- findCpp (optCpp opts) cc
    
    474
    +    hsCpp <- findHsCpp (optHsCpp opts) cc
    
    456 475
         -- TODO: same case as ranlib below
    
    457 476
         -- TODO: we need it really only for javascript target (maybe wasm target as well)
    
    458
    -    jsCpp <- Just <$> findJsCpp (optJsCpp opts) cc0
    
    459
    -    cmmCpp <- findCmmCpp (optCmmCpp opts) cc0
    
    460
    -    cc <- addPlatformDepCcFlags archOs cc0
    
    477
    +    jsCpp <- Just <$> findJsCpp (optJsCpp opts) cc
    
    478
    +    cmmCpp <- findCmmCpp (optCmmCpp opts) cc
    
    479
    +    ccWithPlatformFlags <- addPlatformDepCcFlags archOs cc
    
    461 480
         readelf <- optional $ findReadelf (optReadelf opts)
    
    462 481
         -- TODO: We could have
    
    463 482
         -- ranlib <- if arNeedsRanlib ar
    
    ... ... @@ -466,11 +485,21 @@ mkTarget opts = do
    466 485
         -- but in order to match the configure output, for now we do
    
    467 486
         ranlib <- findRanlib (optRanlib opts)
    
    468 487
         ar <- findAr tgtVendor (optAr opts)
    
    469
    -    ccLink <- findCcLink tgtLlvmTarget (optLd opts) (optCcLink opts) (ldOverrideWhitelist archOs && fromMaybe True (optLdOverride opts)) archOs cc readelf ar ranlib
    
    470
    -
    
    488
    +    ccLink <- findCcLink
    
    489
    +      tgtLlvmTarget
    
    490
    +      (optLd opts)
    
    491
    +      (optCcLink opts)
    
    492
    +      (ldOverrideWhitelist archOs
    
    493
    +        -- ld-override is enabled by default
    
    494
    +        && fromMaybe True (optLdOverride opts))
    
    495
    +      archOs
    
    496
    +      ccWithPlatformFlags
    
    497
    +      readelf
    
    498
    +      ar
    
    499
    +      ranlib
    
    471 500
     
    
    472 501
         nm <- findNm (optNm opts)
    
    473
    -    mergeObjs <- optional $ findMergeObjs (optMergeObjs opts) cc ccLink nm
    
    502
    +    mergeObjs <- optional $ findMergeObjs (optMergeObjs opts) ccWithPlatformFlags ccLink nm
    
    474 503
     
    
    475 504
         when (isNothing mergeObjs && not (arSupportsDashL ar)) $
    
    476 505
           throwE "Neither a object-merging tool (e.g. ld -r) nor an ar that supports -L is available"
    
    ... ... @@ -494,15 +523,15 @@ mkTarget opts = do
    494 523
               _ -> return (Nothing, Nothing)
    
    495 524
     
    
    496 525
         -- various other properties of the platform
    
    497
    -    tgtWordSize <- checkWordSize cc
    
    498
    -    tgtEndianness <- checkEndianness cc
    
    499
    -    tgtSymbolsHaveLeadingUnderscore <- checkLeadingUnderscore cc nm
    
    500
    -    tgtSupportsSubsectionsViaSymbols <- checkSubsectionsViaSymbols archOs cc
    
    501
    -    tgtSupportsIdentDirective <- checkIdentDirective cc
    
    502
    -    tgtSupportsGnuNonexecStack <- checkGnuNonexecStack archOs cc
    
    503
    -    tgtHasLibm <- checkTargetHasLibm cc
    
    526
    +    tgtWordSize <- checkWordSize ccWithPlatformFlags
    
    527
    +    tgtEndianness <- checkEndianness ccWithPlatformFlags
    
    528
    +    tgtSymbolsHaveLeadingUnderscore <- checkLeadingUnderscore ccWithPlatformFlags nm
    
    529
    +    tgtSupportsSubsectionsViaSymbols <- checkSubsectionsViaSymbols archOs ccWithPlatformFlags
    
    530
    +    tgtSupportsIdentDirective <- checkIdentDirective ccWithPlatformFlags
    
    531
    +    tgtSupportsGnuNonexecStack <- checkGnuNonexecStack archOs ccWithPlatformFlags
    
    532
    +    tgtHasLibm <- checkTargetHasLibm ccWithPlatformFlags
    
    504 533
         tgtRTSWithLibdw <- case optDwarfUnwind opts of
    
    505
    -      Just True -> checkTargetHasLibdw cc (optLibdwIncludes opts) (optLibdwLibraries opts)
    
    534
    +      Just True -> checkTargetHasLibdw ccWithPlatformFlags (optLibdwIncludes opts) (optLibdwLibraries opts)
    
    506 535
           _         -> pure Nothing
    
    507 536
     
    
    508 537
         -- code generator configuration
    
    ... ... @@ -515,14 +544,14 @@ mkTarget opts = do
    515 544
             let prog = "int main(int argc, char** argv) { return 0; }"
    
    516 545
                 via_c_args = ["-fwrapv", "-fno-builtin"]
    
    517 546
             forM_ via_c_args $ \arg -> checking ("support of "++arg) $ withTempDir $ \dir -> do
    
    518
    -            let cc' = over (_ccProgram % _prgFlags) (++ [arg]) cc
    
    547
    +            let cc' = over (_ccProgram % _prgFlags) (++ [arg]) ccWithPlatformFlags
    
    519 548
                 compileC cc' (dir </> "test.o") prog
    
    520 549
                 return ()
    
    521 550
     
    
    522 551
         let t = Target { tgtArchOs = archOs
    
    523 552
                        , tgtVendor
    
    524 553
                        , tgtLocallyExecutable = fromMaybe True (optLocallyExecutable opts)
    
    525
    -                   , tgtCCompiler = cc
    
    554
    +                   , tgtCCompiler = ccWithPlatformFlags
    
    526 555
                        , tgtCxxCompiler = cxx
    
    527 556
                        , tgtCPreprocessor = cpp
    
    528 557
                        , tgtHsCPreprocessor = hsCpp
    

  • utils/ghc-toolchain/src/GHC/Toolchain/Lens.hs
    1
    +{-# LANGUAGE DataKinds #-}
    
    1 2
     -- | A very simple Lens implementation
    
    2 3
     module GHC.Toolchain.Lens
    
    3 4
         ( Lens(..)
    
    ... ... @@ -7,11 +8,15 @@ module GHC.Toolchain.Lens
    7 8
         , (&)
    
    8 9
         ) where
    
    9 10
     
    
    10
    -import Prelude ((.), ($), (++))
    
    11
    +import Prelude ((.), ($), (++), Monoid, (<>))
    
    11 12
     import Data.Function ((&))
    
    13
    +import GHC.Records
    
    12 14
     
    
    13 15
     data Lens a b = Lens { view :: (a -> b), set :: (b -> a -> a) }
    
    14 16
     
    
    17
    +instance HasField "over" (Lens a b) ((b -> b) -> a -> a) where
    
    18
    +  getField = over
    
    19
    +
    
    15 20
     (%) :: Lens a b -> Lens b c -> Lens a c
    
    16 21
     a % b = Lens { view = view b . view a
    
    17 22
                  , set = \y x -> set a (set b y (view a x)) x
    

  • utils/ghc-toolchain/src/GHC/Toolchain/Monad.hs
    1 1
     {-# LANGUAGE GeneralizedNewtypeDeriving #-}
    
    2 2
     {-# LANGUAGE DerivingVia #-}
    
    3
    +{-# LANGUAGE NamedFieldPuns #-}
    
    3 4
     
    
    4 5
     module GHC.Toolchain.Monad
    
    5 6
         ( Env(..)
    
    ... ... @@ -21,6 +22,10 @@ module GHC.Toolchain.Monad
    21 22
         , logDebug
    
    22 23
         , checking
    
    23 24
         , withLogContext
    
    25
    +
    
    26
    +      -- * Errors
    
    27
    +    , Error (..)
    
    28
    +    , formatError
    
    24 29
         ) where
    
    25 30
     
    
    26 31
     import Prelude hiding (readFile, writeFile, appendFile)
    
    ... ... @@ -63,6 +68,9 @@ data Error = Error { errorMessage :: String
    63 68
                        }
    
    64 69
         deriving (Show)
    
    65 70
     
    
    71
    +formatError :: Error -> String
    
    72
    +formatError Error {errorMessage, errorLogContexts} = unlines $ errorMessage : errorLogContexts
    
    73
    +
    
    66 74
     throwE :: String -> M a
    
    67 75
     throwE msg = throwEs [msg]
    
    68 76
     
    

  • utils/ghc-toolchain/src/GHC/Toolchain/Tools/Cc.hs
    1 1
     {-# LANGUAGE NamedFieldPuns #-}
    
    2 2
     {-# LANGUAGE ViewPatterns #-}
    
    3
    +{-# LANGUAGE MultiWayIf #-}
    
    3 4
     
    
    4 5
     module GHC.Toolchain.Tools.Cc
    
    5 6
         ( Cc(..)
    
    ... ... @@ -23,6 +24,7 @@ import GHC.Platform.ArchOS
    23 24
     import GHC.Toolchain.Prelude
    
    24 25
     import GHC.Toolchain.Utils
    
    25 26
     import GHC.Toolchain.Program
    
    27
    +import System.Exit (ExitCode(..))
    
    26 28
     
    
    27 29
     newtype Cc = Cc { ccProgram :: Program
    
    28 30
                     }
    
    ... ... @@ -109,11 +111,12 @@ checkCcSupportsExtraViaCFlags cc = checking "whether cc supports extra via-c fla
    109 111
                                       , "-fwrapv", "-fno-builtin"
    
    110 112
                                       , "-Werror", "-x", "c"
    
    111 113
                                       , "-o", test_o, test_c]
    
    112
    -  when (not (isSuccess code)
    
    113
    -        || "unrecognized" `isInfixOf` out
    
    114
    -        || "unrecognized" `isInfixOf` err
    
    115
    -        ) $
    
    116
    -    throwE "Your C compiler must support the -fwrapv and -fno-builtin flags"
    
    114
    +
    
    115
    +  if | ExitSuccess <- code
    
    116
    +     , not $ "unrecognized" `isInfixOf` out
    
    117
    +     , not $ "unrecognized" `isInfixOf` err
    
    118
    +     -> pure ()
    
    119
    +     | otherwise -> throwE "Your C compiler must support the -fwrapv and -fno-builtin flags"
    
    117 120
     
    
    118 121
     -- | Preprocess the given program.
    
    119 122
     preprocess
    

  • utils/ghc-toolchain/src/GHC/Toolchain/Tools/Link.hs
    1
    -{-# OPTIONS_GHC -Wno-name-shadowing #-}
    
    2 1
     {-# LANGUAGE NamedFieldPuns #-}
    
    3 2
     {-# LANGUAGE RecordWildCards #-}
    
    4 3
     {-# LANGUAGE CPP #-}
    
    4
    +{-# LANGUAGE MultiWayIf #-}
    
    5
    +{-# LANGUAGE OverloadedRecordDot #-}
    
    5 6
     
    
    6 7
     module GHC.Toolchain.Tools.Link ( CcLink(..), findCcLink ) where
    
    7 8
     
    
    ... ... @@ -18,6 +19,8 @@ import GHC.Toolchain.Tools.Cc
    18 19
     import GHC.Toolchain.Tools.Ar
    
    19 20
     import GHC.Toolchain.Tools.Ranlib
    
    20 21
     import GHC.Toolchain.Tools.Readelf
    
    22
    +import System.Exit (ExitCode(..))
    
    23
    +import Control.Applicative
    
    21 24
     
    
    22 25
     -- | Configuration on how the C compiler can be used to link
    
    23 26
     data CcLink = CcLink { ccLinkProgram :: Program
    
    ... ... @@ -47,61 +50,97 @@ instance Show CcLink where
    47 50
     _ccLinkProgram :: Lens CcLink Program
    
    48 51
     _ccLinkProgram = Lens ccLinkProgram (\x o -> o{ccLinkProgram=x})
    
    49 52
     
    
    50
    -findCcLink :: String -- ^ The llvm target to use if CcLink supports --target
    
    51
    -           -> ProgOpt
    
    52
    -           -> ProgOpt
    
    53
    -           -> Bool   -- ^ Whether we should search for a more efficient linker
    
    54
    -           -> ArchOS -> Cc -> Maybe Readelf -> Ar -> Ranlib -> M CcLink
    
    55
    -findCcLink target ld progOpt ldOverride archOs cc readelf ar ranlib = checking "for C compiler for linking command" $ do
    
    53
    +-- | tries to add flags to the c compiler to run as a linker
    
    54
    +findCcLink :: String  -- ^ The llvm target to use if CcLink supports --target
    
    55
    +           -> ProgOpt -- ^ The contents of $LD
    
    56
    +           -> ProgOpt -- ^ The c compiler intended for invoking the linker
    
    57
    +           -> Bool    -- ^ Whether GHC should disregard ld and search for a linker it considers better
    
    58
    +           -> ArchOS
    
    59
    +           -> Cc      -- ^ the c compiler used for compiling c programs, used as a fallback
    
    60
    +           -> Maybe Readelf -> Ar -> Ranlib -> M CcLink
    
    61
    +findCcLink target ld progOpt userLdOverride archOs cc readelf ar ranlib = checking "for C compiler for linking command" $ do
    
    56 62
       -- Use the specified linker or try using the C compiler
    
    57 63
       rawCcLink <- findProgram "C compiler for linking" progOpt [] <|> pure (programFromOpt progOpt (prgPath $ ccProgram cc) [])
    
    58
    -  -- See #23857 for why we check to see if LD is set here
    
    59
    -  -- TLDR: If the user explicitly sets LD then in ./configure
    
    60
    -  -- we don't perform a linker search (and set -fuse-ld), so
    
    61
    -  -- we do the same here for consistency.
    
    62
    -  ccLinkProgram <- case (poPath ld, poFlags progOpt) of
    
    63
    -                     (_, Just _) ->
    
    64
    -                         -- If the user specified linker flags don't second-guess them
    
    65
    -                         pure rawCcLink
    
    66
    -                     (Just {}, _) ->
    
    67
    -                         pure rawCcLink
    
    68
    -                     _ -> do
    
    69
    -                         -- If not then try to find decent linker flags
    
    70
    -                         findLinkFlags ldOverride cc rawCcLink <|> pure rawCcLink
    
    71
    -  ccLinkProgram <- linkSupportsTarget archOs cc target ccLinkProgram
    
    72
    -  ccLinkSupportsNoPie         <- checkSupportsNoPie  cc ccLinkProgram
    
    73
    -  ccLinkSupportsCompactUnwind <- checkSupportsCompactUnwind archOs cc ccLinkProgram
    
    74
    -  ccLinkSupportsFilelist      <- checkSupportsFilelist cc ccLinkProgram
    
    75
    -  ccLinkSupportsSingleModule  <- checkSupportsSingleModule archOs cc ccLinkProgram
    
    76
    -  ccLinkIsGnu                 <- checkLinkIsGnu archOs ccLinkProgram
    
    77
    -  checkBfdCopyBug archOs cc readelf ccLinkProgram
    
    78
    -  ccLinkProgram <- addPlatformDepLinkFlags archOs cc ccLinkProgram
    
    79
    -  ccLinkSupportsVerbatimNamespace <- linkSupportsVerbatimNamespace cc ar ranlib ccLinkProgram
    
    80
    -  let ccLink = CcLink {ccLinkProgram, ccLinkSupportsNoPie,
    
    81
    -                       ccLinkSupportsCompactUnwind, ccLinkSupportsFilelist,
    
    82
    -                       ccLinkSupportsSingleModule, ccLinkIsGnu, ccLinkSupportsVerbatimNamespace}
    
    83
    -  ccLink <- linkRequiresNoFixupChains archOs cc ccLink
    
    84
    -  ccLink <- linkRequiresNoWarnDuplicateLibraries archOs cc ccLink
    
    85
    -  return ccLink
    
    86
    -
    
    87
    -
    
    88
    --- | Try to convince @cc@ to use a more efficient linker than @bfd.ld@
    
    89
    -findLinkFlags :: Bool -> Cc -> Program -> M Program
    
    90
    -findLinkFlags enableOverride cc ccLink
    
    91
    -  | enableOverride && doLinkerSearch =
    
    92
    -    oneOf "this can't happen"
    
    93
    -        [ -- Annoyingly, gcc silently falls back to vanilla ld (typically bfd
    
    94
    -          -- ld) if @-fuse-ld@ is given with a non-existent linker.
    
    95
    -          -- Consequently, we must first check that the desired ld
    
    96
    -          -- executable exists before trying cc.
    
    97
    -          do _ <- findProgram (linker ++ " linker") emptyProgOpt ["ld."++linker]
    
    98
    -             prog <$ checkLinkWorks cc prog
    
    99
    -        | linker <- ["lld", "bfd"]
    
    100
    -        , let prog = over _prgFlags (++["-fuse-ld="++linker]) ccLink
    
    101
    -        ]
    
    102
    -        <|> (ccLink <$ checkLinkWorks cc ccLink)
    
    103
    -  | otherwise =
    
    104
    -    return ccLink
    
    64
    +  ccLinkProgram <- if
    
    65
    +    -- A cc with linker was already specified, don't doubt the user's proficiency,
    
    66
    +    -- autonomy and right to segmentation faults
    
    67
    +    | Just _ <- progOpt.poFlags -> pure rawCcLink
    
    68
    +    -- we get a $LD; now figure out how to pass it to the $CC
    
    69
    +    | Just ldPathOrFlavour <- ld.poPath
    
    70
    +    -- even though $LD=ld doesn't really mean anything to C compilers,
    
    71
    +    -- we are lenient and just act as if $LD wasn't set and enable-ld-override
    
    72
    +    -- is off
    
    73
    +    , ldPathOrFlavour /= "ld" -> do
    
    74
    +        flip oneOf'
    
    75
    +
    
    76
    +          [ do
    
    77
    +            -- first check if the c compiler supports --ld-path, which goes best with $LD
    
    78
    +            ldPath <- findProgram (ldPathOrFlavour <> " linker") emptyProgOpt $  tryLdPrefix [ldPathOrFlavour]
    
    79
    +            -- findProgram takes a userSpec but in our case this is emptyProgOpt, so we just
    
    80
    +            -- extract the path that it found and ignore the (empty) arguments
    
    81
    +            checkLink rawCcLink [ fLdPath ldPath.prgPath ]
    
    82
    +          , -- second, check if the c compiler instead understands -fuse-ld (linker "flavour");
    
    83
    +            -- do not try to expand the path first since absolute paths are not valid linker flavours
    
    84
    +            checkLink rawCcLink [ fUseLd ldPathOrFlavour] ]
    
    85
    +
    
    86
    +          -- $LD was set but we couldn't figure out how to pass it to $CC. This is a hard failure,
    
    87
    +          -- we report it.
    
    88
    +          [ ldPathOrFlavour <> " is an invalid linker."
    
    89
    +          , "$LD can be either of an executable name that is in $PATH *or* a"
    
    90
    +            <> " path to an executable."
    
    91
    +          , "If your C compiler only supports the '-fuse-ld' flag, $LD can"
    
    92
    +            <> " only be one of the linker flavours supported by it."
    
    93
    +          , "Mind that if your C compiler supports '--ld-path', 'configure'"
    
    94
    +            <> " will always prefer using an absolute path to your linker as"
    
    95
    +            <> " that is less error-prone." ]
    
    96
    +
    
    97
    +    -- $LD is not set or $LD=ld (see above)
    
    98
    +    -- Try to convince @cc@ to use a more efficient linker than @bfd.ld@
    
    99
    +    | let ldOverride
    
    100
    +            | Just "ld" <- ld.poPath = False
    
    101
    +            | otherwise = userLdOverride
    
    102
    +    , ldOverride ->
    
    103
    +       asum
    
    104
    +         [ -- Annoyingly, gcc silently falls back to vanilla ld
    
    105
    +           -- if @-fuse-ld@ is given passed a non-existent linker.
    
    106
    +           -- Consequently, we must first check that the desired ld
    
    107
    +           -- executable exists before trying cc.
    
    108
    +           do linkerPath <- findProgram (linker ++ " linker") emptyProgOpt [ linker ]
    
    109
    +              checkLink rawCcLink [ fLdPath linkerPath.prgPath]
    
    110
    +                <|> checkLink rawCcLink [ fUseLd linker]
    
    111
    +         | linker <- tryLdPrefix ["lld", "bfd"]
    
    112
    +         ]
    
    113
    +       -- fall back to raw ld
    
    114
    +       <|> checkLink rawCcLink []
    
    115
    +
    
    116
    +    -- we can't help the user
    
    117
    +    | otherwise -> checkLink rawCcLink []
    
    118
    +
    
    119
    +  targetedCcLink                  <- linkSupportsTarget archOs cc target ccLinkProgram
    
    120
    +  ccLinkSupportsNoPie             <- checkSupportsNoPie  cc targetedCcLink
    
    121
    +  ccLinkSupportsCompactUnwind     <- checkSupportsCompactUnwind archOs cc targetedCcLink
    
    122
    +  ccLinkSupportsFilelist          <- checkSupportsFilelist cc targetedCcLink
    
    123
    +  ccLinkSupportsSingleModule      <- checkSupportsSingleModule archOs cc targetedCcLink
    
    124
    +  ccLinkIsGnu                     <- checkLinkIsGnu archOs targetedCcLink
    
    125
    +  checkedCcLink                   <- addPlatformDepLinkFlags archOs cc targetedCcLink
    
    126
    +  ccLinkSupportsVerbatimNamespace <- linkSupportsVerbatimNamespace cc ar ranlib checkedCcLink
    
    127
    +
    
    128
    +  checkBfdCopyBug archOs cc readelf targetedCcLink
    
    129
    +
    
    130
    +  let finalCcLink = CcLink
    
    131
    +                    { ccLinkProgram = checkedCcLink, ccLinkSupportsNoPie
    
    132
    +                    , ccLinkSupportsCompactUnwind, ccLinkSupportsFilelist
    
    133
    +                    , ccLinkSupportsSingleModule, ccLinkIsGnu, ccLinkSupportsVerbatimNamespace }
    
    134
    +
    
    135
    +  linkRequiresNoFixupChains archOs cc finalCcLink
    
    136
    +    >>= linkRequiresNoWarnDuplicateLibraries archOs cc
    
    137
    +  where
    
    138
    +    checkLink ccLink extraFlags =
    
    139
    +      let prog = over _prgFlags (extraFlags <>) ccLink
    
    140
    +       in prog <$ checkLinkWorks cc prog
    
    141
    +    tryLdPrefix progs =  [id, ("ld." <>)] <*> progs
    
    142
    +    fUseLd flavour = "-fuse-ld=" <> flavour
    
    143
    +    fLdPath path = "--ld-path=" <> path
    
    105 144
     
    
    106 145
     -- | Test whether the linker supports the verbatim '-l:libfoo.a' syntax, allowing
    
    107 146
     -- us better control over partial static linking.
    
    ... ... @@ -150,20 +189,6 @@ linkSupportsTarget archOs cc target link =
    150 189
         checking "whether cc linker supports --target" $
    
    151 190
         supportsTarget archOs (Lens id const) (checkLinkWorks cc) target link
    
    152 191
     
    
    153
    --- | Should we attempt to find a more efficient linker on this platform?
    
    154
    ---
    
    155
    --- N.B. On Darwin it is quite important that we use the system linker
    
    156
    --- unchanged as it is very easy to run into broken setups (e.g. unholy mixtures
    
    157
    --- of Homebrew and the Apple toolchain).
    
    158
    ---
    
    159
    --- See #21712.
    
    160
    -doLinkerSearch :: Bool
    
    161
    -#if defined(linux_HOST_OS)
    
    162
    -doLinkerSearch = True
    
    163
    -#else
    
    164
    -doLinkerSearch = False
    
    165
    -#endif
    
    166
    -
    
    167 192
     -- | See Note [No PIE when linking] in GHC.Driver.Session
    
    168 193
     checkSupportsNoPie :: Cc -> Program -> M Bool
    
    169 194
     checkSupportsNoPie cc ccLink = checking "whether the cc linker supports -no-pie" $
    
    ... ... @@ -174,7 +199,11 @@ checkSupportsNoPie cc ccLink = checking "whether the cc linker supports -no-pie"
    174 199
         -- Check output as some GCC versions only warn and don't respect -Werror
    
    175 200
         -- when passed an unrecognized flag.
    
    176 201
         (code, out, err) <- readProgram ccLink ["-no-pie", "-Werror", test_o, "-o", test]
    
    177
    -    return (isSuccess code && not ("unrecognized" `isInfixOf` out) && not ("unrecognized" `isInfixOf` err))
    
    202
    +    return if
    
    203
    +      | ExitSuccess <- code
    
    204
    +      , not ("unrecognized" `isInfixOf` out)
    
    205
    +      , not ("unrecognized" `isInfixOf` err) -> True
    
    206
    +      | otherwise -> False
    
    178 207
     
    
    179 208
     -- ROMES:TODO: This check is wrong here and in configure because with ld.gold parses "-n" "o_compact_unwind"
    
    180 209
     -- TODO:
    
    ... ... @@ -191,7 +220,8 @@ checkSupportsCompactUnwind archOs cc ccLink
    191 220
             compileC cc test_o "int foo() { return 0; }"
    
    192 221
     
    
    193 222
             exitCode <- runProgram ccLink ["-r", "-Wl,-no_compact_unwind", "-o", test2_o, test_o]
    
    194
    -        return $ isSuccess exitCode
    
    223
    +        return if | ExitSuccess <- exitCode -> True
    
    224
    +                  | otherwise -> False
    
    195 225
       | otherwise = return False
    
    196 226
     
    
    197 227
     checkSupportsFilelist :: Cc -> Program -> M Bool
    
    ... ... @@ -210,7 +240,8 @@ checkSupportsFilelist cc ccLink = checking "whether the cc linker understands -f
    210 240
     
    
    211 241
         exitCode <- runProgram ccLink ["-r", "-Wl,-filelist", test_ofiles, "-o", test_o]
    
    212 242
     
    
    213
    -    return (isSuccess exitCode)
    
    243
    +    return if | ExitSuccess <- exitCode -> True
    
    244
    +              | otherwise -> False
    
    214 245
     
    
    215 246
     -- | Check that the (darwin) linker supports @-single_module@.
    
    216 247
     --
    

  • utils/ghc-toolchain/src/GHC/Toolchain/Utils.hs
    ... ... @@ -7,19 +7,18 @@ module GHC.Toolchain.Utils
    7 7
         , withTempDir
    
    8 8
         , oneOf
    
    9 9
         , oneOf'
    
    10
    -    , isSuccess
    
    11 10
         , lastLine
    
    12 11
         , findM
    
    13 12
         ) where
    
    14 13
     
    
    15
    -import Control.Exception
    
    14
    +import Control.Applicative (asum)
    
    15
    +import Control.Exception ( throwIO, bracket, try )
    
    16 16
     import Control.Monad
    
    17 17
     import Control.Monad.IO.Class
    
    18 18
     import Data.List (unsnoc)
    
    19 19
     import System.Directory
    
    20 20
     import System.FilePath
    
    21 21
     import System.IO.Error
    
    22
    -import System.Exit
    
    23 22
     
    
    24 23
     import GHC.Toolchain.Prelude
    
    25 24
     
    
    ... ... @@ -61,12 +60,7 @@ oneOf err = oneOf' [err]
    61 60
     -- | Like 'oneOf' but takes a multi-line error message if none of the checks
    
    62 61
     -- succeed.
    
    63 62
     oneOf' :: [String] -> [M b] -> M b
    
    64
    -oneOf' err = foldr (<|>) (throwEs err)
    
    65
    -
    
    66
    -isSuccess :: ExitCode -> Bool
    
    67
    -isSuccess = \case
    
    68
    -  ExitSuccess -> True
    
    69
    -  ExitFailure _ -> False
    
    63
    +oneOf' err as = asum $ as <> [throwEs err]
    
    70 64
     
    
    71 65
     lastLine :: String -> String
    
    72 66
     lastLine = maybe "" snd . unsnoc . lines