Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC

Commits:

27 changed files:

Changes:

  • .gitlab/ci.sh
    ... ... @@ -628,20 +628,6 @@ function install_bindist() {
    628 628
         *)
    
    629 629
           read -r -a args <<< "${INSTALL_CONFIGURE_ARGS:-}"
    
    630 630
     
    
    631
    -      if [[ "${CROSS_TARGET:-no_cross_target}" =~ "mingw" ]]; then
    
    632
    -          # We suppose that host target = build target.
    
    633
    -          # By the fact above it is clearly turning out which host value is
    
    634
    -          # for currently built compiler.
    
    635
    -          # The fix for #21970 will probably remove this if-branch.
    
    636
    -          local -r CROSS_HOST_GUESS=$($SHELL ./config.guess)
    
    637
    -          args+=( "--target=$CROSS_TARGET" "--host=$CROSS_HOST_GUESS" )
    
    638
    -
    
    639
    -      # FIXME: The bindist configure script shouldn't need to be reminded of
    
    640
    -      # the target platform. See #21970.
    
    641
    -      elif [ -n "${CROSS_TARGET:-}" ]; then
    
    642
    -          args+=( "--target=$CROSS_TARGET" "--host=$CROSS_TARGET" )
    
    643
    -      fi
    
    644
    -
    
    645 631
           run ${CONFIGURE_WRAPPER:-} ./configure \
    
    646 632
               --prefix="$instdir" \
    
    647 633
               "${args[@]+"${args[@]}"}" || fail "bindist configure failed"
    

  • .gitlab/generate-ci/gen_ci.hs
    ... ... @@ -1316,6 +1316,13 @@ cross_jobs = [
    1316 1316
               -- unexpected triple.
    
    1317 1317
             . setVariable "CFLAGS" cflags
    
    1318 1318
             . setVariable "CONF_CC_OPTS_STAGE2" cflags
    
    1319
    +          -- For bindists `$USER_CONF_CC_OPTS_STAGE2` is not automatically set
    
    1320
    +          -- to `$CONF_CC_OPTS_STAGE2`. But, we still have to deal with the hack
    
    1321
    +          -- mentioned in the previous comment.
    
    1322
    +          --
    
    1323
    +          -- TODO: It would be nice to get rid of this hack. This would probably
    
    1324
    +          -- involve setting the toolchain up in a different way.
    
    1325
    +        . setVariable "USER_CONF_CC_OPTS_STAGE2" cflags
    
    1319 1326
             ) where
    
    1320 1327
                 llvm_prefix = "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-"
    
    1321 1328
                 cflags = "-fuse-ld=" ++ llvm_prefix ++ "ld --rtlib=compiler-rt"
    

  • .gitlab/jobs.yaml
    ... ... @@ -331,6 +331,7 @@
    331 331
           "STRINGS": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strings",
    
    332 332
           "STRIP": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strip",
    
    333 333
           "TEST_ENV": "aarch64-linux-deb12-wine-int_native-cross_aarch64-unknown-mingw32-validate",
    
    334
    +      "USER_CONF_CC_OPTS_STAGE2": "-fuse-ld=/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld --rtlib=compiler-rt",
    
    334 335
           "WindresCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-windres"
    
    335 336
         }
    
    336 337
       },
    
    ... ... @@ -412,6 +413,7 @@
    412 413
           "STRINGS": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strings",
    
    413 414
           "STRIP": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strip",
    
    414 415
           "TEST_ENV": "aarch64-linux-deb12-wine-int_native-cross_aarch64-unknown-mingw32-validate+llvm",
    
    416
    +      "USER_CONF_CC_OPTS_STAGE2": "-fuse-ld=/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld --rtlib=compiler-rt",
    
    415 417
           "WindresCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-windres"
    
    416 418
         }
    
    417 419
       },
    
    ... ... @@ -1123,6 +1125,7 @@
    1123 1125
           "STRINGS": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strings",
    
    1124 1126
           "STRIP": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strip",
    
    1125 1127
           "TEST_ENV": "aarch64-linux-deb12-wine-int_native-cross_aarch64-unknown-mingw32-validate",
    
    1128
    +      "USER_CONF_CC_OPTS_STAGE2": "-fuse-ld=/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld --rtlib=compiler-rt",
    
    1126 1129
           "WindresCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-windres",
    
    1127 1130
           "XZ_OPT": "-9"
    
    1128 1131
         }
    
    ... ... @@ -1205,6 +1208,7 @@
    1205 1208
           "STRINGS": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strings",
    
    1206 1209
           "STRIP": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-strip",
    
    1207 1210
           "TEST_ENV": "aarch64-linux-deb12-wine-int_native-cross_aarch64-unknown-mingw32-validate+llvm",
    
    1211
    +      "USER_CONF_CC_OPTS_STAGE2": "-fuse-ld=/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld --rtlib=compiler-rt",
    
    1208 1212
           "WindresCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-windres",
    
    1209 1213
           "XZ_OPT": "-9"
    
    1210 1214
         }
    

  • compiler/GHC/Tc/Errors/Ppr.hs
    ... ... @@ -7710,12 +7710,8 @@ pprHsCtxt = \case
    7710 7710
       PatSigErrCtxt sig_ty res_ty ->
    
    7711 7711
         vcat [ hang (text "When checking that the pattern signature:")
    
    7712 7712
                   4 (ppr sig_ty)
    
    7713
    -         , nest 2 (hang (text "fits the type of its context:") 2 pp_res_ty) ]
    
    7714
    -    where
    
    7715
    -      -- Zonking will have turned Infer into Check
    
    7716
    -      pp_res_ty = case res_ty of
    
    7717
    -                    Check ty -> ppr ty
    
    7718
    -                    Infer ir -> text "OOPS" <+> ppr ir
    
    7713
    +         , nest 2 (hang (text "fits the type of its context:")
    
    7714
    +                      2 (ppr (getCheckExpType res_ty))) ]
    
    7719 7715
     
    
    7720 7716
       PatCtxt pat ->
    
    7721 7717
         hang (text "In the pattern:") 2 (ppr pat)
    
    ... ... @@ -7777,7 +7773,7 @@ pprHsCtxt = \case
    7777 7773
           full_herald = pprExpectedFunTyHerald herald
    
    7778 7774
                     <+> speakNOf n_vis_args_in_call (text "visible argument")
    
    7779 7775
                      -- What are "visible" arguments? See Note [Visibility and arity] in GHC.Types.Basic
    
    7780
    -  FunResCtxt fun n_val_args res_fun res_env n_fun n_env
    
    7776
    +  FunResCtxt fun n_val_args fun_res_ty env_ty
    
    7781 7777
         | -- Check for too few args
    
    7782 7778
           --  fun_tau = a -> b, res_tau = Int
    
    7783 7779
           n_fun > n_env
    
    ... ... @@ -7801,6 +7797,18 @@ pprHsCtxt = \case
    7801 7797
         -> empty
    
    7802 7798
           -- text "Debug" <+> vcat [ppr fun, ppr n_val_args, ppr res_fun, ppr res_env, ppr n_fun, ppr n_env]
    
    7803 7799
         where
    
    7800
    +      -- See Note [Splitting nested sigma types in mismatched
    
    7801
    +      --           function types]
    
    7802
    +      -- env_ty is an ExpRhoTy, but with simple subsumption it
    
    7803
    +      -- is not /deeply/ skolemised, so still use tcSplitNestedSigmaTys
    
    7804
    +
    
    7805
    +      (_,_,fun_tau)   = tcSplitNestedSigmaTys fun_res_ty
    
    7806
    +      (_, _, env_tau) = tcSplitNestedSigmaTys (getCheckExpType env_ty)
    
    7807
    +      (args_fun, res_fun) = tcSplitFunTys fun_tau
    
    7808
    +      (args_env, res_env) = tcSplitFunTys env_tau
    
    7809
    +      n_fun = length args_fun
    
    7810
    +      n_env = length args_env
    
    7811
    +
    
    7804 7812
           not_fun ty   -- ty is definitely not an arrow type,
    
    7805 7813
                        -- and cannot conceivably become one
    
    7806 7814
             = case tcSplitTyConApp_maybe ty of
    

  • compiler/GHC/Tc/Gen/Head.hs
    ... ... @@ -68,7 +68,6 @@ import GHC.Builtin.Names
    68 68
     import GHC.Driver.DynFlags
    
    69 69
     import GHC.Utils.Misc
    
    70 70
     import GHC.Utils.Outputable as Outputable
    
    71
    -import GHC.Utils.Panic
    
    72 71
     
    
    73 72
     import GHC.Data.Maybe
    
    74 73
     
    
    ... ... @@ -961,7 +960,8 @@ See Note [-fno-code mode].
    961 960
     *                                                                      *
    
    962 961
     ********************************************************************* -}
    
    963 962
     
    
    964
    -addFunResCtxt :: HsExpr GhcTc -> [HsExprArg p]
    
    963
    +addFunResCtxt :: HasDebugCallStack
    
    964
    +              => HsExpr GhcTc -> [HsExprArg p]
    
    965 965
                   -> TcType -> ExpRhoType
    
    966 966
                   -> TcM a -> TcM a
    
    967 967
     -- When we have a mis-match in the return type of a function
    
    ... ... @@ -969,33 +969,10 @@ addFunResCtxt :: HsExpr GhcTc -> [HsExprArg p]
    969 969
     -- But not in generated code, where we don't want
    
    970 970
     -- to mention internal (rebindable syntax) function names
    
    971 971
     addFunResCtxt fun args fun_res_ty env_ty thing_inside
    
    972
    -  = do { env_tv  <- newFlexiTyVarTy liftedTypeKind
    
    973
    -       ; dumping <- doptM Opt_D_dump_tc_trace
    
    974
    -       ; msg <- mk_msg dumping env_tv
    
    975
    -       ; addErrCtxt msg thing_inside }
    
    972
    +  = addErrCtxt (FunResCtxt fun (count isValArg args) fun_res_ty env_ty) $
    
    973
    +    thing_inside
    
    976 974
           -- NB: use a landmark error context, so that an empty context
    
    977 975
           -- doesn't suppress some more useful context
    
    978
    -  where
    
    979
    -    mk_msg dumping env_tv
    
    980
    -      = do { mb_env_ty <- readExpType_maybe env_ty
    
    981
    -                     -- by the time the message is rendered, the ExpType
    
    982
    -                     -- will be filled in (except if we're debugging)
    
    983
    -           ; env'     <- case mb_env_ty of
    
    984
    -                           Just env_ty -> return env_ty
    
    985
    -                           Nothing     -> do { massert dumping; return env_tv }
    
    986
    -           ; let -- See Note [Splitting nested sigma types in mismatched
    
    987
    -                 --           function types]
    
    988
    -                 (_, _, fun_tau) = tcSplitNestedSigmaTys fun_res_ty
    
    989
    -                 (_, _, env_tau) = tcSplitNestedSigmaTys env'
    
    990
    -                     -- env_ty is an ExpRhoTy, but with simple subsumption it
    
    991
    -                     -- is not deeply skolemised, so still use tcSplitNestedSigmaTys
    
    992
    -                 (args_fun, res_fun) = tcSplitFunTys fun_tau
    
    993
    -                 (args_env, res_env) = tcSplitFunTys env_tau
    
    994
    -                 info =
    
    995
    -                  FunResCtxt fun (count isValArg args) res_fun res_env
    
    996
    -                    (length args_fun) (length args_env)
    
    997
    -           ; return info }
    
    998
    -
    
    999 976
     
    
    1000 977
     {-
    
    1001 978
     Note [Splitting nested sigma types in mismatched function types]
    

  • compiler/GHC/Tc/Types/ErrCtxt.hs
    ... ... @@ -251,7 +251,10 @@ data HsCtxt
    251 251
       -- | In the instance type signature of a class method.
    
    252 252
       | MethSigCtxt !Name !TcType !TcType
    
    253 253
       -- | In a pattern type signature.
    
    254
    +
    
    254 255
       | PatSigErrCtxt !TcType !ExpType
    
    256
    +     -- ExpType: see Note [ExpType in HsCtxt]
    
    257
    +
    
    255 258
       -- | In a pattern.
    
    256 259
       | PatCtxt !(Pat GhcRn)
    
    257 260
       -- | In a pattern synonym declaration.
    
    ... ... @@ -268,7 +271,10 @@ data HsCtxt
    268 271
       -- | In a function call.
    
    269 272
       | FunTysCtxt !ExpectedFunTyCtxt !Type !Int !Int
    
    270 273
       -- | In the result of a function call.
    
    271
    -  | FunResCtxt !(HsExpr GhcTc) !Int !Type !Type !Int !Int
    
    274
    +
    
    275
    +  | FunResCtxt !(HsExpr GhcTc) !Int !TcType !ExpType
    
    276
    +     -- ExpType: see Note [ExpType in HsCtxt]
    
    277
    +
    
    272 278
       -- | In the declaration of a type constructor.
    
    273 279
       | TyConDeclCtxt !Name !(TyConFlavour TyCon)
    
    274 280
       -- | In a type or data family instance (or default instance).
    
    ... ... @@ -377,3 +383,14 @@ isHsCtxtLandmark (DerivBindCtxt{}) = True
    377 383
     isHsCtxtLandmark (FunResCtxt{}) = True
    
    378 384
     isHsCtxtLandmark (VDQWarningCtxt{}) = True
    
    379 385
     isHsCtxtLandmark _ = False
    
    386
    +
    
    387
    +{- Note [ExpType in HsCtxt]
    
    388
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    389
    +A couple of HsCtxt constructors have ExpTypes in them.  When zonking the
    
    390
    +Infer{} case we read the hole, which should be filled in by now, and zonk
    
    391
    +that type.  Now we want to put it back: we use (Check ty') for this, so that
    
    392
    +clients of a zonked HsCtxt don't need to be monadic.
    
    393
    +
    
    394
    +Result: after zonking, these ExpTypes are always (Check ty).  It woudl be nice
    
    395
    +to guarantee this statically, but it's hard to do so.
    
    396
    +-}

  • compiler/GHC/Tc/Utils/TcType.hs
    ... ... @@ -28,7 +28,7 @@ module GHC.Tc.Utils.TcType (
    28 28
       ExpType(..), ExpKind, InferResult(..), InferInstFlag(..), InferFRRFlag(..),
    
    29 29
       ExpTypeFRR, ExpSigmaType, ExpSigmaTypeFRR,
    
    30 30
       ExpRhoType, ExpRhoTypeFRR,
    
    31
    -  mkCheckExpType,
    
    31
    +  mkCheckExpType, getCheckExpType,
    
    32 32
       checkingExpType_maybe, checkingExpType,
    
    33 33
     
    
    34 34
       ExpPatType(..), mkCheckExpFunPatTy, mkInvisExpPatType,
    
    ... ... @@ -440,11 +440,12 @@ data InferInstFlag -- Specifies whether the inference should return an uninstan
    440 440
     
    
    441 441
       | IIF_ShallowRho  -- Trying to infer a shallow RhoType (no foralls or => at the top)
    
    442 442
                         -- Top-instantiate (only, regardless of DeepSubsumption) before filling the hole
    
    443
    -                    -- Typically used when inferring the type of an expression
    
    443
    +                    -- Used only for view patterns; see Note [View patterns and polymorphism]
    
    444 444
     
    
    445 445
       | IIF_DeepRho     -- Trying to infer a possibly-deep RhoType (depending on DeepSubsumption)
    
    446 446
                         -- If DeepSubsumption is off, same as IIF_ShallowRho
    
    447 447
                         -- If DeepSubsumption is on, instantiate deeply before filling the hole
    
    448
    +                    -- Typically used when inferring the type of an expression
    
    448 449
     
    
    449 450
     type ExpSigmaType = ExpType
    
    450 451
     type ExpRhoType   = ExpType
    
    ... ... @@ -490,6 +491,12 @@ instance Outputable InferResult where
    490 491
     mkCheckExpType :: TcType -> ExpType
    
    491 492
     mkCheckExpType = Check
    
    492 493
     
    
    494
    +getCheckExpType :: HasDebugCallStack => ExpType -> TcType
    
    495
    +-- Expect a (Check ty).
    
    496
    +-- See Note [ExpType in HsCtxt] in GHC.Tc.Types.ErrCtxt
    
    497
    +getCheckExpType (Check ty) = ty
    
    498
    +getCheckExpType (Infer ir) = pprPanic "getCheckExpType" (ppr ir)
    
    499
    +
    
    493 500
     -- | Returns the expected type when in checking mode.
    
    494 501
     checkingExpType_maybe :: ExpType -> Maybe TcType
    
    495 502
     checkingExpType_maybe (Check ty) = Just ty
    

  • compiler/GHC/Tc/Zonk/TcType.hs
    ... ... @@ -818,19 +818,26 @@ zonkTidyHsCtxt env e@(FunAppCtxt{}) = return (env, e)
    818 818
     zonkTidyHsCtxt env (FunTysCtxt ctxt ty i1 i2) = do
    
    819 819
       (env', ty') <- zonkTidyTcType env ty
    
    820 820
       return $ (env', FunTysCtxt ctxt ty' i1 i2)
    
    821
    -zonkTidyHsCtxt env (FunResCtxt e i1 ty1 ty2 i2 i3) = do
    
    822
    -  (env', ty1') <- zonkTidyTcType env ty1
    
    823
    -  (env', ty2') <- zonkTidyTcType env' ty2
    
    824
    -  return $ (env', FunResCtxt e i1 ty1' ty2' i2 i3)
    
    821
    +zonkTidyHsCtxt env (FunResCtxt e n ty1 env_ty) = do
    
    822
    +  (env', ty1')    <- zonkTidyTcType env ty1
    
    823
    +  (env', env_ty') <- zonkExpType env' env_ty
    
    824
    +  return $ (env', FunResCtxt e n ty1' env_ty')
    
    825 825
     zonkTidyHsCtxt env (PatSigErrCtxt sig_ty res_ty) = do
    
    826 826
       (env', sig_ty') <- zonkTidyTcType env sig_ty
    
    827
    -  (env', res_ty') <-
    
    828
    -    case res_ty of
    
    829
    -      Check ty -> zonkTidyTcType env' ty
    
    830
    -      Infer (IR {ir_ref = ref}) -> do -- inlining readExpTyp_maybe to avoid module dep loops
    
    831
    -        mb_ty <- liftIO $ readIORef ref
    
    832
    -        case mb_ty of
    
    833
    -          Nothing -> error "zonkTidyHsCtxt PatSigErrCtxt"
    
    834
    -          Just ty -> zonkTidyTcType env' ty
    
    835
    -  return (env', PatSigErrCtxt sig_ty' (Check res_ty'))
    
    827
    +  (env', res_ty') <- zonkExpType env' res_ty
    
    828
    +  return (env', PatSigErrCtxt sig_ty' res_ty')
    
    836 829
     zonkTidyHsCtxt env p = return (env, p)
    
    830
    +
    
    831
    +zonkExpType :: TidyEnv -> ExpType -> ZonkM (TidyEnv, ExpType)
    
    832
    +-- Zonk Infer{} to Check.  The hole should have been filled in by now
    
    833
    +zonkExpType env (Check ty)
    
    834
    +  = do { (env', ty') <- zonkTidyTcType env ty
    
    835
    +       ; return (env', Check ty') }
    
    836
    +zonkExpType env (Infer ir@(IR { ir_ref = ref }))
    
    837
    +  = do { -- inlining readExpTyp_maybe to avoid module dep loops
    
    838
    +       ; mb_ty <- liftIO $ readIORef ref
    
    839
    +       ; case mb_ty of
    
    840
    +            Nothing -> pprPanic "zonkTidyHsCtxt PatSigErrCtxt" (ppr ir)
    
    841
    +            Just ty -> do { (env', ty') <- zonkTidyTcType env ty
    
    842
    +                          ; return (env', Check ty') } }
    
    843
    +

  • configure.ac
    ... ... @@ -255,6 +255,7 @@ if test "${WithGhc}" != ""
    255 255
     then
    
    256 256
             bootstrap_host=`"${WithGhc}" --info | grep '^ ,("Host platform"' | sed -e 's/.*,"//' -e 's/")//' | tr -d '\r'`
    
    257 257
             bootstrap_target=`"${WithGhc}" --info | grep '^ ,("Target platform"' | sed -e 's/.*,"//' -e 's/")//' | tr -d '\r'`
    
    258
    +	      bootstrap_build="$bootstrap_host"
    
    258 259
             if test "$bootstrap_host" != "$bootstrap_target"
    
    259 260
             then
    
    260 261
                     echo "Bootstrapping GHC is a cross compiler. This probably isn't going to work"
    
    ... ... @@ -394,8 +395,33 @@ then
    394 395
     else
    
    395 396
       TargetPlatformFull="${target_alias}"
    
    396 397
     fi
    
    398
    +
    
    399
    +if test -z "${build_alias}"
    
    400
    +then
    
    401
    +  # --target wasn't given; use result from AC_CANONICAL_TARGET
    
    402
    +  BuildPlatformFull="${build}"
    
    403
    +else
    
    404
    +  BuildPlatformFull="${build_alias}"
    
    405
    +fi
    
    406
    +if test -z "${host_alias}"
    
    407
    +then
    
    408
    +  # --target wasn't given; use result from AC_CANONICAL_TARGET
    
    409
    +  HostPlatformFull="${host}"
    
    410
    +else
    
    411
    +  HostPlatformFull="${host_alias}"
    
    412
    +fi
    
    413
    +if test "$CrossCompiling" = "YES"
    
    414
    +then
    
    415
    +  # Use value passed by user from --target=
    
    416
    +  CrossCompilePrefix="${TargetPlatformFull}-"
    
    417
    +else
    
    418
    +  CrossCompilePrefix=""
    
    419
    +fi
    
    420
    +
    
    397 421
     AC_SUBST(CrossCompiling)
    
    398 422
     AC_SUBST(TargetPlatformFull)
    
    423
    +AC_SUBST(BuildPlatformFull)
    
    424
    +AC_SUBST(HostPlatformFull)
    
    399 425
     
    
    400 426
     dnl ** Which gcc to use?
    
    401 427
     dnl --------------------------------------------------------------
    

  • distrib/configure.ac.in
    ... ... @@ -15,7 +15,18 @@ dnl--------------------------------------------------------------------
    15 15
     dnl * Deal with arguments telling us gmp is somewhere odd
    
    16 16
     dnl--------------------------------------------------------------------
    
    17 17
     
    
    18
    +build_alias=@BuildPlatformFull@
    
    19
    +host_alias=@HostPlatformFull@
    
    20
    +target_alias=@TargetPlatformFull@
    
    21
    +
    
    22
    +dnl this makes sure `./configure --target=<cross-compile-target>`
    
    23
    +dnl works as expected, since we're slightly modifying how Autoconf
    
    24
    +dnl interprets build/host/target and how this interacts with $CC tests
    
    25
    +test -n "$target_alias" && ac_tool_prefix=$target_alias-
    
    26
    +
    
    18 27
     dnl Various things from the source distribution configure
    
    28
    +bootstrap_build=@BuildPlatform@
    
    29
    +bootstrap_host=@HostPlatform@
    
    19 30
     bootstrap_target=@TargetPlatform@
    
    20 31
     
    
    21 32
     bootstrap_llvm_target=@LlvmTarget@
    

  • hadrian/cfg/system.config.in
    ... ... @@ -50,6 +50,9 @@ use-ghc-toolchain = @EnableGhcToolchain@
    50 50
     #     And we can reconstruct the platform info using targetPlatformTriple
    
    51 51
     # Q: What is TargetPlatformFull?
    
    52 52
     target-platform-full  = @TargetPlatformFull@
    
    53
    +build-platform-full   = @BuildPlatformFull@
    
    54
    +host-platform-full    = @HostPlatformFull@
    
    55
    +
    
    53 56
     
    
    54 57
     cross-compiling       = @CrossCompiling@
    
    55 58
     
    

  • hadrian/src/Oracles/Setting.hs
    ... ... @@ -69,6 +69,8 @@ data Setting = CursesIncludeDir
    69 69
                  | ProjectPatchLevel2
    
    70 70
                  | SystemGhc
    
    71 71
                  | TargetPlatformFull
    
    72
    +             | BuildPlatformFull
    
    73
    +             | HostPlatformFull
    
    72 74
                  | BourneShell
    
    73 75
                  | EmsdkVersion
    
    74 76
     
    
    ... ... @@ -107,6 +109,8 @@ setting key = lookupSystemConfig $ case key of
    107 109
         ProjectPatchLevel2 -> "project-patch-level2"
    
    108 110
         SystemGhc          -> "system-ghc"
    
    109 111
         TargetPlatformFull -> "target-platform-full"
    
    112
    +    BuildPlatformFull  -> "build-platform-full"
    
    113
    +    HostPlatformFull   -> "host-platform-full"
    
    110 114
         BourneShell        -> "bourne-shell"
    
    111 115
         EmsdkVersion       -> "emsdk-version"
    
    112 116
     
    

  • hadrian/src/Rules/Generate.hs
    ... ... @@ -424,6 +424,8 @@ bindistRules = do
    424 424
         , interpolateVar "TablesNextToCode" $ yesNo <$> getTarget tgtTablesNextToCode
    
    425 425
         , interpolateVar "TargetHasLibm" $ yesNo <$> getTarget tgtHasLibm
    
    426 426
         , interpolateVar "TargetPlatform" $ getTarget targetPlatformTriple
    
    427
    +    , interpolateVar "BuildPlatform"  $ interp $ queryBuild targetPlatformTriple
    
    428
    +    , interpolateVar "HostPlatform"   $ interp $ queryHost targetPlatformTriple
    
    427 429
         , interpolateVar "TargetWordBigEndian" $ getTarget isBigEndian
    
    428 430
         , interpolateVar "TargetWordSize" $ getTarget wordSize
    
    429 431
         , interpolateVar "Unregisterised" $ yesNo <$> getTarget tgtUnregisterised
    
    ... ... @@ -431,6 +433,9 @@ bindistRules = do
    431 433
         , interpolateVar "UseLibffiForAdjustors" $ yesNo <$> getTarget tgtUseLibffiForAdjustors
    
    432 434
         , interpolateVar "GhcWithSMP" $ yesNo <$> targetSupportsSMP
    
    433 435
         , interpolateVar "BaseUnitId" $ pkgUnitId Stage1 base
    
    436
    +    , interpolateVar "TargetPlatformFull" (setting TargetPlatformFull)
    
    437
    +    , interpolateVar "BuildPlatformFull" (setting BuildPlatformFull)
    
    438
    +    , interpolateVar "HostPlatformFull"  (setting HostPlatformFull)
    
    434 439
         ]
    
    435 440
       where
    
    436 441
         interp = interpretInContext (semiEmptyTarget Stage2)
    

  • hadrian/src/Settings/Default.hs
    ... ... @@ -122,7 +122,11 @@ stage0Packages = do
    122 122
               -- for upper stages. As we only use stage0 to build upper stages,
    
    123 123
               -- this should be fine.
    
    124 124
               ++ [ terminfo | not windowsHost, not cross ]
    
    125
    -          ++ [ timeout  | windowsHost                                ]
    
    125
    +          ++ [ timeout  | windowsHost ]
    
    126
    +          -- Due to some weird logic, we need ghcToolchainBin in Stage0 and
    
    127
    +          -- Stage1 packages if we're cross compiling. "Stage2 cross-compilers"
    
    128
    +          -- will solve this.
    
    129
    +          ++ [ ghcToolchainBin | cross ]
    
    126 130
     
    
    127 131
     -- | Packages built in 'Stage1' by default. You can change this in "UserSettings".
    
    128 132
     stage1Packages :: Action [Package]
    
    ... ... @@ -181,12 +185,12 @@ stage1Packages = do
    181 185
             , transformers
    
    182 186
             , unlit
    
    183 187
             , xhtml
    
    188
    +        , ghcToolchainBin
    
    184 189
             , if winTarget then win32 else unix
    
    185 190
             ]
    
    186 191
           , when (not cross)
    
    187 192
             [ hpcBin
    
    188 193
             , runGhc
    
    189
    -        , ghcToolchainBin
    
    190 194
             ]
    
    191 195
           , when (winTarget && not cross)
    
    192 196
             [ -- See Note [Hadrian's ghci-wrapper package]
    

  • libraries/base/changelog.md
    ... ... @@ -28,6 +28,7 @@
    28 28
       * Hide implementation details when throwing exceptions in throw and throwSTM. ([CLC proposal #387](https://github.com/haskell/core-libraries-committee/issues/387))
    
    29 29
       * Change `hIsReadable` and `hIsWritable` such that they always throw a respective exception when encountering a closed or semi-closed handle, not just in the case of a file handle. ([CLC proposal #371](github.com/haskell/core-libraries-committee/issues/371))
    
    30 30
       * Annotate `onException` continuation with `WhileHandling`. ([CLC Proposal #397](https://github.com/haskell/core-libraries-committee/issues/397))
    
    31
    +  * Improve error message for `Data.Char.chr`. ([CLC Proposal #384](https://github.com/haskell/core-libraries-committee/issues/384))
    
    31 32
     
    
    32 33
     ## 4.22.0.0 *TBA*
    
    33 34
       * Shipped with GHC 9.14.1
    

  • libraries/base/tests/enum01.stdout
    ... ... @@ -81,7 +81,7 @@ Testing Enum Char:
    81 81
         pred (maxBound::Char) = '\1114110'
    
    82 82
         pred (minBound::Char) = error "Prelude.Enum.Char.pred: bad argument"
    
    83 83
         (map (toEnum::Int->Char) [123,ord (minBound::Char), ord(maxBound::Char)]) = "{\NUL\1114111"
    
    84
    -    (toEnum::Int->Char) (minBound::Int) = error "Prelude.chr: bad argument: (-2147483648)"
    
    84
    +    (toEnum::Int->Char) (minBound::Int) = error "Data.Char.chr: argument outside Unicode range: 0..1114111: (-2147483648)"
    
    85 85
         (map fromEnum ['X',minBound,maxBound]) = [88,0,1114111]
    
    86 86
         (take 7 ['\NUL' .. ]) = "\NUL\SOH\STX\ETX\EOT\ENQ\ACK"
    
    87 87
         (take 7 ['\250' .. ]) = "\250\251\252\253\254\255\256"
    

  • libraries/base/tests/enum01.stdout-alpha-dec-osf3
    ... ... @@ -65,7 +65,7 @@ Testing Enum Char:
    65 65
         pred (maxBound::Char) = '\1114110'
    
    66 66
         pred (minBound::Char) = error "Prelude.Enum.Char.pred: bad argument"
    
    67 67
         (map (toEnum::Int->Char) [123,ord (minBound::Char), ord(maxBound::Char)]) = "{\NUL\1114111"
    
    68
    -    (toEnum::Int->Char) (minBound::Int) = error "Prelude.chr: bad argument"
    
    68
    +    (toEnum::Int->Char) (minBound::Int) = error "Data.Char.chr: argument outside Unicode range: 0..1114111:"
    
    69 69
         (map fromEnum ['X',minBound,maxBound]) = [88,0,1114111]
    
    70 70
         (take 7 ['\NUL' .. ]) = "\NUL\SOH\STX\ETX\EOT\ENQ\ACK"
    
    71 71
         (take 7 ['\250' .. ]) = "\250\251\252\253\254\255\256"
    

  • libraries/base/tests/enum01.stdout-ws-64
    ... ... @@ -81,7 +81,7 @@ Testing Enum Char:
    81 81
         pred (maxBound::Char) = '\1114110'
    
    82 82
         pred (minBound::Char) = error "Prelude.Enum.Char.pred: bad argument"
    
    83 83
         (map (toEnum::Int->Char) [123,ord (minBound::Char), ord(maxBound::Char)]) = "{\NUL\1114111"
    
    84
    -    (toEnum::Int->Char) (minBound::Int) = error "Prelude.chr: bad argument: (-9223372036854775808)"
    
    84
    +    (toEnum::Int->Char) (minBound::Int) = error "Data.Char.chr: argument outside Unicode range: 0..1114111: (-9223372036854775808)"
    
    85 85
         (map fromEnum ['X',minBound,maxBound]) = [88,0,1114111]
    
    86 86
         (take 7 ['\NUL' .. ]) = "\NUL\SOH\STX\ETX\EOT\ENQ\ACK"
    
    87 87
         (take 7 ['\250' .. ]) = "\250\251\252\253\254\255\256"
    

  • libraries/ghc-internal/src/GHC/Internal/Char.hs
    ... ... @@ -12,7 +12,7 @@ module GHC.Internal.Char
    12 12
     
    
    13 13
     import GHC.Internal.Classes (eqChar, neChar)
    
    14 14
     import GHC.Internal.Base (otherwise, (++))
    
    15
    -import GHC.Internal.Err (errorWithoutStackTrace)
    
    15
    +import GHC.Internal.Err (error)
    
    16 16
     import GHC.Internal.Show
    
    17 17
     import GHC.Internal.Prim (chr#, int2Word#, leWord#, Int#, Char#)
    
    18 18
     import GHC.Internal.Types (Char(..), Int(..), isTrue#)
    
    ... ... @@ -29,4 +29,7 @@ safe_chr# i#
    29 29
     
    
    30 30
     {-# NOINLINE chr_error #-}
    
    31 31
     chr_error :: Int# -> Char#
    
    32
    -chr_error i# = errorWithoutStackTrace ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) (I# i#) "")
    32
    +chr_error i# = error ("Data.Char.chr: argument outside Unicode range: 0..1114111: " ++ showSignedInt (I# 9#) (I# i#) "")
    
    33
    +-- It's not really "Data.Char", but we assume that
    
    34
    +-- the majority of users will import it from "base:Data.Char"
    
    35
    +-- and not from "ghc-internal:GHC.Internal.Char".

  • m4/fptools_set_platform_vars.m4
    ... ... @@ -77,9 +77,9 @@ dnl fi
    77 77
     # compiler's target platform.
    
    78 78
     AC_DEFUN([FPTOOLS_OVERRIDE_PLATFORM_FROM_BOOTSTRAP],
    
    79 79
     [
    
    80
    -    if test "$bootstrap_target" != ""
    
    80
    +    if test "$bootstrap_$1" != ""
    
    81 81
         then
    
    82
    -        $1=$bootstrap_target
    
    82
    +        $1=$bootstrap_$1
    
    83 83
             echo "$1 platform inferred as: [$]$1"
    
    84 84
         else
    
    85 85
             echo "Can't work out $1 platform"
    

  • m4/ghc_toolchain.m4
    ... ... @@ -136,8 +136,10 @@ dnl and that we must compile ghc-toolchain before invoking it
    136 136
     AC_DEFUN([FIND_GHC_TOOLCHAIN_BIN],[
    
    137 137
         case "$1" in
    
    138 138
             YES)
    
    139
    -            # We're configuring the bindist, and the binary is already available
    
    140
    -            GHC_TOOLCHAIN_BIN="bin/ghc-toolchain-bin"
    
    139
    +            # We're configuring the bindist, and the binary is already available.
    
    140
    +            # For cross-compilation bindists, Hadrian names the binary with the
    
    141
    +            # cross-compile prefix (e.g. riscv64-linux-gnu-ghc-toolchain-bin).
    
    142
    +            GHC_TOOLCHAIN_BIN="bin/${CrossCompilePrefix}ghc-toolchain-bin"
    
    141 143
                 ;;
    
    142 144
             NO)
    
    143 145
                 # We're in the source tree, so compile ghc-toolchain
    

  • rts/posix/FdWakeup.c
    1
    +/* -----------------------------------------------------------------------------
    
    2
    + *
    
    3
    + * (c) The GHC Team 2025
    
    4
    + *
    
    5
    + * Utilities for a simple fd-based cross-thread wakeup mechanism.
    
    6
    + *
    
    7
    + * This is used to provide a mechanism to wake a thread when it is blocked
    
    8
    + * waiting on fds and timeouts. The mechanism works by including the read end
    
    9
    + * fd into the set of fds the thread waits on, and when a wake up is needed,
    
    10
    + * the write end fd is used.
    
    11
    + *
    
    12
    + * This is implemented using either eventfd() or pipe().
    
    13
    + *
    
    14
    + * Linux 2.6.22+ and FreeBSD 13+ support eventfd. It is a single fd with a
    
    15
    + * 64bit counter. It uses fewer resources than a pipe (less memory and one
    
    16
    + * rather than two fds), and is a tad faster (on the order of 5-10%). Using
    
    17
    + * write() adds to the counter, while read() reads and resets it. Thus
    
    18
    + * multiple writes are combined automatically into a single corresponding
    
    19
    + * read.
    
    20
    + *
    
    21
    + * Otherwise we use a classic unix pipe.
    
    22
    + *
    
    23
    + * In both implementations, multiple sendFdWakeup notifcations (without
    
    24
    + * interleaved collectFdWakeup) are combined to a single notification. This
    
    25
    + * is automatic given the semantics of eventfd, while for pipe we implement
    
    26
    + * it explicitly by draining the pipe in collectFdWakeup.
    
    27
    + *
    
    28
    + * -------------------------------------------------------------------------*/
    
    29
    +
    
    30
    +#include "rts/PosixSource.h"
    
    31
    +#include "Rts.h"
    
    32
    +
    
    33
    +#include "FdWakeup.h"
    
    34
    +
    
    35
    +#include <fcntl.h>
    
    36
    +#include <unistd.h>
    
    37
    +
    
    38
    +#ifdef HAVE_SYS_EVENTFD_H
    
    39
    +#include <sys/eventfd.h>
    
    40
    +#endif
    
    41
    +
    
    42
    +#if !defined(HAVE_EVENTFD) \
    
    43
    + || (defined(HAVE_EVENTFD) && !(defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)))
    
    44
    +static void fcntl_CLOEXEC_NONBLOCK(int fd)
    
    45
    +{
    
    46
    +    int res1 = fcntl(fd, F_SETFD, FD_CLOEXEC);
    
    47
    +    int res2 = fcntl(fd, F_SETFL, O_NONBLOCK);
    
    48
    +    if (RTS_UNLIKELY(res1 < 0 || res2 < 0)) {
    
    49
    +        sysErrorBelch("newFdWakeup fcntl()");
    
    50
    +        stg_exit(EXIT_FAILURE);
    
    51
    +    }
    
    52
    +}
    
    53
    +#endif
    
    54
    +
    
    55
    +void newFdWakeup(int *wakeup_fd_r, int *wakeup_fd_w)
    
    56
    +{
    
    57
    +#if defined(HAVE_EVENTFD)
    
    58
    +    int wakeup_fd;
    
    59
    +#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
    
    60
    +    wakeup_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
    
    61
    +#else
    
    62
    +    wakeup_fd = eventfd(0, 0);
    
    63
    +    if (wakeup_fd >= 0) fcntl_CLOEXEC_NONBLOCK(wakeup_fd);
    
    64
    +#endif
    
    65
    +    if (RTS_UNLIKELY(wakeup_fd < 0)) {
    
    66
    +        sysErrorBelch("newFdWakeup eventfd()");
    
    67
    +        stg_exit(EXIT_FAILURE);
    
    68
    +    }
    
    69
    +    /* eventfd uses the same fd for each end */
    
    70
    +    *wakeup_fd_r = wakeup_fd;
    
    71
    +    *wakeup_fd_w = wakeup_fd;
    
    72
    +#else
    
    73
    +    int pipefd[2];
    
    74
    +    int res;
    
    75
    +    res = pipe(pipefd);
    
    76
    +    if (RTS_UNLIKELY(res < 0)) {
    
    77
    +        sysErrorBelch("newFdWakeup pipe");
    
    78
    +        stg_exit(EXIT_FAILURE);
    
    79
    +    }
    
    80
    +    fcntl_CLOEXEC_NONBLOCK(pipefd[0]);
    
    81
    +    fcntl_CLOEXEC_NONBLOCK(pipefd[1]);
    
    82
    +    *wakeup_fd_r = pipefd[0]; /* read end */
    
    83
    +    *wakeup_fd_w = pipefd[1]; /* write end */
    
    84
    +#endif
    
    85
    +}
    
    86
    +
    
    87
    +void closeFdWakeup(int wakeup_fd_r, int wakeup_fd_w)
    
    88
    +{
    
    89
    +#if defined(HAVE_EVENTFD)
    
    90
    +    ASSERT(wakeup_fd_r == wakeup_fd_w);
    
    91
    +    close(wakeup_fd_r);
    
    92
    +#else
    
    93
    +    ASSERT(wakeup_fd_r != wakeup_fd_w);
    
    94
    +    close(wakeup_fd_r);
    
    95
    +    close(wakeup_fd_w);
    
    96
    +#endif
    
    97
    +}
    
    98
    +
    
    99
    +/* This is safe to use from a signal handler. Using write() to a pipe
    
    100
    + * or eventfd is fine. */
    
    101
    +void sendFdWakeup(int wakeup_fd_w)
    
    102
    +{
    
    103
    +    int res;
    
    104
    +#if defined(HAVE_EVENTFD)
    
    105
    +    uint64_t val = 1;
    
    106
    +    res = write(wakeup_fd_w, &val, 8);
    
    107
    +#else
    
    108
    +    unsigned char buf = 1;
    
    109
    +    res = write(wakeup_fd_w, &buf, 1);
    
    110
    +#endif
    
    111
    +    if (RTS_UNLIKELY(res < 0)) {
    
    112
    +        /* Unlikely the pipe buffer will fill, but it would not be an error. */
    
    113
    +        if (errno == EAGAIN) return;
    
    114
    +        sysErrorBelch("sendFdWakeup write");
    
    115
    +        stg_exit(EXIT_FAILURE);
    
    116
    +    }
    
    117
    +}
    
    118
    +
    
    119
    +void collectFdWakeup(int wakeup_fd_r)
    
    120
    +{
    
    121
    +    int res;
    
    122
    +#if defined(HAVE_EVENTFD)
    
    123
    +    uint64_t buf;
    
    124
    +    /* eventfd combines events into one counter, so a single read is enough */
    
    125
    +    res = read(wakeup_fd_r, &buf, 8);
    
    126
    +#else
    
    127
    +    /* Drain the pipe buffer. Multiple wakeup notifications could
    
    128
    +     * have been sent before we have a chance to collect them.
    
    129
    +     */
    
    130
    +    uint64_t buf;
    
    131
    +    do {
    
    132
    +        res = read(wakeup_fd_r, &buf, 8);
    
    133
    +    } while (res == 8);
    
    134
    +#endif
    
    135
    +    if (RTS_UNLIKELY(res < 0)) {
    
    136
    +        /* After the first pipe read, it could block */
    
    137
    +        if (errno == EAGAIN) return;
    
    138
    +        sysErrorBelch("collectFdWakeup read");
    
    139
    +        stg_exit(EXIT_FAILURE);
    
    140
    +    }
    
    141
    +}

  • rts/posix/FdWakeup.h
    1
    +/* -----------------------------------------------------------------------------
    
    2
    + *
    
    3
    + * (c) The GHC Team 2025
    
    4
    + *
    
    5
    + * Utilities for a simple fd-based cross-thread wakeup mechanism.
    
    6
    + *
    
    7
    + * It provides a mechanism for a thread that block on fds to add a simple
    
    8
    + * wakeup/notification feature.
    
    9
    + *
    
    10
    + * Start with newFdWakeup, and pass the fd_r to the thread that needs the
    
    11
    + * wakeup feature. The thread that needs to be woken should include the fd_r
    
    12
    + * into the set of fds that the thread waits on (e.g. using poll or similar).
    
    13
    + * If this fd becomes ready for read, the thread must call collectFdWakeup,
    
    14
    + * and when a wake up is needed, the write end fd is used. In any other thread
    
    15
    + * (or in a signal handler), call sendFdWakeup(fd_w) to (asynchronously) cause
    
    16
    + * the wakeup.
    
    17
    + *
    
    18
    + * There is no message payload. Multiple wakeups may be combined (if they're
    
    19
    + * sent multiple times before the notified thread can wake and call
    
    20
    + * collectFdWakeup).
    
    21
    + *
    
    22
    + * The implementation uses pipe() or eventfd() on supported OSs.
    
    23
    + *
    
    24
    + * Prototypes for functions in FdWakeup.c
    
    25
    + *
    
    26
    + * -------------------------------------------------------------------------*/
    
    27
    +
    
    28
    +#pragma once
    
    29
    +
    
    30
    +#include "BeginPrivate.h"
    
    31
    +
    
    32
    +void newFdWakeup(int *fd_r, int *fd_w);
    
    33
    +void closeFdWakeup(int fd_r, int fd_w);
    
    34
    +
    
    35
    +/* This is safe to use from a signal handler */
    
    36
    +void sendFdWakeup(int fd_w);
    
    37
    +void collectFdWakeup(int fd_r);
    
    38
    +
    
    39
    +#include "EndPrivate.h"
    
    40
    +

  • rts/posix/Ticker.c
    1 1
     /* -----------------------------------------------------------------------------
    
    2 2
      *
    
    3
    - * (c) The GHC Team, 1995-2007
    
    3
    + * (c) The GHC Team, 1995-2026
    
    4 4
      *
    
    5
    - * Posix implementation(s) of the interval timer for profiling and pre-emptive
    
    6
    - * scheduling.
    
    5
    + * The posix implementation of the interval timer, used for pre-emptive
    
    6
    + * scheduling of Haskell threads, and for sample based profiling.
    
    7
    + *
    
    8
    + * This file defines the "ticker": the platform-specific service to install and
    
    9
    + * run the timer. See rts/Timer.c for the platform-dependent view of interval
    
    10
    + * timing.
    
    7 11
      *
    
    8 12
      * ---------------------------------------------------------------------------*/
    
    9 13
     
    
    10
    -/* The interval timer is used for profiling and for context switching.
    
    11
    - * This file defines the platform-specific services to install and run the
    
    12
    - * timers, and we call this the ticker. See rts/Timer.c for the
    
    13
    - * platform-dependent view of interval timing.
    
    14
    +/* This implementation uses a posix thread which repeatedly blocks on a timeout
    
    15
    + * using either the ppoll() or select() API. This lets it also block on a file
    
    16
    + * descriptor for early wakeup.
    
    17
    + *
    
    18
    + * The design uses a simple relative time delay with no catchup. That is, time
    
    19
    + * spent by the ticker thread itself (e.g. flushing eventlog buffers) is not
    
    20
    + * accounted for, and the next tick is delayed by that much (modulo wakeup
    
    21
    + * jitter). This is probably the right thing to do: generally in realtime
    
    22
    + * systems one does not want to try to catch up when behind, since that tends
    
    23
    + * towards oversubscribing resources. Graceful degredation is usually
    
    24
    + * preferable.
    
    25
    + *
    
    26
    + * Experimental results (on Linux 6.18 on x86-64) to measure the typical
    
    27
    + * difference between the requested wakeup time and actual wakeup time for
    
    28
    + * different delay intervals:
    
    29
    + *
    
    30
    + *  interval   typical actual wakeup time after due time
    
    31
    + *   10000us   340 -- 400us      (this is the default interval)
    
    32
    + *    1000us    55 -- 100us
    
    33
    + *     100us    55us
    
    34
    + *      10us    55us
    
    35
    + *
    
    36
    + * While there's quite a bit of variance to these numbers, the results do not
    
    37
    + * vary significantly between using select, ppoll or nanosleep.
    
    38
    + *
    
    39
    + * On Linux at least, for longer delays the kernel allows itself lower wakeup
    
    40
    + * accuracy (which allows it to save power by coalescing multiple wakeups).
    
    41
    + * Similarly, the reason for 55us on the low end is that the default thread
    
    42
    + * timer slack on Linux is 50us, and context switch time accounts for the
    
    43
    + * remainder.
    
    44
    + *
    
    45
    + * In conclusion, on Linux at least, the accuracy is fine, both for the
    
    46
    + * default interval (10ms, 10000us) and for shorter intervals used during
    
    47
    + * profiling.
    
    14 48
      *
    
    15 49
      * Historically we had ticker implementations using signals. This was always a
    
    16
    - * rather shakey thing to do but we had few alternatives.
    
    50
    + * rather shakey thing to do but we originally had few alternatives.
    
    17 51
      * - One problem with using signals is that there are severe limits on what
    
    18 52
      *   code can be called from signal handlers. In particular it's not possible
    
    19 53
      *   to take locks in a signal handler contex. This was enough for contex
    
    ... ... @@ -23,17 +57,245 @@
    23 57
      *   calls (#10840) or can be overwritten by user code.
    
    24 58
      */
    
    25 59
     
    
    26
    -/* Select a ticker implementation to use:
    
    27
    - *
    
    28
    - * On modern Linux, FreeBSD and NetBSD we can use timerfd_create and a thread
    
    29
    - * that waits on it using poll. Linux has had timerfd since version 2.6.25.
    
    30
    - * NetBSD has had timerfd since version 10, and FreeBSD since version 15.
    
    31
    - *
    
    32
    - * For older version of linux/bsd without timerfd, and for all other posix
    
    33
    - * platforms, we use the implementation using posix pthreads and nanosleep().
    
    60
    +#include "rts/PosixSource.h"
    
    61
    +#include "Rts.h"
    
    62
    +
    
    63
    +#include "Ticker.h"
    
    64
    +#include "RtsUtils.h"
    
    65
    +#include "Proftimer.h"
    
    66
    +#include "Schedule.h"
    
    67
    +#include "posix/Clock.h"
    
    68
    +#include "posix/FdWakeup.h"
    
    69
    +
    
    70
    +#if defined(HAVE_DECL_PPOLL) && HAVE_DECL_PPOLL == 1
    
    71
    +/* We prefer the ppoll() function if available since it allows sanely waiting
    
    72
    + * on a single fd with precise timeouts (nanosecond precision). It is not in
    
    73
    + * the posix standard however and some platforms (notably glibc and freebsd)
    
    74
    + * need special CPP defines to make it available:
    
    75
    + */
    
    76
    +#define _GNU_SOURCE 1
    
    77
    +#define __BSD_VISIBLE 1
    
    78
    +#include <signal.h>
    
    79
    +#include <poll.h>
    
    80
    +#else
    
    81
    +/* Otherwise we use the classic select(), which does have microsecond
    
    82
    + * precision, but requires we build three whole 1024 bit (128 byte) fd sets
    
    83
    + * just to wait on one fd.
    
    34 84
      */
    
    35
    -#if defined(HAVE_SYS_TIMERFD_H)
    
    36
    -#include "ticker/TimerFd.c"
    
    85
    +#include <sys/select.h>
    
    86
    +#endif
    
    87
    +
    
    88
    +#include <time.h>
    
    89
    +#if HAVE_SYS_TIME_H
    
    90
    +# include <sys/time.h>
    
    91
    +#endif
    
    92
    +
    
    93
    +#if defined(HAVE_SIGNAL_H)
    
    94
    +# include <signal.h>
    
    95
    +#endif
    
    96
    +
    
    97
    +#include <string.h>
    
    98
    +
    
    99
    +#include <pthread.h>
    
    100
    +#if defined(HAVE_PTHREAD_NP_H)
    
    101
    +#include <pthread_np.h>
    
    102
    +#endif
    
    103
    +#include <unistd.h>
    
    104
    +#include <fcntl.h>
    
    105
    +
    
    106
    +static Time itimer_interval = DEFAULT_TICK_INTERVAL;
    
    107
    +
    
    108
    +// Should we be firing ticks?
    
    109
    +// Writers to this must hold the mutex below.
    
    110
    +static bool stopped = false;
    
    111
    +
    
    112
    +// should the ticker thread exit?
    
    113
    +// This can be set without holding the mutex.
    
    114
    +static bool exited = true;
    
    115
    +
    
    116
    +// Signaled when we want to (re)start the timer
    
    117
    +static Condition start_cond;
    
    118
    +static Mutex mutex;
    
    119
    +static OSThreadId thread;
    
    120
    +
    
    121
    +// fds for interrupting the ticker
    
    122
    +static int interruptfd_r = -1, interruptfd_w = -1;
    
    123
    +
    
    124
    +static void *itimer_thread_func(void *_handle_tick)
    
    125
    +{
    
    126
    +    TickProc handle_tick = _handle_tick;
    
    127
    +
    
    128
    +#if defined(HAVE_DECL_PPOLL) && HAVE_DECL_PPOLL == 1
    
    129
    +    struct pollfd pollfds[1];
    
    130
    +
    
    131
    +    pollfds[0].fd = interruptfd_r;
    
    132
    +    pollfds[0].events = POLLIN;
    
    133
    +
    
    134
    +    struct timespec ts = { .tv_sec  = TimeToSeconds(itimer_interval)
    
    135
    +                         , .tv_nsec = TimeToNS(itimer_interval) % 1000000000
    
    136
    +                         };
    
    37 137
     #else
    
    38
    -#include "ticker/Pthread.c"
    
    138
    +    fd_set selectfds;
    
    139
    +    FD_ZERO(&selectfds);
    
    140
    +    FD_SET(interruptfd_r, &selectfds);
    
    141
    +
    
    142
    +    struct timeval tv = { .tv_sec  = TimeToSeconds(itimer_interval)
    
    143
    +                                     /* convert remainder time in nanoseconds
    
    144
    +                                        to microseconds, rounding up: */
    
    145
    +                        , .tv_usec = ((TimeToNS(itimer_interval) % 1000000000)
    
    146
    +                                     + 999) / 1000
    
    147
    +                        };
    
    148
    +#endif
    
    149
    +
    
    150
    +    // Relaxed is sufficient: If we don't see that exited was set in one iteration we will
    
    151
    +    // see it next time.
    
    152
    +    while (!RELAXED_LOAD_ALWAYS(&exited)) {
    
    153
    +
    
    154
    +#if defined(HAVE_DECL_PPOLL) && HAVE_DECL_PPOLL == 1
    
    155
    +        int nfds   = 1;
    
    156
    +        int nready = ppoll(pollfds, nfds, &ts, NULL);
    
    157
    +#else
    
    158
    +        struct timeval tv_tmp = tv; // copy since select may change this value.
    
    159
    +        int nfds   = interruptfd_r+1;
    
    160
    +        int nready = select(nfds, &selectfds, NULL, NULL, &tv_tmp);
    
    161
    +#endif
    
    162
    +        // In either case (ppoll or select), the result nready is the number
    
    163
    +        // of fds that are ready.
    
    164
    +        if (RTS_LIKELY(nready == 0)) {
    
    165
    +            // Timer expired, not interrupted, continue.
    
    166
    +        } else if (nready > 0) {
    
    167
    +            // We only monitor one fd (the interruptfd_r), so we know
    
    168
    +            // it is that fd that is ready without any further checks.
    
    169
    +            collectFdWakeup(interruptfd_r);
    
    170
    +            // No further action needed, continue on to handling the final tick
    
    171
    +            // and then stop.
    
    172
    +
    
    173
    +            // Note that we rely on sendFdWakeup and select/poll to provide the
    
    174
    +            // happens-before relation. So if 'exited' was set before calling
    
    175
    +            // sendFdWakeup, then we should be able to reliably read it after.
    
    176
    +            // And thus reading 'exited' in the while loop guard is ok.
    
    177
    +        } else {
    
    178
    +            // While the RTS attempts to mask signals, some foreign libraries
    
    179
    +            // that rely on signal delivery may unmask them. Consequently we
    
    180
    +            // may see EINTR. See #24610.
    
    181
    +            if (errno != EINTR) {
    
    182
    +                sysErrorBelch("Ticker: poll failed: %s", strerror(errno));
    
    183
    +            }
    
    184
    +        }
    
    185
    +
    
    186
    +        // first try a cheap test
    
    187
    +        if (RELAXED_LOAD_ALWAYS(&stopped)) {
    
    188
    +            OS_ACQUIRE_LOCK(&mutex);
    
    189
    +            // should we really stop?
    
    190
    +            if (stopped) {
    
    191
    +                waitCondition(&start_cond, &mutex);
    
    192
    +            }
    
    193
    +            OS_RELEASE_LOCK(&mutex);
    
    194
    +        } else {
    
    195
    +            handle_tick(0);
    
    196
    +        }
    
    197
    +    }
    
    198
    +
    
    199
    +    return NULL;
    
    200
    +}
    
    201
    +
    
    202
    +void
    
    203
    +initTicker (Time interval, TickProc handle_tick)
    
    204
    +{
    
    205
    +    itimer_interval = interval;
    
    206
    +    stopped = true;
    
    207
    +    exited = false;
    
    208
    +#if defined(HAVE_SIGNAL_H)
    
    209
    +    sigset_t mask, omask;
    
    210
    +    int sigret;
    
    211
    +#endif
    
    212
    +    int ret;
    
    213
    +
    
    214
    +    initCondition(&start_cond);
    
    215
    +    initMutex(&mutex);
    
    216
    +
    
    217
    +    /* Open the interrupt fd synchronously.
    
    218
    +     *
    
    219
    +     * We used to do it in itimer_thread_func (i.e. in the timer thread) but it
    
    220
    +     * meant that some user code could run before it and get confused by the
    
    221
    +     * allocation of the timerfd.
    
    222
    +     *
    
    223
    +     * See hClose002 which unsafely closes a file descriptor twice expecting an
    
    224
    +     * exception the second time: it sometimes failed when the second call to
    
    225
    +     * "close" closed our own timerfd which inadvertently reused the same file
    
    226
    +     * descriptor closed by the first call! (see #20618)
    
    227
    +     */
    
    228
    +
    
    229
    +    if (interruptfd_r != -1) {
    
    230
    +        // don't leak the old file descriptors after a fork (#25280)
    
    231
    +        closeFdWakeup(interruptfd_r, interruptfd_w);
    
    232
    +    }
    
    233
    +    newFdWakeup(&interruptfd_r, &interruptfd_w);
    
    234
    +
    
    235
    +    /*
    
    236
    +     * Create the thread with all blockable signals blocked, leaving signal
    
    237
    +     * handling to the main and/or other threads.  This is especially useful in
    
    238
    +     * the non-threaded runtime, where applications might expect sigprocmask(2)
    
    239
    +     * to effectively block signals.
    
    240
    +     */
    
    241
    +#if defined(HAVE_SIGNAL_H)
    
    242
    +    sigfillset(&mask);
    
    243
    +    sigret = pthread_sigmask(SIG_SETMASK, &mask, &omask);
    
    244
    +#endif
    
    245
    +    ret = createAttachedOSThread(&thread, "ghc_ticker", itimer_thread_func, (void*)handle_tick);
    
    246
    +#if defined(HAVE_SIGNAL_H)
    
    247
    +    if (sigret == 0)
    
    248
    +        pthread_sigmask(SIG_SETMASK, &omask, NULL);
    
    39 249
     #endif
    
    250
    +
    
    251
    +    if (ret != 0) {
    
    252
    +        barf("Ticker: Failed to spawn thread: %s", strerror(errno));
    
    253
    +    }
    
    254
    +}
    
    255
    +
    
    256
    +void
    
    257
    +startTicker(void)
    
    258
    +{
    
    259
    +    OS_ACQUIRE_LOCK(&mutex);
    
    260
    +    RELAXED_STORE(&stopped, false);
    
    261
    +    signalCondition(&start_cond);
    
    262
    +    OS_RELEASE_LOCK(&mutex);
    
    263
    +}
    
    264
    +
    
    265
    +/* There may be at most one additional tick fired after a call to this */
    
    266
    +void
    
    267
    +stopTicker(void)
    
    268
    +{
    
    269
    +    OS_ACQUIRE_LOCK(&mutex);
    
    270
    +    RELAXED_STORE(&stopped, true);
    
    271
    +    OS_RELEASE_LOCK(&mutex);
    
    272
    +}
    
    273
    +
    
    274
    +/* There may be at most one additional tick fired after a call to this */
    
    275
    +void
    
    276
    +exitTicker (bool wait)
    
    277
    +{
    
    278
    +    ASSERT(!SEQ_CST_LOAD(&exited));
    
    279
    +    SEQ_CST_STORE(&exited, true);
    
    280
    +    // ensure that ticker wakes up if stopped
    
    281
    +    startTicker();
    
    282
    +    sendFdWakeup(interruptfd_w);
    
    283
    +
    
    284
    +    // wait for ticker to terminate if necessary
    
    285
    +    if (wait) {
    
    286
    +        if (pthread_join(thread, NULL)) {
    
    287
    +            sysErrorBelch("Ticker: Failed to join: %s", strerror(errno));
    
    288
    +        }
    
    289
    +        closeFdWakeup(interruptfd_r, interruptfd_w);
    
    290
    +        closeMutex(&mutex);
    
    291
    +        closeCondition(&start_cond);
    
    292
    +    } else {
    
    293
    +        pthread_detach(thread);
    
    294
    +    }
    
    295
    +}
    
    296
    +
    
    297
    +int
    
    298
    +rtsTimerSignal(void)
    
    299
    +{
    
    300
    +    return SIGALRM;
    
    301
    +}

  • rts/posix/ticker/Pthread.c deleted
    1
    -/* -----------------------------------------------------------------------------
    
    2
    - *
    
    3
    - * (c) The GHC Team, 1995-2007
    
    4
    - *
    
    5
    - * Interval timer for profiling and pre-emptive scheduling.
    
    6
    - *
    
    7
    - * ---------------------------------------------------------------------------*/
    
    8
    -
    
    9
    -/*
    
    10
    - * We use a realtime timer by default.  I found this much more
    
    11
    - * reliable than a CPU timer:
    
    12
    - *
    
    13
    - * Experiments with different frequencies: using
    
    14
    - * CLOCK_REALTIME/CLOCK_MONOTONIC on Linux 2.6.32,
    
    15
    - *     1000us has  <1% impact on runtime
    
    16
    - *      100us has  ~2% impact on runtime
    
    17
    - *       10us has ~40% impact on runtime
    
    18
    - *
    
    19
    - * using CLOCK_PROCESS_CPUTIME_ID on Linux 2.6.32,
    
    20
    - *     I cannot get it to tick faster than 10ms (10000us)
    
    21
    - *     which isn't great for profiling.
    
    22
    - *
    
    23
    - * In the threaded RTS, we can't tick in CPU time because the thread
    
    24
    - * which has the virtual timer might be idle, so the tick would never
    
    25
    - * fire.  Therefore we used to tick in realtime in the threaded RTS and
    
    26
    - * in CPU time otherwise, but now we always tick in realtime, for
    
    27
    - * several reasons:
    
    28
    - *
    
    29
    - *   - resolution (see above)
    
    30
    - *   - consistency (-threaded is the same as normal)
    
    31
    - *   - more consistency: Windows only has a realtime timer
    
    32
    - *
    
    33
    - * Note we want to use CLOCK_MONOTONIC rather than CLOCK_REALTIME,
    
    34
    - * because the latter may jump around (NTP adjustments, leap seconds
    
    35
    - * etc.).
    
    36
    - */
    
    37
    -
    
    38
    -#include "rts/PosixSource.h"
    
    39
    -#include "Rts.h"
    
    40
    -
    
    41
    -#include "Ticker.h"
    
    42
    -#include "RtsUtils.h"
    
    43
    -#include "Proftimer.h"
    
    44
    -#include "Schedule.h"
    
    45
    -#include "posix/Clock.h"
    
    46
    -#include <poll.h>
    
    47
    -
    
    48
    -#include <time.h>
    
    49
    -#if HAVE_SYS_TIME_H
    
    50
    -# include <sys/time.h>
    
    51
    -#endif
    
    52
    -
    
    53
    -#if defined(HAVE_SIGNAL_H)
    
    54
    -# include <signal.h>
    
    55
    -#endif
    
    56
    -
    
    57
    -#include <string.h>
    
    58
    -
    
    59
    -#include <pthread.h>
    
    60
    -#if defined(HAVE_PTHREAD_NP_H)
    
    61
    -#include <pthread_np.h>
    
    62
    -#endif
    
    63
    -#include <unistd.h>
    
    64
    -#include <fcntl.h>
    
    65
    -
    
    66
    -/*
    
    67
    - * TFD_CLOEXEC has been added in Linux 2.6.26.
    
    68
    - * If it is not available, we use fcntl(F_SETFD).
    
    69
    - */
    
    70
    -#if !defined(TFD_CLOEXEC)
    
    71
    -#define TFD_CLOEXEC 0
    
    72
    -#endif
    
    73
    -
    
    74
    -static Time itimer_interval = DEFAULT_TICK_INTERVAL;
    
    75
    -
    
    76
    -// Should we be firing ticks?
    
    77
    -// Writers to this must hold the mutex below.
    
    78
    -static bool stopped = false;
    
    79
    -
    
    80
    -// should the ticker thread exit?
    
    81
    -// This can be set without holding the mutex.
    
    82
    -static bool exited = true;
    
    83
    -
    
    84
    -// Signaled when we want to (re)start the timer
    
    85
    -static Condition start_cond;
    
    86
    -static Mutex mutex;
    
    87
    -static OSThreadId thread;
    
    88
    -
    
    89
    -static void *itimer_thread_func(void *_handle_tick)
    
    90
    -{
    
    91
    -    TickProc handle_tick = _handle_tick;
    
    92
    -
    
    93
    -    // Relaxed is sufficient: If we don't see that exited was set in one iteration we will
    
    94
    -    // see it next time.
    
    95
    -    while (!RELAXED_LOAD_ALWAYS(&exited)) {
    
    96
    -        if (rtsSleep(itimer_interval) != 0) {
    
    97
    -            sysErrorBelch("Ticker: sleep failed: %s", strerror(errno));
    
    98
    -        }
    
    99
    -
    
    100
    -        // first try a cheap test
    
    101
    -        if (RELAXED_LOAD_ALWAYS(&stopped)) {
    
    102
    -            OS_ACQUIRE_LOCK(&mutex);
    
    103
    -            // should we really stop?
    
    104
    -            if (stopped) {
    
    105
    -                waitCondition(&start_cond, &mutex);
    
    106
    -            }
    
    107
    -            OS_RELEASE_LOCK(&mutex);
    
    108
    -        } else {
    
    109
    -            handle_tick(0);
    
    110
    -        }
    
    111
    -    }
    
    112
    -
    
    113
    -    return NULL;
    
    114
    -}
    
    115
    -
    
    116
    -void
    
    117
    -initTicker (Time interval, TickProc handle_tick)
    
    118
    -{
    
    119
    -    itimer_interval = interval;
    
    120
    -    stopped = true;
    
    121
    -    exited = false;
    
    122
    -#if defined(HAVE_SIGNAL_H)
    
    123
    -    sigset_t mask, omask;
    
    124
    -    int sigret;
    
    125
    -#endif
    
    126
    -    int ret;
    
    127
    -
    
    128
    -    initCondition(&start_cond);
    
    129
    -    initMutex(&mutex);
    
    130
    -
    
    131
    -    /*
    
    132
    -     * Create the thread with all blockable signals blocked, leaving signal
    
    133
    -     * handling to the main and/or other threads.  This is especially useful in
    
    134
    -     * the non-threaded runtime, where applications might expect sigprocmask(2)
    
    135
    -     * to effectively block signals.
    
    136
    -     */
    
    137
    -#if defined(HAVE_SIGNAL_H)
    
    138
    -    sigfillset(&mask);
    
    139
    -    sigret = pthread_sigmask(SIG_SETMASK, &mask, &omask);
    
    140
    -#endif
    
    141
    -    ret = createAttachedOSThread(&thread, "ghc_ticker", itimer_thread_func, (void*)handle_tick);
    
    142
    -#if defined(HAVE_SIGNAL_H)
    
    143
    -    if (sigret == 0)
    
    144
    -        pthread_sigmask(SIG_SETMASK, &omask, NULL);
    
    145
    -#endif
    
    146
    -
    
    147
    -    if (ret != 0) {
    
    148
    -        barf("Ticker: Failed to spawn thread: %s", strerror(errno));
    
    149
    -    }
    
    150
    -}
    
    151
    -
    
    152
    -void
    
    153
    -startTicker(void)
    
    154
    -{
    
    155
    -    OS_ACQUIRE_LOCK(&mutex);
    
    156
    -    RELAXED_STORE(&stopped, false);
    
    157
    -    signalCondition(&start_cond);
    
    158
    -    OS_RELEASE_LOCK(&mutex);
    
    159
    -}
    
    160
    -
    
    161
    -/* There may be at most one additional tick fired after a call to this */
    
    162
    -void
    
    163
    -stopTicker(void)
    
    164
    -{
    
    165
    -    OS_ACQUIRE_LOCK(&mutex);
    
    166
    -    RELAXED_STORE(&stopped, true);
    
    167
    -    OS_RELEASE_LOCK(&mutex);
    
    168
    -}
    
    169
    -
    
    170
    -/* There may be at most one additional tick fired after a call to this */
    
    171
    -void
    
    172
    -exitTicker (bool wait)
    
    173
    -{
    
    174
    -    ASSERT(!SEQ_CST_LOAD(&exited));
    
    175
    -    SEQ_CST_STORE(&exited, true);
    
    176
    -    // ensure that ticker wakes up if stopped
    
    177
    -    startTicker();
    
    178
    -
    
    179
    -    // wait for ticker to terminate if necessary
    
    180
    -    if (wait) {
    
    181
    -        if (pthread_join(thread, NULL)) {
    
    182
    -            sysErrorBelch("Ticker: Failed to join: %s", strerror(errno));
    
    183
    -        }
    
    184
    -        closeMutex(&mutex);
    
    185
    -        closeCondition(&start_cond);
    
    186
    -    } else {
    
    187
    -        pthread_detach(thread);
    
    188
    -    }
    
    189
    -}
    
    190
    -
    
    191
    -int
    
    192
    -rtsTimerSignal(void)
    
    193
    -{
    
    194
    -    return SIGALRM;
    
    195
    -}

  • rts/posix/ticker/TimerFd.c deleted
    1
    -/* -----------------------------------------------------------------------------
    
    2
    - *
    
    3
    - * (c) The GHC Team, 1995-2023
    
    4
    - *
    
    5
    - * Interval timer for profiling and pre-emptive scheduling.
    
    6
    - *
    
    7
    - * ---------------------------------------------------------------------------*/
    
    8
    -
    
    9
    -/*
    
    10
    - * We use a realtime timer by default.  I found this much more
    
    11
    - * reliable than a CPU timer:
    
    12
    - *
    
    13
    - * Experiments with different frequencies: using
    
    14
    - * CLOCK_REALTIME/CLOCK_MONOTONIC on Linux 2.6.32,
    
    15
    - *     1000us has  <1% impact on runtime
    
    16
    - *      100us has  ~2% impact on runtime
    
    17
    - *       10us has ~40% impact on runtime
    
    18
    - *
    
    19
    - * using CLOCK_PROCESS_CPUTIME_ID on Linux 2.6.32,
    
    20
    - *     I cannot get it to tick faster than 10ms (10000us)
    
    21
    - *     which isn't great for profiling.
    
    22
    - *
    
    23
    - * In the threaded RTS, we can't tick in CPU time because the thread
    
    24
    - * which has the virtual timer might be idle, so the tick would never
    
    25
    - * fire.  Therefore we used to tick in realtime in the threaded RTS and
    
    26
    - * in CPU time otherwise, but now we always tick in realtime, for
    
    27
    - * several reasons:
    
    28
    - *
    
    29
    - *   - resolution (see above)
    
    30
    - *   - consistency (-threaded is the same as normal)
    
    31
    - *   - more consistency: Windows only has a realtime timer
    
    32
    - *
    
    33
    - * Note we want to use CLOCK_MONOTONIC rather than CLOCK_REALTIME,
    
    34
    - * because the latter may jump around (NTP adjustments, leap seconds
    
    35
    - * etc.).
    
    36
    - */
    
    37
    -
    
    38
    -#include "rts/PosixSource.h"
    
    39
    -#include "Rts.h"
    
    40
    -
    
    41
    -#include "Ticker.h"
    
    42
    -#include "RtsUtils.h"
    
    43
    -#include "Proftimer.h"
    
    44
    -#include "Schedule.h"
    
    45
    -#include "posix/Clock.h"
    
    46
    -#include <poll.h>
    
    47
    -
    
    48
    -#include <time.h>
    
    49
    -#if HAVE_SYS_TIME_H
    
    50
    -# include <sys/time.h>
    
    51
    -#endif
    
    52
    -
    
    53
    -#if defined(HAVE_SIGNAL_H)
    
    54
    -# include <signal.h>
    
    55
    -#endif
    
    56
    -
    
    57
    -#include <string.h>
    
    58
    -
    
    59
    -#include <pthread.h>
    
    60
    -#if defined(HAVE_PTHREAD_NP_H)
    
    61
    -#include <pthread_np.h>
    
    62
    -#endif
    
    63
    -#include <unistd.h>
    
    64
    -#include <fcntl.h>
    
    65
    -
    
    66
    -#include <sys/timerfd.h>
    
    67
    -
    
    68
    -
    
    69
    -/*
    
    70
    - * TFD_CLOEXEC has been added in Linux 2.6.26.
    
    71
    - * If it is not available, we use fcntl(F_SETFD).
    
    72
    - */
    
    73
    -#if !defined(TFD_CLOEXEC)
    
    74
    -#define TFD_CLOEXEC 0
    
    75
    -#endif
    
    76
    -
    
    77
    -static Time itimer_interval = DEFAULT_TICK_INTERVAL;
    
    78
    -
    
    79
    -// Should we be firing ticks?
    
    80
    -// Writers to this must hold the mutex below.
    
    81
    -static bool stopped = false;
    
    82
    -
    
    83
    -// should the ticker thread exit?
    
    84
    -// This can be set without holding the mutex.
    
    85
    -static bool exited = true;
    
    86
    -
    
    87
    -// Signaled when we want to (re)start the timer
    
    88
    -static Condition start_cond;
    
    89
    -static Mutex mutex;
    
    90
    -static OSThreadId thread;
    
    91
    -
    
    92
    -// file descriptor for the timer (Linux only)
    
    93
    -static int timerfd = -1;
    
    94
    -
    
    95
    -// pipe for signaling exit
    
    96
    -static int pipefds[2];
    
    97
    -
    
    98
    -static void *itimer_thread_func(void *_handle_tick)
    
    99
    -{
    
    100
    -    TickProc handle_tick = _handle_tick;
    
    101
    -    uint64_t nticks;
    
    102
    -    ssize_t r = 0;
    
    103
    -    struct pollfd pollfds[2];
    
    104
    -
    
    105
    -    pollfds[0].fd = pipefds[0];
    
    106
    -    pollfds[0].events = POLLIN;
    
    107
    -    pollfds[1].fd = timerfd;
    
    108
    -    pollfds[1].events = POLLIN;
    
    109
    -
    
    110
    -    // Relaxed is sufficient: If we don't see that exited was set in one iteration we will
    
    111
    -    // see it next time.
    
    112
    -    while (!RELAXED_LOAD_ALWAYS(&exited)) {
    
    113
    -        if (poll(pollfds, 2, -1) == -1) {
    
    114
    -            // While the RTS attempts to mask signals, some foreign libraries
    
    115
    -            // may rely on signal delivery may unmask them. Consequently we may
    
    116
    -            // see EINTR. See #24610.
    
    117
    -            if (errno != EINTR) {
    
    118
    -                sysErrorBelch("Ticker: poll failed: %s", strerror(errno));
    
    119
    -            }
    
    120
    -        }
    
    121
    -
    
    122
    -        // We check the pipe first, even though the timerfd may also have triggered.
    
    123
    -        if (pollfds[0].revents & POLLIN) {
    
    124
    -            // the pipe is ready for reading, the only possible reason is that we're exiting
    
    125
    -            exited = true; // set this again to make sure even RELAXED_LOAD will read the proper value
    
    126
    -            // no further action needed, skip ahead to handling the final tick and then stopping
    
    127
    -        }
    
    128
    -        else if (pollfds[1].revents & POLLIN) { // the timerfd is ready for reading
    
    129
    -            r = read(timerfd, &nticks, sizeof(nticks)); // this should never block now
    
    130
    -
    
    131
    -            if ((r == 0) && (errno == 0)) {
    
    132
    -               /* r == 0 is expected only for non-blocking fd (in which case
    
    133
    -                * errno should be EAGAIN) but we use a blocking fd.
    
    134
    -                *
    
    135
    -                * Due to a kernel bug (cf https://lkml.org/lkml/2019/8/16/335)
    
    136
    -                * on some platforms we could see r == 0 and errno == 0.
    
    137
    -                */
    
    138
    -               IF_DEBUG(scheduler, debugBelch("read(timerfd) returned 0 with errno=0. This is a known kernel bug. We just ignore it."));
    
    139
    -            }
    
    140
    -            else if (r != sizeof(nticks) && errno != EINTR) {
    
    141
    -               barf("Ticker: read(timerfd) failed with %s and returned %zd", strerror(errno), r);
    
    142
    -            }
    
    143
    -        }
    
    144
    -
    
    145
    -        // first try a cheap test
    
    146
    -        if (RELAXED_LOAD_ALWAYS(&stopped)) {
    
    147
    -            OS_ACQUIRE_LOCK(&mutex);
    
    148
    -            // should we really stop?
    
    149
    -            if (stopped) {
    
    150
    -                waitCondition(&start_cond, &mutex);
    
    151
    -            }
    
    152
    -            OS_RELEASE_LOCK(&mutex);
    
    153
    -        } else {
    
    154
    -            handle_tick(0);
    
    155
    -        }
    
    156
    -    }
    
    157
    -
    
    158
    -    close(timerfd);
    
    159
    -    return NULL;
    
    160
    -}
    
    161
    -
    
    162
    -void
    
    163
    -initTicker (Time interval, TickProc handle_tick)
    
    164
    -{
    
    165
    -    itimer_interval = interval;
    
    166
    -    stopped = true;
    
    167
    -    exited = false;
    
    168
    -#if defined(HAVE_SIGNAL_H)
    
    169
    -    sigset_t mask, omask;
    
    170
    -    int sigret;
    
    171
    -#endif
    
    172
    -    int ret;
    
    173
    -
    
    174
    -    initCondition(&start_cond);
    
    175
    -    initMutex(&mutex);
    
    176
    -
    
    177
    -    /* Open the file descriptor for the timer synchronously.
    
    178
    -     *
    
    179
    -     * We used to do it in itimer_thread_func (i.e. in the timer thread) but it
    
    180
    -     * meant that some user code could run before it and get confused by the
    
    181
    -     * allocation of the timerfd.
    
    182
    -     *
    
    183
    -     * See hClose002 which unsafely closes a file descriptor twice expecting an
    
    184
    -     * exception the second time: it sometimes failed when the second call to
    
    185
    -     * "close" closed our own timerfd which inadvertently reused the same file
    
    186
    -     * descriptor closed by the first call! (see #20618)
    
    187
    -     */
    
    188
    -    struct itimerspec it;
    
    189
    -    it.it_value.tv_sec  = TimeToSeconds(itimer_interval);
    
    190
    -    it.it_value.tv_nsec = TimeToNS(itimer_interval) % 1000000000;
    
    191
    -    it.it_interval = it.it_value;
    
    192
    -
    
    193
    -    if (timerfd != -1) {
    
    194
    -        // don't leak the old file descriptors after a fork (#25280)
    
    195
    -        close(timerfd);
    
    196
    -        close(pipefds[0]);
    
    197
    -        close(pipefds[1]);
    
    198
    -        timerfd = -1;
    
    199
    -    }
    
    200
    -
    
    201
    -    timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
    
    202
    -    if (timerfd == -1) {
    
    203
    -        barf("timerfd_create: %s", strerror(errno));
    
    204
    -    }
    
    205
    -    if (!TFD_CLOEXEC) {
    
    206
    -        fcntl(timerfd, F_SETFD, FD_CLOEXEC);
    
    207
    -    }
    
    208
    -    if (timerfd_settime(timerfd, 0, &it, NULL)) {
    
    209
    -        barf("timerfd_settime: %s", strerror(errno));
    
    210
    -    }
    
    211
    -
    
    212
    -    if (pipe(pipefds) < 0) {
    
    213
    -        barf("pipe: %s", strerror(errno));
    
    214
    -    }
    
    215
    -
    
    216
    -    /*
    
    217
    -     * Create the thread with all blockable signals blocked, leaving signal
    
    218
    -     * handling to the main and/or other threads.  This is especially useful in
    
    219
    -     * the non-threaded runtime, where applications might expect sigprocmask(2)
    
    220
    -     * to effectively block signals.
    
    221
    -     */
    
    222
    -#if defined(HAVE_SIGNAL_H)
    
    223
    -    sigfillset(&mask);
    
    224
    -    sigret = pthread_sigmask(SIG_SETMASK, &mask, &omask);
    
    225
    -#endif
    
    226
    -    ret = createAttachedOSThread(&thread, "ghc_ticker", itimer_thread_func, (void*)handle_tick);
    
    227
    -#if defined(HAVE_SIGNAL_H)
    
    228
    -    if (sigret == 0)
    
    229
    -        pthread_sigmask(SIG_SETMASK, &omask, NULL);
    
    230
    -#endif
    
    231
    -
    
    232
    -    if (ret != 0) {
    
    233
    -        barf("Ticker: Failed to spawn thread: %s", strerror(errno));
    
    234
    -    }
    
    235
    -}
    
    236
    -
    
    237
    -void
    
    238
    -startTicker(void)
    
    239
    -{
    
    240
    -    OS_ACQUIRE_LOCK(&mutex);
    
    241
    -    RELAXED_STORE(&stopped, false);
    
    242
    -    signalCondition(&start_cond);
    
    243
    -    OS_RELEASE_LOCK(&mutex);
    
    244
    -}
    
    245
    -
    
    246
    -/* There may be at most one additional tick fired after a call to this */
    
    247
    -void
    
    248
    -stopTicker(void)
    
    249
    -{
    
    250
    -    OS_ACQUIRE_LOCK(&mutex);
    
    251
    -    RELAXED_STORE(&stopped, true);
    
    252
    -    OS_RELEASE_LOCK(&mutex);
    
    253
    -}
    
    254
    -
    
    255
    -/* There may be at most one additional tick fired after a call to this */
    
    256
    -void
    
    257
    -exitTicker (bool wait)
    
    258
    -{
    
    259
    -    ASSERT(!SEQ_CST_LOAD(&exited));
    
    260
    -    SEQ_CST_STORE(&exited, true);
    
    261
    -    // ensure that ticker wakes up if stopped
    
    262
    -    startTicker();
    
    263
    -
    
    264
    -    // wait for ticker to terminate if necessary
    
    265
    -    if (wait) {
    
    266
    -        // write anything to the pipe to trigger poll() in the ticker thread
    
    267
    -        if (write(pipefds[1], "stop", 5) < 0) {
    
    268
    -            sysErrorBelch("Ticker: Failed to write to pipe: %s", strerror(errno));
    
    269
    -        }
    
    270
    -
    
    271
    -        if (pthread_join(thread, NULL)) {
    
    272
    -            sysErrorBelch("Ticker: Failed to join: %s", strerror(errno));
    
    273
    -        }
    
    274
    -
    
    275
    -        // These need to happen AFTER the ticker thread has finished to prevent a race condition
    
    276
    -        // where the ticker thread closes the read end of the pipe before we're done writing to it.
    
    277
    -        close(pipefds[0]);
    
    278
    -        close(pipefds[1]);
    
    279
    -
    
    280
    -        closeMutex(&mutex);
    
    281
    -        closeCondition(&start_cond);
    
    282
    -    } else {
    
    283
    -        pthread_detach(thread);
    
    284
    -    }
    
    285
    -}
    
    286
    -
    
    287
    -int
    
    288
    -rtsTimerSignal(void)
    
    289
    -{
    
    290
    -    return SIGALRM;
    
    291
    -}

  • rts/rts.cabal
    ... ... @@ -582,11 +582,9 @@ library
    582 582
                         posix/Ticker.c
    
    583 583
                         posix/OSMem.c
    
    584 584
                         posix/OSThreads.c
    
    585
    +                    posix/FdWakeup.c
    
    585 586
                         posix/Poll.c
    
    586 587
                         posix/Select.c
    
    587 588
                         posix/Signals.c
    
    588 589
                         posix/Timeout.c
    
    589 590
                         posix/TTY.c
    590
    -                    -- ticker/*.c
    
    591
    -                    -- We don't want to compile posix/ticker/*.c, these will be #included
    
    592
    -                    -- from Ticker.c