Rodrigo Mesquita pushed to branch wip/romes/async-eval-resume at Glasgow Haskell Compiler / GHC

Commits:

18 changed files:

Changes:

  • changelog.d/28228
    1
    +section: ghc-lib
    
    2
    +synopsis: Asynchronous ``evalStmt`` and ``resumeStmt`` results must now be awaited explicitly with ``waitThreadResult``
    
    3
    +issues: #28228
    
    4
    +mrs: !17082
    
    5
    +
    
    6
    +description: {
    
    7
    +  ``evalStmt`` and ``resumeStmt`` from ``GHC.Runtime.Interpreter`` no longer
    
    8
    +  block waiting for the evaluation result. This allows API users to use the
    
    9
    +  multi-threaded debugging capabilities, e.g. resuming many threads without
    
    10
    +  blocking and then only later waiting for the main result. GHCi's interface is
    
    11
    +  not adapted to the multi-threaded debugging capabilities yet. Namely:
    
    12
    +  - ``evalStmt`` returns the ``ForeignRef ThreadId`` of the evaluation thread
    
    13
    +    and ``resumeStmt`` returns ``()``.
    
    14
    +  - New ``waitThreadResult`` awaits the result or a breakpoint of an
    
    15
    +    interpreter thread, redirecting asynchronous exceptions such as ``^C`` at
    
    16
    +    the interpreter thread, to give it a chance to clean up.
    
    17
    +}

  • compiler/GHC/Runtime/Eval.hs
    ... ... @@ -43,6 +43,7 @@ module GHC.Runtime.Eval (
    43 43
             ) where
    
    44 44
     
    
    45 45
     import GHC.Prelude
    
    46
    +import GHC.Conc
    
    46 47
     
    
    47 48
     import GHC.Driver.Monad
    
    48 49
     import GHC.Driver.Main
    
    ... ... @@ -186,7 +187,7 @@ execOptions = ExecOptions
    186 187
       , execWrap = EvalThis -- just run the statement, don't wrap it in anything
    
    187 188
       }
    
    188 189
     
    
    189
    --- | Run a statement in the current interactive context.
    
    190
    +-- | Run a statement in the current interactive context, as a new thread in the interpreter.
    
    190 191
     execStmt
    
    191 192
       :: GhcMonad m
    
    192 193
       => String             -- ^ a statement (bind or expression)
    
    ... ... @@ -229,15 +230,16 @@ execStmt' stmt stmt_text ExecOptions{..} = do
    229 230
             updateFixityEnv fix_env
    
    230 231
     
    
    231 232
             let eval_opts = initEvalOpts idflags' (enableGhcStepMode execSingleStep)
    
    232
    -        status <- liftIO $ evalStmt interp eval_opts (execWrap hval)
    
    233
    +        main_tid <- liftIO $ evalStmt interp eval_opts (execWrap hval)
    
    233 234
     
    
    234 235
             let ic = hsc_IC hsc_env
    
    235 236
                 bindings = (ic_tythings ic, ic_gre_cache ic)
    
    236 237
     
    
    237 238
                 size = ghciHistSize idflags'
    
    238 239
     
    
    240
    +        status <- liftIO $ waitThreadResult interp main_tid eval_opts main_tid
    
    239 241
             handleRunStatus execSingleStep eval_opts stmt_text bindings ids
    
    240
    -                        status (emptyHistory size)
    
    242
    +                        status (emptyHistory size) main_tid
    
    241 243
     
    
    242 244
     runDecls :: GhcMonad m => String -> m [TyThing]
    
    243 245
     runDecls = runDeclsWithLocation "<interactive>" 1
    
    ... ... @@ -300,8 +302,10 @@ handleRunStatus :: GhcMonad m
    300 302
                     -> [Id]
    
    301 303
                     -> EvalStatus [ForeignHValue]
    
    302 304
                     -> BoundedList History
    
    305
    +                -> ForeignRef ThreadId
    
    306
    +                -- ^ The thread started by evalStmt to run this evaluation
    
    303 307
                     -> m ExecResult
    
    304
    -handleRunStatus step eval_opts expr bindings final_ids status history0 = do
    
    308
    +handleRunStatus step eval_opts expr bindings final_ids status history0 main_tid = do
    
    305 309
       hsc_env <- getSession
    
    306 310
       let
    
    307 311
         interp = hscInterp hsc_env
    
    ... ... @@ -342,6 +346,7 @@ handleRunStatus step eval_opts expr bindings final_ids status history0 = do
    342 346
               , resumeDecl = "<exception thrown>"
    
    343 347
               , resumeCCS = ccs
    
    344 348
               , resumeHistoryIx = 0
    
    349
    +          , resumeMainThread = main_tid
    
    345 350
               }
    
    346 351
             hsc_env2 = pushResume hsc_env1 resume
    
    347 352
     
    
    ... ... @@ -389,19 +394,24 @@ handleRunStatus step eval_opts expr bindings final_ids status history0 = do
    389 394
                 , resumeDecl = decl
    
    390 395
                 , resumeCCS = ccs
    
    391 396
                 , resumeHistoryIx = 0
    
    397
    +            , resumeMainThread = main_tid
    
    392 398
                 }
    
    393 399
               hsc_env2 = pushResume hsc_env1 resume
    
    394 400
             setSession hsc_env2
    
    395 401
             return (ExecBreak break_ids (Just ibi) resume)
    
    396 402
           else do
    
    397
    -        -- resume with the same step type
    
    398
    -        status <- liftIO $ GHCi.resumeStmt interp eval_opts resume_ctxt_fhv
    
    399
    -        history <- if not tracing then pure history0 else do
    
    400
    -          history1 <- liftIO $ mkHistory hug apStack_fhv ibi
    
    401
    -          let !history' = history1 `consBL` history0
    
    402
    -                -- history is strict, otherwise our BoundedList is pointless.
    
    403
    -          return history'
    
    404
    -        handleRunStatus step eval_opts expr bindings final_ids status history
    
    403
    +        (status, history) <- liftIO $ do
    
    404
    +          -- resume with the same step type
    
    405
    +          GHCi.resumeStmt interp eval_opts resume_ctxt_fhv
    
    406
    +          -- Redirect exceptions to the resumed thread, but await the main thread:
    
    407
    +          status <- waitThreadResult interp resume_ctxt_fhv eval_opts main_tid
    
    408
    +          history <- if not tracing then pure history0 else do
    
    409
    +            history1 <- mkHistory hug apStack_fhv ibi
    
    410
    +            let !history' = history1 `consBL` history0
    
    411
    +                  -- history is strict, otherwise our BoundedList is pointless.
    
    412
    +            return history'
    
    413
    +          return (status, history)
    
    414
    +        handleRunStatus step eval_opts expr bindings final_ids status history main_tid
    
    405 415
      where
    
    406 416
       tracing | RunAndLogSteps <- step = True
    
    407 417
               | otherwise              = False
    
    ... ... @@ -447,7 +457,9 @@ resumeExec step mbCnt r = do
    447 457
                , resumeApStack = apStack
    
    448 458
                , resumeBreakpointId = mb_brkpt
    
    449 459
                , resumeSpan = span
    
    450
    -           , resumeHistory = hist } ->
    
    460
    +           , resumeHistory = hist
    
    461
    +           , resumeMainThread = main_tid
    
    462
    +           } ->
    
    451 463
              do
    
    452 464
               -- When the user specified a break ignore count, set it
    
    453 465
               -- in the interpreter
    
    ... ... @@ -456,17 +468,19 @@ resumeExec step mbCnt r = do
    456 468
                 _ -> return ()
    
    457 469
     
    
    458 470
               let eval_opts = initEvalOpts dflags (enableGhcStepMode step)
    
    459
    -          status <- liftIO $ GHCi.resumeStmt interp eval_opts fhv
    
    471
    +          status <- liftIO $ do
    
    472
    +            GHCi.resumeStmt interp eval_opts fhv
    
    473
    +            waitThreadResult interp fhv eval_opts main_tid
    
    460 474
               let prevHistoryLst = fromListBL 50 hist
    
    461 475
                   hug = hsc_HUG hsc_env
    
    462
    -              hist' = case mb_brkpt of
    
    476
    +          hist_val <- case mb_brkpt of
    
    463 477
                      Nothing -> pure prevHistoryLst
    
    464 478
                      Just bi
    
    465 479
                        | breakHere False step span -> do
    
    466 480
                           hist1 <- liftIO (mkHistory hug apStack bi)
    
    467 481
                           return $ hist1 `consBL` fromListBL 50 hist
    
    468 482
                        | otherwise -> pure prevHistoryLst
    
    469
    -          handleRunStatus step eval_opts expr bindings final_ids status =<< hist'
    
    483
    +          handleRunStatus step eval_opts expr bindings final_ids status hist_val main_tid
    
    470 484
     
    
    471 485
     setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m ()   -- #19157
    
    472 486
     setupBreakpoint interp ibi cnt = do
    
    ... ... @@ -1278,7 +1292,8 @@ compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do
    1278 1292
       updateFixityEnv fix_env
    
    1279 1293
       -- Only this expression's result is expected, never another thread's break
    
    1280 1294
       let eval_opts = (initEvalOpts dflags EvalStepNone) { readAllBreaks = False }
    
    1281
    -  status <- liftIO $ evalStmt interp eval_opts (EvalThis hvals_io)
    
    1295
    +  main_tid <- liftIO $ evalStmt interp eval_opts (EvalThis hvals_io)
    
    1296
    +  status   <- liftIO $ waitThreadResult interp main_tid eval_opts main_tid
    
    1282 1297
       case status of
    
    1283 1298
         EvalComplete _ (EvalSuccess [hval]) -> return hval
    
    1284 1299
         EvalComplete _ (EvalException e) ->
    

  • compiler/GHC/Runtime/Eval/Types.hs
    ... ... @@ -198,6 +198,10 @@ data Resume = Resume
    198 198
            , resumeCCS       :: RemotePtr CostCentreStack
    
    199 199
            , resumeHistory   :: [History]
    
    200 200
            , resumeHistoryIx :: Int           -- 0 <==> at the top of the history
    
    201
    +       , resumeMainThread :: ForeignRef ThreadId
    
    202
    +         -- ^ The corresponding main evaluation thread. A breakpoint may be on
    
    203
    +         -- a forked thread: we resume the stopped thread ('resumeContext'),
    
    204
    +         -- but await on the main evaluation one ('resumeMainThread')
    
    201 205
            }
    
    202 206
     
    
    203 207
     type ResumeBindings = ([TyThing], IcGlobalRdrEnv)
    

  • compiler/GHC/Runtime/Interpreter.hs
    ... ... @@ -10,6 +10,8 @@ module GHC.Runtime.Interpreter
    10 10
       -- * High-level interface to the interpreter
    
    11 11
       , evalStmt, EvalStatus(..), EvalResult(..), EvalExpr(..)
    
    12 12
       , resumeStmt
    
    13
    +  , waitThreadResult
    
    14
    +  , redirectInterrupts
    
    13 15
       , abandonStmt
    
    14 16
       , evalIO
    
    15 17
       , evalString
    
    ... ... @@ -104,7 +106,7 @@ import GHC.Unit.Home.ModInfo
    104 106
     import GHC.Unit.Env
    
    105 107
     
    
    106 108
     #if defined(HAVE_INTERNAL_INTERPRETER)
    
    107
    -import GHCi.Run
    
    109
    +import GHCi.Run hiding (redirectInterrupts)
    
    108 110
     #endif
    
    109 111
     
    
    110 112
     import Control.Concurrent
    
    ... ... @@ -322,11 +324,11 @@ evalStmt
    322 324
       :: SafeInterp
    
    323 325
       -> EvalOpts
    
    324 326
       -> EvalExpr ForeignHValue
    
    325
    -  -> IO (EvalStatus [ForeignHValue])
    
    327
    +  -> IO (ForeignRef ThreadId)
    
    326 328
     evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do
    
    327
    -  status <- withExpr foreign_expr $ \expr ->
    
    329
    +  rtid <- withExpr foreign_expr $ \expr ->
    
    328 330
         interpCmd interp (EvalStmt opts expr)
    
    329
    -  handleEvalStatus interp status
    
    331
    +  mkFinalizedHValue interp rtid
    
    330 332
      where
    
    331 333
       withExpr :: EvalExpr ForeignHValue -> (EvalExpr HValueRef -> IO a) -> IO a
    
    332 334
       withExpr (EvalThis fhv) cont =
    
    ... ... @@ -340,12 +342,48 @@ resumeStmt
    340 342
       :: SafeInterp
    
    341 343
       -> EvalOpts
    
    342 344
       -> ForeignRef ThreadId
    
    343
    -  -> IO (EvalStatus [ForeignHValue])
    
    345
    +  -- ^ The thread to resume
    
    346
    +  -> IO ()
    
    344 347
     resumeStmt interp0 opts resume_tid = withInterp interp0 $ \interp -> do
    
    345
    -  status <- withForeignRef resume_tid $ \rhv ->
    
    348
    +  withForeignRef resume_tid $ \rhv -> do
    
    346 349
         interpCmd interp (ResumeStmt opts rhv)
    
    350
    +
    
    351
    +-- | Await the result of an action of type @IO [a]@, running on the given
    
    352
    +-- interpreter thread, returning 'ForeignHValue's for each of the results.
    
    353
    +waitThreadResult
    
    354
    +  :: SafeInterp
    
    355
    +  -> ForeignRef ThreadId
    
    356
    +  -- ^ The thread on the interpreter on which asynchronous exceptions raised in
    
    357
    +  -- this host thread are thrown to. Typically this should be the same as the
    
    358
    +  -- thread whose result we're awaiting.
    
    359
    +  -> EvalOpts
    
    360
    +  -- ^ Use 'readAllBreaks' as: @True@ to read breakpoints on all non-isolated
    
    361
    +  -- interpreter threads (such as those forked off by the debuggee evaluation
    
    362
    +  -- statement); @False@ to only return the result or breakpoints in this
    
    363
    +  -- thread specifically.
    
    364
    +  -> ForeignRef ThreadId
    
    365
    +  -- ^ The main isolated evaluation thread whose status is awaited
    
    366
    +  -> IO (EvalStatus [ForeignHValue])
    
    367
    +waitThreadResult interp0 redirect_ftid opts wait_ftid = withInterp interp0 $ \interp -> do
    
    368
    +  status <- withForeignRef redirect_ftid $ \redirect_tid -> do
    
    369
    +    redirectInterrupts interp redirect_tid $
    
    370
    +      withForeignRef wait_ftid $ \wait_tid ->
    
    371
    +        interpCmd interp (WaitThreadResult (readAllBreaks opts) wait_tid)
    
    347 372
       handleEvalStatus interp status
    
    348 373
     
    
    374
    +-- | While we're waiting for the possibly remote interpreter thread to yield a
    
    375
    +-- result, if the current host thread receives an asynchronous exception, we
    
    376
    +-- re-throw it at the target thread on the possibly remote interpreter and
    
    377
    +-- continue to wait. This allows e.g. a ^C on the host to interrupt an
    
    378
    +-- 'evalStmt' on the external interpreter.
    
    379
    +--
    
    380
    +-- Akin 'GHCi.Run.redirectInterrupts', but on the ghc side.
    
    381
    +redirectInterrupts :: Interp -> RemoteRef ThreadId -> IO a -> IO a
    
    382
    +redirectInterrupts interp rtid wait =
    
    383
    +  wait `catch` \(e::SomeAsyncException) -> do
    
    384
    +    interpCmd interp (ThrowToThread rtid (toSerializableException (toException e)))
    
    385
    +    wait
    
    386
    +
    
    349 387
     abandonStmt :: SafeInterp -> ForeignRef ThreadId -> IO ()
    
    350 388
     abandonStmt interp0 resume_tid = withInterp interp0 $ \ interp ->
    
    351 389
       withForeignRef resume_tid $ \rhv ->
    
    ... ... @@ -452,7 +490,11 @@ whereFrom interp0 ref = withInterp interp0 $ \ interp ->
    452 490
     seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
    
    453 491
     seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp ->
    
    454 492
       withForeignRef ref $ \hval -> do
    
    455
    -    status <- interpCmd interp (Seq hval)
    
    493
    +    rtid <- interpCmd interp (Seq hval)
    
    494
    +    frtid <- mkFinalizedHValue interp rtid
    
    495
    +    status <- withForeignRef frtid $ \rtid ->
    
    496
    +      redirectInterrupts interp rtid $ do
    
    497
    +        interpCmd interp (WaitThreadResult False rtid)
    
    456 498
         handleSeqHValueStatus interp unit_env logger (clearEvalStatus status)
    
    457 499
     
    
    458 500
     evalBreakpointToId :: EvalBreakpoint -> InternalBreakpointId
    
    ... ... @@ -496,7 +538,12 @@ handleSeqHValueStatus interp unit_env logger eval_status =
    496 538
     
    
    497 539
           -- resume the seq (:force) processing in the iserv process
    
    498 540
           withForeignRef resume_tid_fhv $ \rtid -> do
    
    499
    -        status <- interpCmd interp (ResumeSeq rtid)
    
    541
    +        interpCmd interp (ResumeSeq rtid)
    
    542
    +        status <- redirectInterrupts interp rtid $ do
    
    543
    +          -- Resume the stopped thread. The stopped thread must be the main
    
    544
    +          -- `:seq` thread, since readAllBreaks=False on @Seq@ cmd implies an
    
    545
    +          -- EvalBreak on a :seq must be from from the seq main thread
    
    546
    +          interpCmd interp (WaitThreadResult False rtid)
    
    500 547
             handleSeqHValueStatus interp unit_env logger (clearEvalStatus status)
    
    501 548
         (EvalComplete _ r) -> return r
    
    502 549
     
    

  • ghc/GHCi/UI/Monad.hs
    ... ... @@ -380,7 +380,8 @@ runStmt stmt stmt_text step = do
    380 380
                       , GHC.execSingleStep = step
    
    381 381
                       , GHC.execWrap = \fhv -> EvalApp (EvalThis (evalWrapper st))
    
    382 382
                                                        (EvalThis fhv) }
    
    383
    -    Just <$> GHC.execStmt' stmt stmt_text opts
    
    383
    +    waitRes <- GHC.execStmt' stmt stmt_text opts
    
    384
    +    Just <$> waitRes
    
    384 385
     
    
    385 386
     runDecls :: GhciMonad m => String -> m (Maybe [GHC.TyThing])
    
    386 387
     runDecls decls = do
    
    ... ... @@ -418,7 +419,8 @@ resume step mbIgnoreCnt = do
    418 419
                     throwGhcExceptionIO (GHC.ProgramError "not stopped at a breakpoint")
    
    419 420
               (r:rs) -> do
    
    420 421
                 modifySession $ \env -> env{hsc_IC = (hsc_IC env){ ic_resume = rs }}
    
    421
    -            GHC.resumeExec step mbIgnoreCnt r
    
    422
    +            waitRes <- GHC.resumeExec step mbIgnoreCnt r
    
    423
    +            waitRes
    
    422 424
     
    
    423 425
     -- --------------------------------------------------------------------------
    
    424 426
     -- timing & statistics
    

  • libraries/ghci/GHCi/Message.hs
    ... ... @@ -144,13 +144,14 @@ data Message a where
    144 144
       EvalStmt
    
    145 145
         :: EvalOpts
    
    146 146
         -> EvalExpr HValueRef {- IO [a] -}
    
    147
    -    -> Message (EvalStatus [HValueRef]) {- [a] -}
    
    147
    +    -> Message (RemoteRef ThreadId)
    
    148
    +    -- ^ 'WaitThreadResult' of this thread id yields [a]
    
    148 149
     
    
    149 150
       -- | Resume evaluation of a statement after a breakpoint
    
    150 151
       ResumeStmt
    
    151 152
        :: EvalOpts
    
    152 153
        -> RemoteRef ThreadId
    
    153
    -   -> Message (EvalStatus [HValueRef])
    
    154
    +   -> Message ()
    
    154 155
     
    
    155 156
       -- | Abandon evaluation of a statement after a breakpoint
    
    156 157
       AbandonStmt
    
    ... ... @@ -254,13 +255,27 @@ data Message a where
    254 255
       -- | Evaluate something. This is used to support :force in GHCi.
    
    255 256
       Seq
    
    256 257
         :: HValueRef
    
    257
    -    -> Message (EvalStatus [HValueRef])
    
    258
    +    -> Message (RemoteRef ThreadId)
    
    258 259
     
    
    259 260
       -- | Resume forcing a free variable in a breakpoint (#2950)
    
    260 261
       ResumeSeq
    
    261 262
         :: RemoteRef ThreadId
    
    263
    +    -> Message ()
    
    264
    +
    
    265
    +  -- | Await the result or a breakpoint of a sandbox thread.
    
    266
    +  WaitThreadResult
    
    267
    +    :: Bool
    
    268
    +    -- ^ Whether to read all thread breaks on any forked threads (@True@) or
    
    269
    +    -- just this thread's breakpoints or its eval result (@False@)
    
    270
    +    -> RemoteRef ThreadId
    
    262 271
         -> Message (EvalStatus [HValueRef])
    
    263 272
     
    
    273
    +  -- | Throw a serializable exception to the given thread
    
    274
    +  ThrowToThread
    
    275
    +    :: RemoteRef ThreadId
    
    276
    +    -> SerializableException
    
    277
    +    -> Message ()
    
    278
    +
    
    264 279
       -- | User-defined request encoded as a tag/payload pair.  This is left
    
    265 280
       -- uninterpreted by GHC and is meant for GHC API applications to be able to supply
    
    266 281
       -- their own interpreter which understands additional commands.
    
    ... ... @@ -295,20 +310,22 @@ resultRemoteResources msg res = case msg of
    295 310
       PrepFFI{}                 -> [RemoteFFI res]
    
    296 311
       LookupClosure{}           -> map RemoteHValueRef $ toList res
    
    297 312
       CreateBCOs{}              -> map RemoteHValueRef $ res
    
    298
    -  EvalStmt{}                -> map RemoteHValueRef $ evalStatus id res
    
    299
    -  ResumeStmt{}              -> map RemoteHValueRef $ evalStatus id res
    
    300 313
       NewBreakArray{}           -> map RemoteHValueRef $ [castRemoteRef res]
    
    301 314
       GetBreakpointVar{}        -> map RemoteHValueRef $ toList res
    
    302 315
       StartTH{}                 -> [RemoteHValueRef $ castRemoteRef res]
    
    303 316
       GetClosure{}              -> map RemoteHValueRef $ toList res
    
    304
    -  Seq{}                     -> map RemoteHValueRef $ evalStatus (const []) res
    
    305
    -  ResumeSeq{}               -> map RemoteHValueRef $ evalStatus (const []) res
    
    306 317
       AddLibrarySearchPath{}    -> [RemoteLibrarySearchPath res]
    
    318
    +  WaitThreadResult{}        -> map RemoteHValueRef $ evalStatus id res
    
    319
    +  EvalStmt{}                -> [RemoteHValueRef $ castRemoteRef res]
    
    320
    +  Seq{}                     -> [RemoteHValueRef $ castRemoteRef res]
    
    307 321
     
    
    308 322
       (CustomMessage _ _ CustomMessageMethods{..})
    
    309 323
                                 -> customResultRemoteResources res
    
    310 324
       (CustomMessage _ _ Deserialized)
    
    311 325
                                 -> error "resultRemoteRefs on deserialized CustomMessage"
    
    326
    +  -- resume returns ()
    
    327
    +  ResumeStmt{}              -> []
    
    328
    +  ResumeSeq{}               -> []
    
    312 329
     
    
    313 330
       -- 'LoadDLLs' is idempotent.
    
    314 331
       LoadDLLs{}                -> []
    
    ... ... @@ -343,6 +360,7 @@ resultRemoteResources msg res = case msg of
    343 360
       RunModFinalizers{}        -> []
    
    344 361
       WhereFrom{}               -> []
    
    345 362
       FreeRemoteResources{}     -> []
    
    363
    +  ThrowToThread{}           -> []
    
    346 364
       where
    
    347 365
         evalStatus :: (b -> [HValueRef]) -> EvalStatus b -> [HValueRef]
    
    348 366
         evalStatus f = \case
    
    ... ... @@ -694,6 +712,8 @@ getMessage = do
    694 712
           41 -> Msg <$> (AddHpcModule <$> get <*> get <*> get <*> get)
    
    695 713
           42 -> Msg <$> (CustomMessage <$> get <*> get <*> pure Deserialized)
    
    696 714
           43 -> Msg <$> (FreeRemoteResources <$> get)
    
    715
    +      44 -> Msg <$> (WaitThreadResult <$> get <*> get)
    
    716
    +      45 -> Msg <$> (ThrowToThread <$> get <*> get)
    
    697 717
           _  -> error $ "Unknown Message code " ++ (show b)
    
    698 718
     
    
    699 719
     putMessage :: Message a -> Put
    
    ... ... @@ -743,6 +763,8 @@ putMessage m = case m of
    743 763
       AddHpcModule m n h ticks    -> putWord8 41 >> put m >> put n >> put h >> put ticks
    
    744 764
       CustomMessage tag payload _ -> putWord8 42 >> put tag >> put payload
    
    745 765
       FreeRemoteResources ps      -> putWord8 43 >> put ps
    
    766
    +  WaitThreadResult b tid      -> putWord8 44 >> put b >> put tid
    
    767
    +  ThrowToThread tid e         -> putWord8 45 >> put tid >> put e
    
    746 768
     
    
    747 769
     {-
    
    748 770
     Note [Parallelize CreateBCOs serialization]
    

  • libraries/ghci/GHCi/Run.hs
    ... ... @@ -49,7 +49,6 @@ import GHC.Stack
    49 49
     import Foreign hiding (void)
    
    50 50
     import Foreign.C
    
    51 51
     import GHC.Conc.Sync
    
    52
    -import GHC.IO hiding ( bracket )
    
    53 52
     import System.Mem.Weak  ( deRefWeak )
    
    54 53
     import Unsafe.Coerce
    
    55 54
     
    
    ... ... @@ -130,7 +129,10 @@ run m = case m of
    130 129
         InfoProv.whereFrom =<< localRef ref
    
    131 130
       Seq ref -> doSeq ref
    
    132 131
       ResumeSeq ref -> resumeSeq ref
    
    133
    -
    
    132
    +  WaitThreadResult b tid -> waitThreadResult b tid
    
    133
    +  ThrowToThread ref e -> do
    
    134
    +    tid <- localRef ref
    
    135
    +    throwTo tid (fromSerializableException e)
    
    134 136
       Shutdown            -> unexpectedMessage m
    
    135 137
       RunTH {}            -> unexpectedMessage m
    
    136 138
       RunModFinalizers {} -> unexpectedMessage m
    
    ... ... @@ -214,7 +216,7 @@ tryEval io = do
    214 216
     
    
    215 217
     --------------------------------------------------------------------------------
    
    216 218
     
    
    217
    -evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (EvalStatus [HValueRef])
    
    219
    +evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (RemoteRef ThreadId)
    
    218 220
     evalStmt opts expr = do
    
    219 221
       io <- mkIO expr
    
    220 222
       sandboxIO opts $ do
    
    ... ... @@ -256,7 +258,7 @@ evalStringToString r str = do
    256 258
     -- The UI process has more and therefore also can show more
    
    257 259
     -- information about the breakpoint than the current iserv
    
    258 260
     -- process.
    
    259
    -doSeq :: RemoteRef a -> IO (EvalStatus [HValueRef])
    
    261
    +doSeq :: RemoteRef a -> IO (RemoteRef ThreadId)
    
    260 262
     doSeq ref = do
    
    261 263
         sandboxIO evalOptsSeq $ do
    
    262 264
           _ <- (void $ evaluate =<< localRef ref)
    
    ... ... @@ -264,7 +266,7 @@ doSeq ref = do
    264 266
     
    
    265 267
     -- | Process a ResumeSeq message. Continue the :force processing     #2950
    
    266 268
     -- after a breakpoint.
    
    267
    -resumeSeq :: RemoteRef ThreadId -> IO (EvalStatus [HValueRef])
    
    269
    +resumeSeq :: RemoteRef ThreadId -> IO ()
    
    268 270
     resumeSeq = resumeStmt evalOptsSeq
    
    269 271
     
    
    270 272
     evalOptsSeq :: EvalOpts
    
    ... ... @@ -287,20 +289,20 @@ evalOptsSeq = EvalOpts
    287 289
     -- only while we execute the user's code.  We can't afford to lose the final
    
    288 290
     -- 'writeThreadEvalStatus', otherwise deadlock ensues. (#1583, #1922, #1946)
    
    289 291
     
    
    290
    -sandboxIO :: EvalOpts -> IO [HValueRef] -> IO (EvalStatus [HValueRef])
    
    292
    +sandboxIO :: EvalOpts -> IO [HValueRef] -> IO (RemoteRef ThreadId)
    
    291 293
     sandboxIO opts io = do
    
    292 294
         -- Make sure the global breakpoint action is set; and that the interpreter
    
    293 295
         -- main thread doesn't stop at breakpoints in it.
    
    294 296
         -- See Note [Disable breakpoints in certain threads]
    
    295 297
         poke breakPointIOAction globalBreakStablePtr
    
    296
    -    disableThreadBreakpoints =<< myThreadId
    
    298
    +    mytid <- myThreadId
    
    299
    +    disableThreadBreakpoints mytid
    
    297 300
     
    
    298
    -    -- We are running in uninterruptibleMask
    
    299 301
         let runIt = measureAlloc $ tryEval $ rethrow opts $ clearCCS io
    
    300 302
         if useSandboxThread opts
    
    301 303
            then do
    
    302 304
     
    
    303
    -         tid <- forkIO $ do
    
    305
    +         tid <- mask_ $ forkIOWithUnmask $ \restore -> do
    
    304 306
                tid <- myThreadId
    
    305 307
                setIsolatedThread tid  -- main thread is always isolated
    
    306 308
                setBreakFlags opts tid -- set flags on the sandbox thread
    
    ... ... @@ -308,13 +310,9 @@ sandboxIO opts io = do
    308 310
                -- We only write the thread status map in two places:
    
    309 311
                -- * When the "main" thread finishes (here)
    
    310 312
                -- * When any thread hits a breakpoint (global break action)
    
    311
    -           unsafeUnmask runIt >>= writeThreadEvalStatus tid
    
    312
    -
    
    313
    -         main <- mkMainThreadWithContext tid
    
    314
    -         atomically $ modifyTVar evaluationMainThreadGlobalVar (main :)
    
    315
    -         redirectInterrupts tid $ unsafeUnmask $
    
    316
    -           atomically $ readEvalStatus opts main
    
    317
    -       else
    
    313
    +           restore runIt >>= writeThreadEvalStatus tid
    
    314
    +         mkRemoteRef tid
    
    315
    +       else do
    
    318 316
               -- GLUT on OS X needs to run on the main thread. If you
    
    319 317
               -- try to use it from another thread then you just get a
    
    320 318
               -- white rectangle rendered. For this, or anything else
    
    ... ... @@ -325,7 +323,12 @@ sandboxIO opts io = do
    325 323
               -- tracing, etc.) need the expression to be running in a
    
    326 324
               -- separate thread, so debugging is only enabled when
    
    327 325
               -- using the sandbox.
    
    328
    -         runIt
    
    326
    +         ctx <- getThreadResumeContext mytid
    
    327
    +         mask $ \restore -> do
    
    328
    +           -- clear the result of a previous eval on the no-sandbox thread
    
    329
    +           atomically $ writeTVar (resumeEvalStatus ctx) ThreadStatusRunning
    
    330
    +           restore runIt >>= writeCtxEvalStatus ctx
    
    331
    +         mkRemoteRef mytid
    
    329 332
     
    
    330 333
     -- We want to turn ^C into a break when -fbreak-on-exception is on,
    
    331 334
     -- but it's an async exception and we only break for sync exceptions.
    
    ... ... @@ -362,34 +365,6 @@ rethrow EvalOpts{..} io =
    362 365
     
    
    363 366
         rethrowIO (ExceptionWithContext cx se)
    
    364 367
     
    
    365
    ---
    
    366
    --- While we're waiting for the sandbox thread to return a result, if
    
    367
    --- the current thread receives an asynchronous exception we re-throw
    
    368
    --- it at the sandbox thread and continue to wait.
    
    369
    ---
    
    370
    --- This is for two reasons:
    
    371
    ---
    
    372
    ---  * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
    
    373
    ---    computation to run its exception handlers before returning the
    
    374
    ---    exception result to the caller of runStmt.
    
    375
    ---
    
    376
    ---  * clients of the GHC API can terminate a runStmt in progress
    
    377
    ---    without knowing the ThreadId of the sandbox thread (#1381)
    
    378
    ---
    
    379
    --- NB. use a weak pointer to the thread, so that the thread can still
    
    380
    --- be considered deadlocked by the RTS and sent a BlockedIndefinitely
    
    381
    --- exception.  A symptom of getting this wrong is that conc033(ghci)
    
    382
    --- will hang.
    
    383
    ---
    
    384
    -redirectInterrupts :: ThreadId -> IO a -> IO a
    
    385
    -redirectInterrupts target wait = do
    
    386
    -  wtid <- mkWeakThreadId target
    
    387
    -  wait `catch` \e -> do
    
    388
    -     m <- deRefWeak wtid
    
    389
    -     case m of
    
    390
    -       Nothing -> wait
    
    391
    -       Just target -> do throwTo target (e :: SomeException); wait
    
    392
    -
    
    393 368
     measureAlloc :: IO (EvalResult a) -> IO (EvalStatus a)
    
    394 369
     measureAlloc io = do
    
    395 370
       setAllocationCounter 0                                 -- #16012
    
    ... ... @@ -439,31 +414,128 @@ Likewise for other interactions between eval/resume/abandon.
    439 414
     TL;DR: always `setBreakFlags` when running/resuming a thread
    
    440 415
     -}
    
    441 416
     
    
    442
    -resumeStmt :: EvalOpts -> RemoteRef ThreadId -> IO (EvalStatus [HValueRef])
    
    417
    +resumeStmt :: EvalOpts -> RemoteRef ThreadId -> IO ()
    
    443 418
     resumeStmt opts rtid = do
    
    444 419
       tid <- localRef rtid
    
    445 420
       ctx <- getThreadResumeContext tid
    
    446 421
       setBreakFlags opts tid
    
    447
    -  main:_ <- readTVarIO evaluationMainThreadGlobalVar
    
    448
    -  mask_ $ do
    
    449
    -    resumeStoppedThread ctx -- this awakens the stopped thread...
    
    450
    -    -- wait for the result of the main thread, not of the stopped one, but
    
    451
    -    -- interrupt the thread which was resumed.
    
    452
    -    redirectInterrupts tid $ unsafeUnmask $
    
    453
    -      atomically $ readEvalStatus opts main
    
    422
    +  resumeStoppedThread ctx -- this awakens the stopped thread...
    
    454 423
     
    
    455 424
     -- | Wait for the given main thread of an evaluation to complete or break or,
    
    456
    --- if 'readAllBreaks', for any other thread to break.
    
    457
    -readEvalStatus :: EvalOpts -> MainThreadWithCtx -> STM (EvalStatus [HValueRef])
    
    458
    -readEvalStatus opts main = do
    
    459
    -  r <- readCtxEvalStatus (mainContext main)
    
    460
    -    & if readAllBreaks opts
    
    425
    +-- if 'readAllBreaks :: Bool', for any other thread to break.
    
    426
    +readEvalStatus :: Bool -> ResumeContext -> STM (EvalStatus [HValueRef])
    
    427
    +readEvalStatus readAllBreaks ctx = do
    
    428
    +  readCtxEvalStatus ctx
    
    429
    +    & if readAllBreaks
    
    461 430
             then (`orElse` (EvalPaused <$> readAnyThreadEvalBreak))
    
    462 431
             else id
    
    463
    -  case r of
    
    464
    -    EvalComplete{} -> popMainThread main
    
    465
    -    EvalPaused{}   -> pure ()
    
    466
    -  pure r
    
    432
    +
    
    433
    +-- | Await the result or breakpoint of a main evaluation thread (started with
    
    434
    +-- 'sandboxIO', unless -fno-ghci-sandbox). If the @readAllBreaks :: Bool@ is
    
    435
    +-- @True@, we may also return breakpoints hit by any other non-sandboxed
    
    436
    +-- threads in the interpreter.
    
    437
    +--
    
    438
    +-- If this function is used on a non-main-eval thread, such as one forked by
    
    439
    +-- the main debuggee that hit a breakpoint, we will only ever return its
    
    440
    +-- breakpoints, as that thread won't write ever an 'EvalComplete' result.
    
    441
    +-- @readAllBreaks@ works the same.
    
    442
    +--
    
    443
    +-- __WARNING__: You very likely want to wrap a call to this function in
    
    444
    +-- 'redirectInterrupts', as in
    
    445
    +-- @
    
    446
    +-- 'redirectInterrupts' tid $
    
    447
    +--    'waitThreadResult' ... tid
    
    448
    +-- @
    
    449
    +-- Because if an asynchronous exception is thrown to the main interpreter
    
    450
    +-- thread, which is awaiting the evaluation result or a breakpoint on another
    
    451
    +-- thread, that exception should be re-throw to that thread to give it a chance
    
    452
    +-- to clean-up. See also Note [interpreter redirectInterrupts and signal handling]
    
    453
    +waitThreadResult :: Bool -> RemoteRef ThreadId -> IO (EvalStatus [HValueRef])
    
    454
    +waitThreadResult readAllBreaks r = do
    
    455
    +  tid <- localRef r
    
    456
    +  ctx <- getThreadResumeContext tid
    
    457
    +  atomically $ readEvalStatus readAllBreaks ctx
    
    458
    +
    
    459
    +{-
    
    460
    +Note [interpreter redirectInterrupts and signal handling]
    
    461
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    462
    +When evaluating a statement at the REPL, the interpreter will do something
    
    463
    +like:
    
    464
    +
    
    465
    +    evalStmt expr = forkIO (expr >>= writeThreadResult mytid)
    
    466
    +
    
    467
    +    tid <- evalStmt <user expr>
    
    468
    +    redirectInterrupts tid $
    
    469
    +       waitThreadResult tid
    
    470
    +
    
    471
    +The 'redirectInterrupts' call is responsible for re-throwing an asynchronous
    
    472
    +expression thrown to the main interpreter thread (which is blocked awaiting for
    
    473
    +the thread result) to the thread that the interpreter thread is blocked on, so
    
    474
    +it has a chance to clean-up properly.
    
    475
    +
    
    476
    +When using the internal interpreter, this is direct: a ^C goes directly to the
    
    477
    +main interpreter thread (GHC's 'withSignalHandlers' redirects signals to the
    
    478
    +ghc execution main thread, which, with the internal interpreter, is also
    
    479
    +running the interpreter commands and is currently blocked waiting for the
    
    480
    +evaluation result).
    
    481
    +
    
    482
    +With the external interpreter, which is a sub-process spawned by the main ghc
    
    483
    +process, if ^C interrupts the ghc process at the terminal, BOTH the main ghc
    
    484
    +process and the external interpreter get the ^C signal (^C at the terminal gets
    
    485
    +sent to all processes in the foreground process group).
    
    486
    +
    
    487
    +Therefore, we disable all signals on the external interpreter process (^C is
    
    488
    +fully ignored on the external interpreter) and, instead, let the main ghc process
    
    489
    +capture ^C and send a message to the external interpreter redirecting this
    
    490
    +interrupt to the thread we were waiting for. The program above, when using the
    
    491
    +external interpreter, under the hood works like:
    
    492
    +
    
    493
    +    tid <- remoteCall (EvalStmt <user expr>)
    
    494
    +    remoteCall (WaitThreadResult tid)
    
    495
    +      `onAsyncException` \e ->
    
    496
    +        remoteCall (ThrowToThread tid (serializeException e))
    
    497
    +        remoteCall (WaitThreadResult tid)
    
    498
    +
    
    499
    +where 'remoteCall' blocks waiting for the external interpreter to
    
    500
    +asynchronously deliver a reply to the given request, and cancels the pending
    
    501
    +request when an exception is thrown while waiting.
    
    502
    +
    
    503
    +This way, when there's a ^C on the main ghc process, we'll cancel the wait
    
    504
    +request (in `remoteCall`) and then send a request to interrupt the remote
    
    505
    +process thread with ^C (in `GHC.Runtime.Interpreter.redirectInterrupts`)
    
    506
    +
    
    507
    +Note: the `ghci` library still exposes a `redirectInterrupts`, in case you want
    
    508
    +to wrap calls to `waitThreadResult` using the ghci library directly; however,
    
    509
    +in ghc, we define `redirectInterrupts` as a function which captures host
    
    510
    +exceptions and sends a 'ThrowToThread' message which is interpreted by
    
    511
    +'throwTo'ing that exception on the interpreter process.
    
    512
    +-}
    
    513
    +
    
    514
    +-- | While we're waiting for the sandbox thread to return a result, if
    
    515
    +-- the current thread receives an asynchronous exception we re-throw
    
    516
    +-- it at the sandbox thread and continue to wait.
    
    517
    +--
    
    518
    +-- This is for two reasons:
    
    519
    +--
    
    520
    +--  * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
    
    521
    +--    computation to run its exception handlers before returning the
    
    522
    +--    exception result to the caller of runStmt.
    
    523
    +--
    
    524
    +--  * clients of the GHC API can terminate a runStmt in progress
    
    525
    +--    without knowing the ThreadId of the sandbox thread (#1381)
    
    526
    +--
    
    527
    +-- NB. use a weak pointer to the thread, so that the thread can still
    
    528
    +-- be considered deadlocked by the RTS and sent a BlockedIndefinitely
    
    529
    +-- exception.  A symptom of getting this wrong is that conc033(ghci)
    
    530
    +-- will hang.
    
    531
    +redirectInterrupts :: ThreadId -> IO a -> IO a
    
    532
    +redirectInterrupts target wait = do
    
    533
    +  wtid <- mkWeakThreadId target
    
    534
    +  wait `catch` \e -> do
    
    535
    +     m <- deRefWeak wtid
    
    536
    +     case m of
    
    537
    +       Nothing -> wait
    
    538
    +       Just target -> do throwTo target (e :: SomeException); wait
    
    467 539
     
    
    468 540
     -- | When abandoning a computation we have to
    
    469 541
     --      (a) kill the stopped thread with an async exception, so that the
    
    ... ... @@ -473,21 +545,15 @@ readEvalStatus opts main = do
    473 545
     --         evaluating a thunk when we stopped at the breakpoint, so the async
    
    474 546
     --         exception makes the thunk resumable from where we stopped instead of
    
    475 547
     --         updating it with an exception (tested in break010).
    
    476
    ---      (c) wait for the main thread to terminate by waiting for its result.
    
    477
    ---          This step is necessary to prevent race conditions with
    
    478
    ---          -fbreak-on-exception (see #5975).
    
    479 548
     --  See test break010 and break034.
    
    549
    +--
    
    550
    +-- If the expression where we're stopped catches asynchronous exceptions it
    
    551
    +-- might catch the `AbandonException` instead of abandoning.
    
    480 552
     abandonStmt :: RemoteRef ThreadId -> IO ()
    
    481 553
     abandonStmt hvref = do
    
    482
    -  main:_ <- readTVarIO evaluationMainThreadGlobalVar
    
    483 554
       tid <- localRef hvref
    
    484 555
       setBreakFlags evalOptsAbandon tid
    
    485
    -  throwTo tid AbandonException -- kill stopped thread, then wait for main thread
    
    486
    -  atomically $
    
    487
    -    readCtxEvalStatus (mainContext main) >>= \case
    
    488
    -      -- throwTo may return before the thread is marked as running
    
    489
    -      EvalPaused{} -> retry
    
    490
    -      EvalComplete{} -> popMainThread main
    
    556
    +  throwTo tid AbandonException -- kill the stopped thread
    
    491 557
       where
    
    492 558
         -- Don't stop anywhere on abandon
    
    493 559
         evalOptsAbandon = EvalOpts
    
    ... ... @@ -504,34 +570,3 @@ data AbandonException = AbandonException deriving Show
    504 570
     instance Exception AbandonException where
    
    505 571
       toException = asyncExceptionToException
    
    506 572
       fromException = asyncExceptionFromException
    507
    -
    
    508
    ---------------------------------------------------------------------------------
    
    509
    --- To remove completely when sandboxIO/resume becomes asynchronous:
    
    510
    ---------------------------------------------------------------------------------
    
    511
    -
    
    512
    --- | The main threads of the exprs being currently evaluated, the most recent
    
    513
    --- first. Evaluating an expr while stopped at a breakpoint pushes its thread on
    
    514
    --- top of the stopped one, until it completes.
    
    515
    ---
    
    516
    --- FIXME: Remove this global variable. It is only needed while `resumeStmt` is
    
    517
    --- synchronous, since `resumeStmt` currently tries to return the Eval result of
    
    518
    --- the main thread (which is a bit non-sensical for a resume operation to do).
    
    519
    --- It is only needed to preserve the previous behavior, but as soon as
    
    520
    --- `evalStmt` returns the sandboxIO thread id we can wait on that explicitly
    
    521
    --- instead of resuming having anything to do with waiting for the main
    
    522
    --- evaluation result.
    
    523
    -evaluationMainThreadGlobalVar :: TVar [MainThreadWithCtx]
    
    524
    -evaluationMainThreadGlobalVar = unsafePerformIO $ newTVarIO []
    
    525
    -{-# NOINLINE evaluationMainThreadGlobalVar #-}
    
    526
    -
    
    527
    --- | (Keep the ResumeContext to reduce allocations, triggered interpreter_steplocal regression)
    
    528
    -data MainThreadWithCtx = MainThreadWithCtx { mainKey :: !Word64, mainContext :: !ResumeContext }
    
    529
    -
    
    530
    -mkMainThreadWithContext :: ThreadId -> IO MainThreadWithCtx
    
    531
    -mkMainThreadWithContext tid = MainThreadWithCtx (fromThreadId tid) <$> getThreadResumeContext tid
    
    532
    -
    
    533
    --- | FIXME: Kill this function, just like 'evaluationMainThreadGlobalVar' will be killed.
    
    534
    -popMainThread :: MainThreadWithCtx -> STM ()
    
    535
    -popMainThread main =
    
    536
    -  modifyTVar evaluationMainThreadGlobalVar (filter ((/= mainKey main) . mainKey))
    
    537
    -

  • libraries/ghci/GHCi/Server.hs
    ... ... @@ -54,18 +54,17 @@ noCustomHandler _ _ = return Nothing
    54 54
     trace :: String -> IO ()
    
    55 55
     trace s = getProgName >>= \name -> hPrintf stderr "[%20s] %s\n" name s
    
    56 56
     
    
    57
    -serv :: Bool -> MessageHook -> Pipe -> (forall a .IO a -> IO a) -> IO ()
    
    58
    -serv verbose hook pipe restore =
    
    59
    -  servWithCustom verbose hook pipe restore noCustomHandler
    
    57
    +serv :: Bool -> MessageHook -> Pipe -> IO ()
    
    58
    +serv verbose hook pipe =
    
    59
    +  servWithCustom verbose hook pipe noCustomHandler
    
    60 60
     
    
    61 61
     servWithCustom
    
    62 62
       :: Bool
    
    63 63
       -> MessageHook
    
    64 64
       -> Pipe
    
    65
    -  -> (forall a. IO a -> IO a)
    
    66 65
       -> CustomMessageHandler
    
    67 66
       -> IO ()
    
    68
    -servWithCustom verbose hook pipe restore customHandler = do
    
    67
    +servWithCustom verbose hook pipe customHandler = do
    
    69 68
       ref <- newIORef False
    
    70 69
       withThreadManager $ \mngr -> handle @PipeClosedException (const $ pure ()) $ do
    
    71 70
         loop ref mngr `finally` closePipe pipe
    
    ... ... @@ -75,7 +74,6 @@ servWithCustom verbose hook pipe restore customHandler = do
    75 74
     
    
    76 75
         handleRemoteCall pipe hook $ \wr setCancel (msg :: Message a) ->
    
    77 76
     
    
    78
    -      discardCtrlC                                 %>>= \_ ->
    
    79 77
           when verbose (trace ("msg: " ++ (show msg))) %>>= \_ ->
    
    80 78
     
    
    81 79
           case msg of
    
    ... ... @@ -83,12 +81,29 @@ servWithCustom verbose hook pipe restore customHandler = do
    83 81
             Shutdown                  -> writeIORef doneRef True >> closingPipe pipe >>
    
    84 82
                                          reply ()                %>>= \r ->
    
    85 83
                                          runWriteReply wr (Right r) ignorePipeClosedException
    
    84
    +
    
    85
    +        -- Run splices concurrently without blocking the server thread
    
    86 86
             RunTH ii st q ty loc      -> handleAsync wr
    
    87
    -                                     (restore $ wrapRunTH ii (runTH pipe ii st q ty loc))
    
    87
    +                                     (wrapRunTH ii (runTH pipe ii st q ty loc))
    
    88 88
                                          (setCancel . void . forkIO . killThread)
    
    89 89
             RunModFinalizers ii st qs -> handleAsync wr
    
    90
    -                                     (restore $ wrapRunTH ii (runModFinalizerRefs pipe ii st qs))
    
    90
    +                                     (wrapRunTH ii (runModFinalizerRefs pipe ii st qs))
    
    91
    +                                     (setCancel . void . forkIO . killThread)
    
    92
    +
    
    93
    +        -- Wait off the main thread and reply asynchronously once ready. This
    
    94
    +        -- wait thread is killed if the wait request is cancelled, but a result
    
    95
    +        -- of the target thread can still be read e.g. with a follow-up wait.
    
    96
    +        -- If the target thread should be killed, see 'ThrowToThread'.
    
    97
    +        -- See Note [interpreter redirectInterrupts and signal handling] for both.
    
    98
    +        WaitThreadResult{}        -> handleAsync wr
    
    99
    +                                     (run msg >>= reply)
    
    100
    +                                     (setCancel . void . forkIO . killThread)
    
    101
    +        -- Run throwTo off the main thread in case the user program behaves
    
    102
    +        -- "badly" wrt async exceptions.
    
    103
    +        ThrowToThread{}           -> handleAsync wr
    
    104
    +                                     (run msg >>= reply)
    
    91 105
                                          (setCancel . void . forkIO . killThread)
    
    106
    +
    
    92 107
             _other                    -> run msg >>= reply        %>>= writeReply wr
    
    93 108
     
    
    94 109
         isDone <- readIORef doneRef
    
    ... ... @@ -157,17 +172,6 @@ servWithCustom verbose hook pipe restore customHandler = do
    157 172
            Left e -> showException e
    
    158 173
            Right str -> return str
    
    159 174
     
    
    160
    -  -- throw away any pending ^C exceptions while we're not running
    
    161
    -  -- interpreted code.  GHC will also get the ^C, and either ignore it
    
    162
    -  -- (if this is GHCi), or tell us to quit with a Shutdown message.
    
    163
    -  discardCtrlC = do
    
    164
    -    when verbose $ trace "discardCtrlC"
    
    165
    -    r <- try $ restore $ return ()
    
    166
    -    case r of
    
    167
    -      Left UserInterrupt -> return () >> discardCtrlC
    
    168
    -      Left e -> throwIO e
    
    169
    -      _ -> return ()
    
    170
    -
    
    171 175
     -- | Default server
    
    172 176
     #if defined(wasm32_HOST_ARCH)
    
    173 177
     defaultServer :: Callback (JSVal -> IO ()) -> Callback (IO JSUint8Array) -> Callback (JSUint8Array -> IO ()) -> IO ()
    
    ... ... @@ -212,12 +216,12 @@ defaultServerWithCustom customHandler = do
    212 216
     
    
    213 217
     #if defined(wasm32_HOST_ARCH)
    
    214 218
       -- See Note [wasm ghci signal handlers] for details
    
    215
    -  installSignalHandlers $ js_register_signal_handler cb_sig
    
    219
    +  ignoreInterrupts $ js_register_signal_handler cb_sig
    
    216 220
       pipe <- mkPipeFromContinuations (recv_buf cb_recv) (send_buf cb_send) (pure ()) (pure ())
    
    217 221
     #else
    
    218 222
       when verbose $
    
    219 223
         printf "GHC iserv starting (in: %s; out: %s)\n" (show inh) (show outh)
    
    220
    -  installSignalHandlers
    
    224
    +  ignoreInterrupts
    
    221 225
       pipe <- mkPipeFromHandles inh outh
    
    222 226
     #endif
    
    223 227
     
    
    ... ... @@ -226,11 +230,9 @@ defaultServerWithCustom customHandler = do
    226 230
           putStrLn "Waiting 3s"
    
    227 231
         threadDelay 3000000
    
    228 232
     
    
    229
    -  uninterruptibleMask $ \restore -> servWithCustom verbose hook pipe restore customHandler
    
    233
    +  servWithCustom verbose hook pipe customHandler
    
    230 234
     
    
    231 235
       where hook = return -- empty hook
    
    232
    -    -- we cannot allow any async exceptions while communicating, because
    
    233
    -    -- we will lose sync in the protocol, hence uninterruptibleMask.
    
    234 236
     
    
    235 237
     dieWithUsage :: IO a
    
    236 238
     dieWithUsage = do
    

  • libraries/ghci/GHCi/Signals.hs
    1 1
     {-# LANGUAGE CPP #-}
    
    2
    -module GHCi.Signals (installSignalHandlers) where
    
    2
    +module GHCi.Signals (ignoreInterrupts) where
    
    3 3
     
    
    4 4
     import Prelude -- See note [Why do we import Prelude here?]
    
    5
    -import Control.Concurrent
    
    6
    -import Control.Exception
    
    7
    -import System.Mem.Weak  ( deRefWeak )
    
    8 5
     
    
    9 6
     #if defined(wasm32_HOST_ARCH)
    
    10 7
     import GHC.Wasm.Prim
    
    ... ... @@ -16,55 +13,34 @@ import System.Posix.Signals
    16 13
     import GHC.ConsoleHandler
    
    17 14
     #endif
    
    18 15
     
    
    19
    --- | Install standard signal handlers for catching ^C, which just throw an
    
    20
    ---   exception in the target thread.  The current target thread is the
    
    21
    ---   thread at the head of the list in the MVar passed to
    
    22
    ---   installSignalHandlers.
    
    16
    +-- | Install standard signal handlers for catching ^C, which just ignore it.
    
    17
    +-- See Note [interpreter redirectInterrupts and signal handling].
    
    23 18
     #if defined(wasm32_HOST_ARCH)
    
    24
    -installSignalHandlers :: (JSVal -> IO ()) -> IO ()
    
    25
    -installSignalHandlers cb_sig = do
    
    26
    -#else
    
    27
    -installSignalHandlers :: IO ()
    
    28
    -installSignalHandlers = do
    
    29
    -#endif
    
    30
    -  main_thread <- myThreadId
    
    31
    -  wtid <- mkWeakThreadId main_thread
    
    32
    -
    
    33
    -  let interrupt = do
    
    34
    -        r <- deRefWeak wtid
    
    35
    -        case r of
    
    36
    -          Nothing -> return ()
    
    37
    -          Just t  -> throwTo t UserInterrupt
    
    38
    -
    
    39
    -#if defined(wasm32_HOST_ARCH)
    
    40
    -  cb_sig =<< js_export_signal_handler interrupt
    
    19
    +ignoreInterrupts :: (JSVal -> IO ()) -> IO ()
    
    20
    +ignoreInterrupts cb_sig = do
    
    21
    +  -- See Note [wasm ghci signal handlers]
    
    22
    +  cb_sig =<< js_export_signal_handler (return ())
    
    41 23
     #elif !defined(mingw32_HOST_OS)
    
    42
    -  _ <- installHandler sigQUIT  (Catch interrupt) Nothing
    
    43
    -  _ <- installHandler sigINT   (Catch interrupt) Nothing
    
    24
    +ignoreInterrupts :: IO ()
    
    25
    +ignoreInterrupts = do
    
    26
    +  -- use `Catch (return ())` instead of `Ignore`, because `Ignore` gets
    
    27
    +  -- inherited by subprocesses the server may spawn.
    
    28
    +  _ <- installHandler sigQUIT (Catch (return ())) Nothing
    
    29
    +  _ <- installHandler sigINT  (Catch (return ())) Nothing
    
    30
    +  return ()
    
    44 31
     #else
    
    45
    -  -- GHC 6.3+ has support for console events on Windows
    
    46
    -  -- NOTE: running GHCi under a bash shell for some reason requires
    
    47
    -  -- you to press Ctrl-Break rather than Ctrl-C to provoke
    
    48
    -  -- an interrupt.  Ctrl-C is getting blocked somewhere, I don't know
    
    49
    -  -- why --SDM 17/12/2004
    
    50
    -  let sig_handler ControlC = interrupt
    
    51
    -      sig_handler Break    = interrupt
    
    52
    -      sig_handler _        = return ()
    
    53
    -
    
    54
    -  _ <- installHandler (Catch sig_handler)
    
    55
    -#endif
    
    32
    +ignoreInterrupts :: IO ()
    
    33
    +ignoreInterrupts = do
    
    34
    +  _ <- installHandler (Catch (\_ -> return ()))
    
    56 35
       return ()
    
    36
    +#endif
    
    57 37
     
    
    58 38
     #if defined(wasm32_HOST_ARCH)
    
    59
    -
    
    60 39
     -- Note [wasm ghci signal handlers]
    
    61 40
     -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    62
    ---
    
    63 41
     -- For native ghc with -fexternal-interpreter, when you press ^C,
    
    64
    --- SIGINT is delivered to both ghc/iserv. iserv SIGINT handler raises
    
    65
    --- an async UserInterrupt exception in the main thread, which might
    
    66
    --- handle it right away, or later since it's doing I/O under
    
    67
    --- uninterruptibleMask.
    
    42
    +-- SIGINT is delivered to both ghc/iserv. iserv SIGINT handler simply
    
    43
    +-- ignores the SIGINT (see Note [interpreter redirectInterrupts and signal handling]).
    
    68 44
     --
    
    69 45
     -- wasm is no different here. The node process needs to catch the same
    
    70 46
     -- signals. Instead of calling process.on('SIGINT', handler) in
    
    ... ... @@ -73,15 +49,7 @@ installSignalHandlers = do
    73 49
     -- callback to register the handler. This allows iserv to be run in
    
    74 50
     -- non-nodejs environments as well, and the dyld script can pass a
    
    75 51
     -- handler register callback other than process.on().
    
    76
    ---
    
    77
    --- IMPORTANT: THE SIGNAL HANDLER MUST BE EXPORTED AS ASYNC!!!!!!!
    
    78
    --- Otherwise, throwTo may block the handler thread, so the handler
    
    79
    --- thread is removed from the run queue. Since the main thread may
    
    80
    --- also be absent from the run queue (e.g. blocked on waiting for
    
    81
    --- input message), the run queue is empty and then the RTS scheduler
    
    82
    --- panics.
    
    83 52
     
    
    84 53
     foreign import javascript "wrapper"
    
    85 54
       js_export_signal_handler :: IO () -> IO JSVal
    
    86
    -
    
    87 55
     #endif

  • testsuite/tests/concurrent/should_run/all.T
    ... ... @@ -168,7 +168,11 @@ test('conc030', extra_run_opts('+RTS -K4M -RTS'), compile_and_run, [''])
    168 168
     test('conc031', exit_code(1), compile_and_run, [''])
    
    169 169
     
    
    170 170
     test('conc032', normal, compile_and_run, [''])
    
    171
    -test('conc033', when(config.have_ext_interp, extra_ways(['ghci-ext'])), compile_and_run, [''])
    
    171
    +# You don't get any guarantee that the RTS ever throws a BlockedIndefinitely
    
    172
    +# exception, so it's fine if ghci doesn't throw one to the sandboxed thread.
    
    173
    +test('conc033', [when(config.have_ext_interp, extra_ways(['ghci-ext'])),
    
    174
    +                 expect_fail_for(['ghci-ext'])],
    
    175
    +     compile_and_run, [''])
    
    172 176
     
    
    173 177
     # Omit for GHCi, because it just sits there waiting for you to press ^C
    
    174 178
     test('conc034', [
    

  • testsuite/tests/ghc-api/T8628.hs
    1 1
     module Main where
    
    2 2
     
    
    3
    +import Control.Monad (join)
    
    3 4
     import System.IO
    
    4 5
     import GHC.Driver.Session
    
    5 6
     import GHC
    
    ... ... @@ -25,10 +26,10 @@ main
    25 26
               setContext [ IIDecl (simpleImportDecl pRELUDE_NAME)
    
    26 27
                          , IIDecl (simpleImportDecl (mkModuleNameFS (fsLit "System.IO")))]
    
    27 28
               runDecls "data X = Y ()"
    
    28
    -          execStmt "print True" execOptions
    
    29
    -          MC.try $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult)
    
    29
    +          join $ execStmt "print True" execOptions
    
    30
    +          MC.try $ join $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult)
    
    30 31
               runDecls "data X = Y () deriving Show"
    
    31 32
               _ <- dynCompileExpr "'x'"
    
    32
    -          execStmt "print (Y ())" execOptions
    
    33
    -          execStmt "System.IO.hFlush System.IO.stdout" execOptions
    
    33
    +          join $ execStmt "print (Y ())" execOptions
    
    34
    +          join $ execStmt "System.IO.hFlush System.IO.stdout" execOptions
    
    34 35
             print "done"

  • testsuite/tests/ghc-api/T8639_api.hs
    1 1
     module Main where
    
    2 2
     
    
    3
    +import Control.Monad (join)
    
    3 4
     import GHC
    
    4 5
     import GHC.Driver.Monad
    
    5 6
     import GHC.Driver.Ppr
    
    ... ... @@ -20,8 +21,8 @@ main
    20 21
     
    
    21 22
                -- With the next line, you get an "Not in scope" exception.
    
    22 23
                -- If you comment out this runStmt, it runs without error and prints the  type.
    
    23
    -           execStmt "putStrLn (show 3)" execOptions
    
    24
    -           execStmt "hFlush stdout" execOptions
    
    24
    +           join $ execStmt "putStrLn (show 3)" execOptions
    
    25
    +           join $ execStmt "hFlush stdout" execOptions
    
    25 26
     
    
    26 27
                ty <- exprType TM_Inst "T8639_api_a.it"
    
    27 28
                liftIO (putStrLn (showPpr flags ty))
    

  • testsuite/tests/ghc-api/apirecomp001/myghc.hs
    ... ... @@ -50,7 +50,7 @@ main = do
    50 50
         setContext [IIModule mod]
    
    51 51
         liftIO $ hFlush stdout  -- make sure things above are printed before
    
    52 52
                                 -- interactive output
    
    53
    -    r <- execStmt "main" execOptions
    
    53
    +    r <- join $ execStmt "main" execOptions
    
    54 54
         case r of
    
    55 55
           ExecComplete { execResult = Right _ } -> prn "ok"
    
    56 56
           ExecComplete { execResult = Left _ } -> prn "exception"
    

  • testsuite/tests/ghci.debugger/scripts/break037.hs
    1 1
     module Main where
    
    2 2
     
    
    3
    +import Control.Concurrent
    
    3 4
     import Control.Exception
    
    5
    +import System.IO.Unsafe
    
    6
    +
    
    7
    +cleanupDone :: MVar ()
    
    8
    +cleanupDone = unsafePerformIO newEmptyMVar
    
    9
    +{-# NOINLINE cleanupDone #-}
    
    4 10
     
    
    5 11
     f :: () -> IO ()
    
    6 12
     f () = throwIO (ErrorCall "boom") `finally` g ()
    
    7 13
     
    
    8 14
     g :: () -> IO ()
    
    9
    -g () = putStrLn "cleanup"
    
    15
    +g () = putStrLn "cleanup" >> putMVar cleanupDone ()
    
    10 16
     
    
    11 17
     main :: IO ()
    
    12 18
     main = f ()

  • testsuite/tests/ghci.debugger/scripts/break037.script
    ... ... @@ -6,4 +6,5 @@
    6 6
     :step
    
    7 7
     -- Running the cleanup in g while abandoning must not hit a breakpoint
    
    8 8
     :abandon
    
    9
    -putStrLn "after abandon"
    9
    +-- :abandon does not wait for the cleanup, so wait for it explicitly
    
    10
    +takeMVar cleanupDone >> putStrLn "after abandon"

  • testsuite/tests/ghci.debugger/scripts/break037.stdout
    1
    -Stopped in Main.f, break037.hs:6:8-48
    
    1
    +Stopped in Main.f, break037.hs:12:8-48
    
    2 2
     _result :: IO () = _
    
    3
    -Stopped in Main.f, break037.hs:6:8-33
    
    3
    +Stopped in Main.f, break037.hs:12:8-33
    
    4 4
     _result :: IO () = _
    
    5 5
     Stopped in <exception thrown>, <unknown>
    
    6 6
     _exception :: e = _
    

  • testsuite/tests/ghci.debugger/scripts/break050ext.stdout
    ... ... @@ -4,4 +4,3 @@ _result :: IO () = _
    4 4
     x :: Int = 0
    
    5 5
     forked thread: user interrupt
    
    6 6
     main was not interrupted
    7
    -Interrupted.

  • testsuite/tests/ghci/interp-cancellation/Main.hs
    ... ... @@ -10,7 +10,7 @@ module Main (main) where
    10 10
     
    
    11 11
     import Control.Concurrent (forkIO, killThread, threadDelay)
    
    12 12
     import Control.Concurrent.MVar (newMVar, readMVar)
    
    13
    -import Control.Exception (SomeException, bracket, handle, uninterruptibleMask)
    
    13
    +import Control.Exception (SomeException, bracket, handle)
    
    14 14
     import Control.Monad (replicateM, unless, void)
    
    15 15
     import Data.Binary (Binary)
    
    16 16
     import qualified Data.ByteString.Char8 as BC
    
    ... ... @@ -109,9 +109,7 @@ runServer [wfd, rfd, notifyFd, goFd] = do
    109 109
       goH     <- readGhcHandle ReadMode  goFd
    
    110 110
       prepareGateHandles [notifyH, goH]
    
    111 111
       pipe <- mkPipeFromHandles inh outh
    
    112
    -  -- As in 'defaultServer': we cannot take an async exception while
    
    113
    -  -- communicating, or we lose sync in the protocol.
    
    114
    -  uninterruptibleMask $ \restore -> serv False (gateHook notifyH goH) pipe restore
    
    112
    +  serv False (gateHook notifyH goH) pipe
    
    115 113
     runServer args =
    
    116 114
       die $ "server: expected <write-fd> <read-fd> <notify-fd> <go-fd>, got "
    
    117 115
               ++ unwords args