[Git][ghc/ghc][wip/romes/async-eval-resume] WIP: Start Async Eval/Resume
Rodrigo Mesquita pushed to branch wip/romes/async-eval-resume at Glasgow Haskell Compiler / GHC Commits: a7f092c0 by Rodrigo Mesquita at 2026-11-29T10:13:06+00:00 WIP: Start Async Eval/Resume TODO: - Commit description - Reference Note in commit description - Explain "Interrupted" no longer in testsuite: GHCi's top level printed that line because ghc's own ^C went uncaught; it's gone because ghc's redirectInterrupts now catches the ^C and keeps waiting. TODO: Add to changelog information about how to use the new execStmt/resumeStmt, which return an action that when run blocks waiting for the result. Notes: - The async eval/resume design requires an interpreter sandbox ThreadId to be held by the host program. Therefore, we won't be able to detect a deadlock in a sandboxed thread and won't send a BlockedIndefinitely, so conc033 won't work on the ghci way. This is acceptable because BlockedIndefinitely is a debug mechanism, and the RTS doesn't guarantee that it is thrown. WIP TICKET DESCRIPTION: Title: Asynchronous evalStmt/resumeStmt interpreter interface Description: After #28124 (global break action) and #27960 (asynchronous ext interpreter RPC), we can adapt the interpreter `evalStmt` and `resumeStmt` functions from `GHC.Runtime.Interpreter` to be more asynchronous in the sense that we don't need to block immediately waiting for the evaluation result, or for a resumed evaluation result. - - - - - 13 changed files: - compiler/GHC/Runtime/Eval.hs - compiler/GHC/Runtime/Eval/Types.hs - compiler/GHC/Runtime/Interpreter.hs - ghc/GHCi/UI/Monad.hs - libraries/ghci/GHCi/Message.hs - libraries/ghci/GHCi/Run.hs - libraries/ghci/GHCi/Server.hs - libraries/ghci/GHCi/Signals.hs - testsuite/tests/concurrent/should_run/all.T - testsuite/tests/ghc-api/T8628.hs - testsuite/tests/ghc-api/T8639_api.hs - testsuite/tests/ghc-api/apirecomp001/myghc.hs - testsuite/tests/ghci.debugger/scripts/break050ext.stdout Changes: ===================================== compiler/GHC/Runtime/Eval.hs ===================================== @@ -43,6 +43,7 @@ module GHC.Runtime.Eval ( ) where import GHC.Prelude +import GHC.Conc import GHC.Driver.Monad import GHC.Driver.Main @@ -186,12 +187,13 @@ execOptions = ExecOptions , execWrap = EvalThis -- just run the statement, don't wrap it in anything } --- | Run a statement in the current interactive context. +-- | Run a statement in the current interactive context, as a new thread in the interpreter. +-- Returns an action which blocks waiting for the execution to finish and yield a result. execStmt :: GhcMonad m => String -- ^ a statement (bind or expression) -> ExecOptions - -> m ExecResult + -> m (m ExecResult) execStmt input exec_opts@ExecOptions{..} = do hsc_env <- getSession @@ -202,13 +204,15 @@ execStmt input exec_opts@ExecOptions{..} = do case mb_stmt of -- empty statement / comment - Nothing -> return (ExecComplete (Right []) 0) + Nothing -> return (return (ExecComplete (Right []) 0)) Just stmt -> execStmt' stmt input exec_opts -- | Like `execStmt`, but takes a parsed statement as argument. Useful when -- doing preprocessing on the AST before execution, e.g. in GHCi (see -- GHCi.UI.runStmt). -execStmt' :: GhcMonad m => GhciLStmt GhcPs -> String -> ExecOptions -> m ExecResult +-- +-- Returns an action which blocks waiting for the execution to finish and yield a result. +execStmt' :: GhcMonad m => GhciLStmt GhcPs -> String -> ExecOptions -> m (m ExecResult) execStmt' stmt stmt_text ExecOptions{..} = do hsc_env <- getSession let interp = hscInterp hsc_env @@ -224,20 +228,22 @@ execStmt' stmt stmt_text ExecOptions{..} = do case r of Nothing -> -- empty statement / comment - return (ExecComplete (Right []) 0) + return (return (ExecComplete (Right []) 0)) Just (ids, hval, fix_env) -> do updateFixityEnv fix_env let eval_opts = initEvalOpts idflags' (enableGhcStepMode execSingleStep) - status <- liftIO $ evalStmt interp eval_opts (execWrap hval) + main_tid <- liftIO $ evalStmt interp eval_opts (execWrap hval) let ic = hsc_IC hsc_env bindings = (ic_tythings ic, ic_gre_cache ic) size = ghciHistSize idflags' - handleRunStatus execSingleStep eval_opts stmt_text bindings ids - status (emptyHistory size) + pure $ do + status <- liftIO $ waitThreadResult interp main_tid eval_opts main_tid + handleRunStatus execSingleStep eval_opts stmt_text bindings ids + status (emptyHistory size) main_tid runDecls :: GhcMonad m => String -> m [TyThing] runDecls = runDeclsWithLocation "<interactive>" 1 @@ -300,8 +306,10 @@ handleRunStatus :: GhcMonad m -> [Id] -> EvalStatus [ForeignHValue] -> BoundedList History + -> ForeignRef ThreadId + -- ^ The thread started by evalStmt to run this evaluation -> m ExecResult -handleRunStatus step eval_opts expr bindings final_ids status history0 = do +handleRunStatus step eval_opts expr bindings final_ids status history0 main_tid = do hsc_env <- getSession let interp = hscInterp hsc_env @@ -342,6 +350,7 @@ handleRunStatus step eval_opts expr bindings final_ids status history0 = do , resumeDecl = "<exception thrown>" , resumeCCS = ccs , resumeHistoryIx = 0 + , resumeMainThread = main_tid } hsc_env2 = pushResume hsc_env1 resume @@ -389,19 +398,22 @@ handleRunStatus step eval_opts expr bindings final_ids status history0 = do , resumeDecl = decl , resumeCCS = ccs , resumeHistoryIx = 0 + , resumeMainThread = main_tid } hsc_env2 = pushResume hsc_env1 resume setSession hsc_env2 return (ExecBreak break_ids (Just ibi) resume) else do -- resume with the same step type - status <- liftIO $ GHCi.resumeStmt interp eval_opts resume_ctxt_fhv + liftIO $ GHCi.resumeStmt interp eval_opts resume_ctxt_fhv + -- Redirect exceptions to the resumed thread, but await the main thread: + status <- liftIO $ waitThreadResult interp resume_ctxt_fhv eval_opts main_tid history <- if not tracing then pure history0 else do history1 <- liftIO $ mkHistory hug apStack_fhv ibi let !history' = history1 `consBL` history0 -- history is strict, otherwise our BoundedList is pointless. return history' - handleRunStatus step eval_opts expr bindings final_ids status history + handleRunStatus step eval_opts expr bindings final_ids status history main_tid where tracing | RunAndLogSteps <- step = True | otherwise = False @@ -418,7 +430,10 @@ resumeExec :: GhcMonad m => SingleStep -> Maybe Int -> Resume - -> m ExecResult + -> m (m ExecResult) + -- ^ Returns an action which blocks waiting for the execution of + -- this @'Resume'@'s @'resumeMainThread'@ to finish and yield another + -- breakpoint or result. resumeExec step mbCnt r = do hsc_env <- getSession let ic = hsc_IC hsc_env @@ -447,7 +462,9 @@ resumeExec step mbCnt r = do , resumeApStack = apStack , resumeBreakpointId = mb_brkpt , resumeSpan = span - , resumeHistory = hist } -> + , resumeHistory = hist + , resumeMainThread = main_tid + } -> do -- When the user specified a break ignore count, set it -- in the interpreter @@ -456,17 +473,19 @@ resumeExec step mbCnt r = do _ -> return () let eval_opts = initEvalOpts dflags (enableGhcStepMode step) - status <- liftIO $ GHCi.resumeStmt interp eval_opts fhv - let prevHistoryLst = fromListBL 50 hist - hug = hsc_HUG hsc_env - hist' = case mb_brkpt of - Nothing -> pure prevHistoryLst - Just bi - | breakHere False step span -> do - hist1 <- liftIO (mkHistory hug apStack bi) - return $ hist1 `consBL` fromListBL 50 hist - | otherwise -> pure prevHistoryLst - handleRunStatus step eval_opts expr bindings final_ids status =<< hist' + liftIO $ GHCi.resumeStmt interp eval_opts fhv + pure $ do + status <- liftIO $ waitThreadResult interp fhv eval_opts main_tid + let prevHistoryLst = fromListBL 50 hist + hug = hsc_HUG hsc_env + hist_val <- case mb_brkpt of + Nothing -> pure prevHistoryLst + Just bi + | breakHere False step span -> do + hist1 <- liftIO (mkHistory hug apStack bi) + return $ hist1 `consBL` fromListBL 50 hist + | otherwise -> pure prevHistoryLst + handleRunStatus step eval_opts expr bindings final_ids status hist_val main_tid setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157 setupBreakpoint interp ibi cnt = do @@ -1278,7 +1297,8 @@ compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do updateFixityEnv fix_env -- Only this expression's result is expected, never another thread's break let eval_opts = (initEvalOpts dflags EvalStepNone) { readAllBreaks = False } - status <- liftIO $ evalStmt interp eval_opts (EvalThis hvals_io) + main_tid <- liftIO $ evalStmt interp eval_opts (EvalThis hvals_io) + status <- liftIO $ waitThreadResult interp main_tid eval_opts main_tid case status of EvalComplete _ (EvalSuccess [hval]) -> return hval EvalComplete _ (EvalException e) -> ===================================== compiler/GHC/Runtime/Eval/Types.hs ===================================== @@ -198,6 +198,10 @@ data Resume = Resume , resumeCCS :: RemotePtr CostCentreStack , resumeHistory :: [History] , resumeHistoryIx :: Int -- 0 <==> at the top of the history + , resumeMainThread :: ForeignRef ThreadId + -- ^ The corresponding main evaluation thread. A breakpoint may be on + -- a forked thread: we resume the stopped thread ('resumeContext'), + -- but await on the main evaluation one ('resumeMainThread') } type ResumeBindings = ([TyThing], IcGlobalRdrEnv) ===================================== compiler/GHC/Runtime/Interpreter.hs ===================================== @@ -10,6 +10,8 @@ module GHC.Runtime.Interpreter -- * High-level interface to the interpreter , evalStmt, EvalStatus(..), EvalResult(..), EvalExpr(..) , resumeStmt + , waitThreadResult + , redirectInterrupts , abandonStmt , evalIO , evalString @@ -104,7 +106,7 @@ import GHC.Unit.Home.ModInfo import GHC.Unit.Env #if defined(HAVE_INTERNAL_INTERPRETER) -import GHCi.Run +import GHCi.Run hiding (redirectInterrupts) #endif import Control.Concurrent @@ -322,11 +324,11 @@ evalStmt :: SafeInterp -> EvalOpts -> EvalExpr ForeignHValue - -> IO (EvalStatus [ForeignHValue]) + -> IO (ForeignRef ThreadId) evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do - status <- withExpr foreign_expr $ \expr -> + rtid <- withExpr foreign_expr $ \expr -> interpCmd interp (EvalStmt opts expr) - handleEvalStatus interp status + mkFinalizedHValue interp rtid where withExpr :: EvalExpr ForeignHValue -> (EvalExpr HValueRef -> IO a) -> IO a withExpr (EvalThis fhv) cont = @@ -340,12 +342,48 @@ resumeStmt :: SafeInterp -> EvalOpts -> ForeignRef ThreadId - -> IO (EvalStatus [ForeignHValue]) + -- ^ The thread to resume + -> IO () resumeStmt interp0 opts resume_tid = withInterp interp0 $ \interp -> do - status <- withForeignRef resume_tid $ \rhv -> + withForeignRef resume_tid $ \rhv -> do interpCmd interp (ResumeStmt opts rhv) + +-- | Await the result of an action of type @IO [a]@, running on the given +-- interpreter thread, returning 'ForeignHValue's for each of the results. +waitThreadResult + :: SafeInterp + -> ForeignRef ThreadId + -- ^ The thread on the interpreter on which asynchronous exceptions raised in + -- this host thread are thrown to. Typically this should be the same as the + -- thread whose result we're awaiting. + -> EvalOpts + -- ^ Use 'readAllBreaks' as: @True@ to read breakpoints on all non-isolated + -- interpreter threads (such as those forked off by the debuggee evaluation + -- statement); @False@ to only return the result or breakpoints in this + -- thread specifically. + -> ForeignRef ThreadId + -- ^ The main isolated evaluation thread whose status is awaited + -> IO (EvalStatus [ForeignHValue]) +waitThreadResult interp0 redirect_ftid opts wait_ftid = withInterp interp0 $ \interp -> do + status <- withForeignRef redirect_ftid $ \redirect_tid -> do + redirectInterrupts interp redirect_tid $ + withForeignRef wait_ftid $ \wait_tid -> + interpCmd interp (WaitThreadResult (readAllBreaks opts) wait_tid) handleEvalStatus interp status +-- | While we're waiting for the possibly remote interpreter thread to yield a +-- result, if the current host thread receives an asynchronous exception, we +-- re-throw it at the target thread on the possibly remote interpreter and +-- continue to wait. This allows e.g. a ^C on the host to interrupt an +-- 'evalStmt' on the external interpreter. +-- +-- Akin 'GHCi.Run.redirectInterrupts', but on the ghc side. +redirectInterrupts :: Interp -> RemoteRef ThreadId -> IO a -> IO a +redirectInterrupts interp rtid wait = + wait `catch` \(e::SomeAsyncException) -> do + interpCmd interp (ThrowToThread rtid (toSerializableException (toException e))) + wait + abandonStmt :: SafeInterp -> ForeignRef ThreadId -> IO () abandonStmt interp0 resume_tid = withInterp interp0 $ \ interp -> withForeignRef resume_tid $ \rhv -> @@ -452,7 +490,11 @@ whereFrom interp0 ref = withInterp interp0 $ \ interp -> seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ()) seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp -> withForeignRef ref $ \hval -> do - status <- interpCmd interp (Seq hval) + rtid <- interpCmd interp (Seq hval) + frtid <- mkFinalizedHValue interp rtid + status <- withForeignRef frtid $ \rtid -> + redirectInterrupts interp rtid $ do + interpCmd interp (WaitThreadResult False rtid) handleSeqHValueStatus interp unit_env logger (clearEvalStatus status) evalBreakpointToId :: EvalBreakpoint -> InternalBreakpointId @@ -496,7 +538,12 @@ handleSeqHValueStatus interp unit_env logger eval_status = -- resume the seq (:force) processing in the iserv process withForeignRef resume_tid_fhv $ \rtid -> do - status <- interpCmd interp (ResumeSeq rtid) + interpCmd interp (ResumeSeq rtid) + status <- redirectInterrupts interp rtid $ do + -- Resume the stopped thread. The stopped thread must be the main + -- `:seq` thread, since readAllBreaks=False on @Seq@ cmd implies an + -- EvalBreak on a :seq must be from from the seq main thread + interpCmd interp (WaitThreadResult False rtid) handleSeqHValueStatus interp unit_env logger (clearEvalStatus status) (EvalComplete _ r) -> return r ===================================== ghc/GHCi/UI/Monad.hs ===================================== @@ -380,7 +380,8 @@ runStmt stmt stmt_text step = do , GHC.execSingleStep = step , GHC.execWrap = \fhv -> EvalApp (EvalThis (evalWrapper st)) (EvalThis fhv) } - Just <$> GHC.execStmt' stmt stmt_text opts + waitRes <- GHC.execStmt' stmt stmt_text opts + Just <$> waitRes runDecls :: GhciMonad m => String -> m (Maybe [GHC.TyThing]) runDecls decls = do @@ -418,7 +419,8 @@ resume step mbIgnoreCnt = do throwGhcExceptionIO (GHC.ProgramError "not stopped at a breakpoint") (r:rs) -> do modifySession $ \env -> env{hsc_IC = (hsc_IC env){ ic_resume = rs }} - GHC.resumeExec step mbIgnoreCnt r + waitRes <- GHC.resumeExec step mbIgnoreCnt r + waitRes -- -------------------------------------------------------------------------- -- timing & statistics ===================================== libraries/ghci/GHCi/Message.hs ===================================== @@ -144,13 +144,14 @@ data Message a where EvalStmt :: EvalOpts -> EvalExpr HValueRef {- IO [a] -} - -> Message (EvalStatus [HValueRef]) {- [a] -} + -> Message (RemoteRef ThreadId) + -- ^ 'WaitThreadResult' of this thread id yields [a] -- | Resume evaluation of a statement after a breakpoint ResumeStmt :: EvalOpts -> RemoteRef ThreadId - -> Message (EvalStatus [HValueRef]) + -> Message () -- | Abandon evaluation of a statement after a breakpoint AbandonStmt @@ -254,13 +255,27 @@ data Message a where -- | Evaluate something. This is used to support :force in GHCi. Seq :: HValueRef - -> Message (EvalStatus [HValueRef]) + -> Message (RemoteRef ThreadId) -- | Resume forcing a free variable in a breakpoint (#2950) ResumeSeq :: RemoteRef ThreadId + -> Message () + + -- | Await the result or a breakpoint of a sandbox thread. + WaitThreadResult + :: Bool + -- ^ Whether to read all thread breaks on any forked threads (@True@) or + -- just this thread's breakpoints or its eval result (@False@) + -> RemoteRef ThreadId -> Message (EvalStatus [HValueRef]) + -- | Throw a serializable exception to the given thread + ThrowToThread + :: RemoteRef ThreadId + -> SerializableException + -> Message () + -- | User-defined request encoded as a tag/payload pair. This is left -- uninterpreted by GHC and is meant for GHC API applications to be able to supply -- their own interpreter which understands additional commands. @@ -295,20 +310,22 @@ resultRemoteResources msg res = case msg of PrepFFI{} -> [RemoteFFI res] LookupClosure{} -> map RemoteHValueRef $ toList res CreateBCOs{} -> map RemoteHValueRef $ res - EvalStmt{} -> map RemoteHValueRef $ evalStatus id res - ResumeStmt{} -> map RemoteHValueRef $ evalStatus id res NewBreakArray{} -> map RemoteHValueRef $ [castRemoteRef res] GetBreakpointVar{} -> map RemoteHValueRef $ toList res StartTH{} -> [RemoteHValueRef $ castRemoteRef res] GetClosure{} -> map RemoteHValueRef $ toList res - Seq{} -> map RemoteHValueRef $ evalStatus (const []) res - ResumeSeq{} -> map RemoteHValueRef $ evalStatus (const []) res AddLibrarySearchPath{} -> [RemoteLibrarySearchPath res] + WaitThreadResult{} -> map RemoteHValueRef $ evalStatus id res + EvalStmt{} -> [RemoteHValueRef $ castRemoteRef res] + Seq{} -> [RemoteHValueRef $ castRemoteRef res] (CustomMessage _ _ CustomMessageMethods{..}) -> customResultRemoteResources res (CustomMessage _ _ Deserialized) -> error "resultRemoteRefs on deserialized CustomMessage" + -- resume returns () + ResumeStmt{} -> [] + ResumeSeq{} -> [] -- 'LoadDLLs' is idempotent. LoadDLLs{} -> [] @@ -343,6 +360,7 @@ resultRemoteResources msg res = case msg of RunModFinalizers{} -> [] WhereFrom{} -> [] FreeRemoteResources{} -> [] + ThrowToThread{} -> [] where evalStatus :: (b -> [HValueRef]) -> EvalStatus b -> [HValueRef] evalStatus f = \case @@ -694,6 +712,8 @@ getMessage = do 41 -> Msg <$> (AddHpcModule <$> get <*> get <*> get <*> get) 42 -> Msg <$> (CustomMessage <$> get <*> get <*> pure Deserialized) 43 -> Msg <$> (FreeRemoteResources <$> get) + 44 -> Msg <$> (WaitThreadResult <$> get <*> get) + 45 -> Msg <$> (ThrowToThread <$> get <*> get) _ -> error $ "Unknown Message code " ++ (show b) putMessage :: Message a -> Put @@ -743,6 +763,8 @@ putMessage m = case m of AddHpcModule m n h ticks -> putWord8 41 >> put m >> put n >> put h >> put ticks CustomMessage tag payload _ -> putWord8 42 >> put tag >> put payload FreeRemoteResources ps -> putWord8 43 >> put ps + WaitThreadResult b tid -> putWord8 44 >> put b >> put tid + ThrowToThread tid e -> putWord8 45 >> put tid >> put e {- Note [Parallelize CreateBCOs serialization] ===================================== libraries/ghci/GHCi/Run.hs ===================================== @@ -49,7 +49,6 @@ import GHC.Stack import Foreign hiding (void) import Foreign.C import GHC.Conc.Sync -import GHC.IO hiding ( bracket ) import System.Mem.Weak ( deRefWeak ) import Unsafe.Coerce @@ -130,7 +129,10 @@ run m = case m of InfoProv.whereFrom =<< localRef ref Seq ref -> doSeq ref ResumeSeq ref -> resumeSeq ref - + WaitThreadResult b tid -> waitThreadResult b tid + ThrowToThread ref e -> do + tid <- localRef ref + throwTo tid (fromSerializableException e) Shutdown -> unexpectedMessage m RunTH {} -> unexpectedMessage m RunModFinalizers {} -> unexpectedMessage m @@ -214,7 +216,7 @@ tryEval io = do -------------------------------------------------------------------------------- -evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (EvalStatus [HValueRef]) +evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (RemoteRef ThreadId) evalStmt opts expr = do io <- mkIO expr sandboxIO opts $ do @@ -256,7 +258,7 @@ evalStringToString r str = do -- The UI process has more and therefore also can show more -- information about the breakpoint than the current iserv -- process. -doSeq :: RemoteRef a -> IO (EvalStatus [HValueRef]) +doSeq :: RemoteRef a -> IO (RemoteRef ThreadId) doSeq ref = do sandboxIO evalOptsSeq $ do _ <- (void $ evaluate =<< localRef ref) @@ -264,7 +266,7 @@ doSeq ref = do -- | Process a ResumeSeq message. Continue the :force processing #2950 -- after a breakpoint. -resumeSeq :: RemoteRef ThreadId -> IO (EvalStatus [HValueRef]) +resumeSeq :: RemoteRef ThreadId -> IO () resumeSeq = resumeStmt evalOptsSeq evalOptsSeq :: EvalOpts @@ -287,20 +289,20 @@ evalOptsSeq = EvalOpts -- only while we execute the user's code. We can't afford to lose the final -- 'writeThreadEvalStatus', otherwise deadlock ensues. (#1583, #1922, #1946) -sandboxIO :: EvalOpts -> IO [HValueRef] -> IO (EvalStatus [HValueRef]) +sandboxIO :: EvalOpts -> IO [HValueRef] -> IO (RemoteRef ThreadId) sandboxIO opts io = do -- Make sure the global breakpoint action is set; and that the interpreter -- main thread doesn't stop at breakpoints in it. -- See Note [Disable breakpoints in certain threads] poke breakPointIOAction globalBreakStablePtr - disableThreadBreakpoints =<< myThreadId + mytid <- myThreadId + disableThreadBreakpoints mytid - -- We are running in uninterruptibleMask let runIt = measureAlloc $ tryEval $ rethrow opts $ clearCCS io if useSandboxThread opts then do - tid <- forkIO $ do + tid <- mask_ $ forkIOWithUnmask $ \restore -> do tid <- myThreadId setIsolatedThread tid -- main thread is always isolated setBreakFlags opts tid -- set flags on the sandbox thread @@ -308,13 +310,9 @@ sandboxIO opts io = do -- We only write the thread status map in two places: -- * When the "main" thread finishes (here) -- * When any thread hits a breakpoint (global break action) - unsafeUnmask runIt >>= writeThreadEvalStatus tid - - main <- mkMainThreadWithContext tid - atomically $ modifyTVar evaluationMainThreadGlobalVar (main :) - redirectInterrupts tid $ unsafeUnmask $ - atomically $ readEvalStatus opts main - else + restore runIt >>= writeThreadEvalStatus tid + mkRemoteRef tid + else do -- GLUT on OS X needs to run on the main thread. If you -- try to use it from another thread then you just get a -- white rectangle rendered. For this, or anything else @@ -325,7 +323,12 @@ sandboxIO opts io = do -- tracing, etc.) need the expression to be running in a -- separate thread, so debugging is only enabled when -- using the sandbox. - runIt + ctx <- getThreadResumeContext mytid + mask $ \restore -> do + -- clear the result of a previous eval on the no-sandbox thread + atomically $ writeTVar (resumeEvalStatus ctx) ThreadStatusRunning + restore runIt >>= writeCtxEvalStatus ctx + mkRemoteRef mytid -- We want to turn ^C into a break when -fbreak-on-exception is on, -- but it's an async exception and we only break for sync exceptions. @@ -362,34 +365,6 @@ rethrow EvalOpts{..} io = rethrowIO (ExceptionWithContext cx se) --- --- While we're waiting for the sandbox thread to return a result, if --- the current thread receives an asynchronous exception we re-throw --- it at the sandbox thread and continue to wait. --- --- This is for two reasons: --- --- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the --- computation to run its exception handlers before returning the --- exception result to the caller of runStmt. --- --- * clients of the GHC API can terminate a runStmt in progress --- without knowing the ThreadId of the sandbox thread (#1381) --- --- NB. use a weak pointer to the thread, so that the thread can still --- be considered deadlocked by the RTS and sent a BlockedIndefinitely --- exception. A symptom of getting this wrong is that conc033(ghci) --- will hang. --- -redirectInterrupts :: ThreadId -> IO a -> IO a -redirectInterrupts target wait = do - wtid <- mkWeakThreadId target - wait `catch` \e -> do - m <- deRefWeak wtid - case m of - Nothing -> wait - Just target -> do throwTo target (e :: SomeException); wait - measureAlloc :: IO (EvalResult a) -> IO (EvalStatus a) measureAlloc io = do setAllocationCounter 0 -- #16012 @@ -439,31 +414,128 @@ Likewise for other interactions between eval/resume/abandon. TL;DR: always `setBreakFlags` when running/resuming a thread -} -resumeStmt :: EvalOpts -> RemoteRef ThreadId -> IO (EvalStatus [HValueRef]) +resumeStmt :: EvalOpts -> RemoteRef ThreadId -> IO () resumeStmt opts rtid = do tid <- localRef rtid ctx <- getThreadResumeContext tid setBreakFlags opts tid - main:_ <- readTVarIO evaluationMainThreadGlobalVar - mask_ $ do - resumeStoppedThread ctx -- this awakens the stopped thread... - -- wait for the result of the main thread, not of the stopped one, but - -- interrupt the thread which was resumed. - redirectInterrupts tid $ unsafeUnmask $ - atomically $ readEvalStatus opts main + resumeStoppedThread ctx -- this awakens the stopped thread... -- | Wait for the given main thread of an evaluation to complete or break or, --- if 'readAllBreaks', for any other thread to break. -readEvalStatus :: EvalOpts -> MainThreadWithCtx -> STM (EvalStatus [HValueRef]) -readEvalStatus opts main = do - r <- readCtxEvalStatus (mainContext main) - & if readAllBreaks opts +-- if 'readAllBreaks :: Bool', for any other thread to break. +readEvalStatus :: Bool -> ResumeContext -> STM (EvalStatus [HValueRef]) +readEvalStatus readAllBreaks ctx = do + readCtxEvalStatus ctx + & if readAllBreaks then (`orElse` (EvalPaused <$> readAnyThreadEvalBreak)) else id - case r of - EvalComplete{} -> popMainThread main - EvalPaused{} -> pure () - pure r + +-- | Await the result or breakpoint of a main evaluation thread (started with +-- 'sandboxIO', unless -fno-ghci-sandbox). If the @readAllBreaks :: Bool@ is +-- @True@, we may also return breakpoints hit by any other non-sandboxed +-- threads in the interpreter. +-- +-- If this function is used on a non-main-eval thread, such as one forked by +-- the main debuggee that hit a breakpoint, we will only ever return its +-- breakpoints, as that thread won't write ever an 'EvalComplete' result. +-- @readAllBreaks@ works the same. +-- +-- __WARNING__: You very likely want to wrap a call to this function in +-- 'redirectInterrupts', as in +-- @ +-- 'redirectInterrupts' tid $ +-- 'waitThreadResult' ... tid +-- @ +-- Because if an asynchronous exception is thrown to the main interpreter +-- thread, which is awaiting the evaluation result or a breakpoint on another +-- thread, that exception should be re-throw to that thread to give it a chance +-- to clean-up. See also Note [interpreter redirectInterrupts and signal handling] +waitThreadResult :: Bool -> RemoteRef ThreadId -> IO (EvalStatus [HValueRef]) +waitThreadResult readAllBreaks r = do + tid <- localRef r + ctx <- getThreadResumeContext tid + atomically $ readEvalStatus readAllBreaks ctx + +{- +Note [interpreter redirectInterrupts and signal handling] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +When evaluating a statement at the REPL, the interpreter will do something +like: + + evalStmt expr = forkIO (expr >>= writeThreadResult mytid) + + tid <- evalStmt <user expr> + redirectInterrupts tid $ + waitThreadResult tid + +The 'redirectInterrupts' call is responsible for re-throwing an asynchronous +expression thrown to the main interpreter thread (which is blocked awaiting for +the thread result) to the thread that the interpreter thread is blocked on, so +it has a chance to clean-up properly. + +When using the internal interpreter, this is direct: a ^C goes directly to the +main interpreter thread (GHC's 'withSignalHandlers' redirects signals to the +ghc execution main thread, which, with the internal interpreter, is also +running the interpreter commands and is currently blocked waiting for the +evaluation result). + +With the external interpreter, which is a sub-process spawned by the main ghc +process, if ^C interrupts the ghc process at the terminal, BOTH the main ghc +process and the external interpreter get the ^C signal (^C at the terminal gets +sent to all processes in the foreground process group). + +Therefore, we disable all signals on the external interpreter process (^C is +fully ignored on the external interpreter) and, instead, let the main ghc process +capture ^C and send a message to the external interpreter redirecting this +interrupt to the thread we were waiting for. The program above, when using the +external interpreter, under the hood works like: + + tid <- remoteCall (EvalStmt <user expr>) + remoteCall (WaitThreadResult tid) + `onAsyncException` \e -> + remoteCall (ThrowToThread tid (serializeException e)) + remoteCall (WaitThreadResult tid) + +where 'remoteCall' blocks waiting for the external interpreter to +asynchronously deliver a reply to the given request, and cancels the pending +request when an exception is thrown while waiting. + +This way, when there's a ^C on the main ghc process, we'll cancel the wait +request (in `remoteCall`) and then send a request to interrupt the remote +process thread with ^C (in `GHC.Runtime.Interpreter.redirectInterrupts`) + +Note: the `ghci` library still exposes a `redirectInterrupts`, in case you want +to wrap calls to `waitThreadResult` using the ghci library directly; however, +in ghc, we define `redirectInterrupts` as a function which captures host +exceptions and sends a 'ThrowToThread' message which is interpreted by +'throwTo'ing that exception on the interpreter process. +-} + +-- | While we're waiting for the sandbox thread to return a result, if +-- the current thread receives an asynchronous exception we re-throw +-- it at the sandbox thread and continue to wait. +-- +-- This is for two reasons: +-- +-- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the +-- computation to run its exception handlers before returning the +-- exception result to the caller of runStmt. +-- +-- * clients of the GHC API can terminate a runStmt in progress +-- without knowing the ThreadId of the sandbox thread (#1381) +-- +-- NB. use a weak pointer to the thread, so that the thread can still +-- be considered deadlocked by the RTS and sent a BlockedIndefinitely +-- exception. A symptom of getting this wrong is that conc033(ghci) +-- will hang. +redirectInterrupts :: ThreadId -> IO a -> IO a +redirectInterrupts target wait = do + wtid <- mkWeakThreadId target + wait `catch` \e -> do + m <- deRefWeak wtid + case m of + Nothing -> wait + Just target -> do throwTo target (e :: SomeException); wait -- | When abandoning a computation we have to -- (a) kill the stopped thread with an async exception, so that the @@ -473,21 +545,15 @@ readEvalStatus opts main = do -- evaluating a thunk when we stopped at the breakpoint, so the async -- exception makes the thunk resumable from where we stopped instead of -- updating it with an exception (tested in break010). --- (c) wait for the main thread to terminate by waiting for its result. --- This step is necessary to prevent race conditions with --- -fbreak-on-exception (see #5975). -- See test break010 and break034. +-- +-- If the expression where we're stopped catches asynchronous exceptions it +-- might catch the `AbandonException` instead of abandoning. abandonStmt :: RemoteRef ThreadId -> IO () abandonStmt hvref = do - main:_ <- readTVarIO evaluationMainThreadGlobalVar tid <- localRef hvref setBreakFlags evalOptsAbandon tid - throwTo tid AbandonException -- kill stopped thread, then wait for main thread - atomically $ - readCtxEvalStatus (mainContext main) >>= \case - -- throwTo may return before the thread is marked as running - EvalPaused{} -> retry - EvalComplete{} -> popMainThread main + throwTo tid AbandonException -- kill the stopped thread where -- Don't stop anywhere on abandon evalOptsAbandon = EvalOpts @@ -504,34 +570,3 @@ data AbandonException = AbandonException deriving Show instance Exception AbandonException where toException = asyncExceptionToException fromException = asyncExceptionFromException - --------------------------------------------------------------------------------- --- To remove completely when sandboxIO/resume becomes asynchronous: --------------------------------------------------------------------------------- - --- | The main threads of the exprs being currently evaluated, the most recent --- first. Evaluating an expr while stopped at a breakpoint pushes its thread on --- top of the stopped one, until it completes. --- --- FIXME: Remove this global variable. It is only needed while `resumeStmt` is --- synchronous, since `resumeStmt` currently tries to return the Eval result of --- the main thread (which is a bit non-sensical for a resume operation to do). --- It is only needed to preserve the previous behavior, but as soon as --- `evalStmt` returns the sandboxIO thread id we can wait on that explicitly --- instead of resuming having anything to do with waiting for the main --- evaluation result. -evaluationMainThreadGlobalVar :: TVar [MainThreadWithCtx] -evaluationMainThreadGlobalVar = unsafePerformIO $ newTVarIO [] -{-# NOINLINE evaluationMainThreadGlobalVar #-} - --- | (Keep the ResumeContext to reduce allocations, triggered interpreter_steplocal regression) -data MainThreadWithCtx = MainThreadWithCtx { mainKey :: !Word64, mainContext :: !ResumeContext } - -mkMainThreadWithContext :: ThreadId -> IO MainThreadWithCtx -mkMainThreadWithContext tid = MainThreadWithCtx (fromThreadId tid) <$> getThreadResumeContext tid - --- | FIXME: Kill this function, just like 'evaluationMainThreadGlobalVar' will be killed. -popMainThread :: MainThreadWithCtx -> STM () -popMainThread main = - modifyTVar evaluationMainThreadGlobalVar (filter ((/= mainKey main) . mainKey)) - ===================================== libraries/ghci/GHCi/Server.hs ===================================== @@ -54,18 +54,17 @@ noCustomHandler _ _ = return Nothing trace :: String -> IO () trace s = getProgName >>= \name -> hPrintf stderr "[%20s] %s\n" name s -serv :: Bool -> MessageHook -> Pipe -> (forall a .IO a -> IO a) -> IO () -serv verbose hook pipe restore = - servWithCustom verbose hook pipe restore noCustomHandler +serv :: Bool -> MessageHook -> Pipe -> IO () +serv verbose hook pipe = + servWithCustom verbose hook pipe noCustomHandler servWithCustom :: Bool -> MessageHook -> Pipe - -> (forall a. IO a -> IO a) -> CustomMessageHandler -> IO () -servWithCustom verbose hook pipe restore customHandler = do +servWithCustom verbose hook pipe customHandler = do ref <- newIORef False withThreadManager $ \mngr -> handle @PipeClosedException (const $ pure ()) $ do loop ref mngr `finally` closePipe pipe @@ -75,7 +74,6 @@ servWithCustom verbose hook pipe restore customHandler = do handleRemoteCall pipe hook $ \wr setCancel (msg :: Message a) -> - discardCtrlC %>>= \_ -> when verbose (trace ("msg: " ++ (show msg))) %>>= \_ -> case msg of @@ -83,12 +81,29 @@ servWithCustom verbose hook pipe restore customHandler = do Shutdown -> writeIORef doneRef True >> closingPipe pipe >> reply () %>>= \r -> runWriteReply wr (Right r) ignorePipeClosedException + + -- Run splices concurrently without blocking the server thread RunTH ii st q ty loc -> handleAsync wr - (restore $ wrapRunTH ii (runTH pipe ii st q ty loc)) + (wrapRunTH ii (runTH pipe ii st q ty loc)) (setCancel . void . forkIO . killThread) RunModFinalizers ii st qs -> handleAsync wr - (restore $ wrapRunTH ii (runModFinalizerRefs pipe ii st qs)) + (wrapRunTH ii (runModFinalizerRefs pipe ii st qs)) + (setCancel . void . forkIO . killThread) + + -- Wait off the main thread and reply asynchronously once ready. This + -- wait thread is killed if the wait request is cancelled, but a result + -- of the target thread can still be read e.g. with a follow-up wait. + -- If the target thread should be killed, see 'ThrowToThread'. + -- See Note [interpreter redirectInterrupts and signal handling] for both. + WaitThreadResult{} -> handleAsync wr + (run msg >>= reply) + (setCancel . void . forkIO . killThread) + -- Run throwTo off the main thread in case the user program behaves + -- "badly" wrt async exceptions. + ThrowToThread{} -> handleAsync wr + (run msg >>= reply) (setCancel . void . forkIO . killThread) + _other -> run msg >>= reply %>>= writeReply wr isDone <- readIORef doneRef @@ -157,17 +172,6 @@ servWithCustom verbose hook pipe restore customHandler = do Left e -> showException e Right str -> return str - -- throw away any pending ^C exceptions while we're not running - -- interpreted code. GHC will also get the ^C, and either ignore it - -- (if this is GHCi), or tell us to quit with a Shutdown message. - discardCtrlC = do - when verbose $ trace "discardCtrlC" - r <- try $ restore $ return () - case r of - Left UserInterrupt -> return () >> discardCtrlC - Left e -> throwIO e - _ -> return () - -- | Default server #if defined(wasm32_HOST_ARCH) defaultServer :: Callback (JSVal -> IO ()) -> Callback (IO JSUint8Array) -> Callback (JSUint8Array -> IO ()) -> IO () @@ -212,12 +216,12 @@ defaultServerWithCustom customHandler = do #if defined(wasm32_HOST_ARCH) -- See Note [wasm ghci signal handlers] for details - installSignalHandlers $ js_register_signal_handler cb_sig + ignoreInterrupts $ js_register_signal_handler cb_sig pipe <- mkPipeFromContinuations (recv_buf cb_recv) (send_buf cb_send) (pure ()) (pure ()) #else when verbose $ printf "GHC iserv starting (in: %s; out: %s)\n" (show inh) (show outh) - installSignalHandlers + ignoreInterrupts pipe <- mkPipeFromHandles inh outh #endif @@ -226,11 +230,9 @@ defaultServerWithCustom customHandler = do putStrLn "Waiting 3s" threadDelay 3000000 - uninterruptibleMask $ \restore -> servWithCustom verbose hook pipe restore customHandler + servWithCustom verbose hook pipe customHandler where hook = return -- empty hook - -- we cannot allow any async exceptions while communicating, because - -- we will lose sync in the protocol, hence uninterruptibleMask. dieWithUsage :: IO a dieWithUsage = do ===================================== libraries/ghci/GHCi/Signals.hs ===================================== @@ -1,10 +1,7 @@ {-# LANGUAGE CPP #-} -module GHCi.Signals (installSignalHandlers) where +module GHCi.Signals (ignoreInterrupts) where import Prelude -- See note [Why do we import Prelude here?] -import Control.Concurrent -import Control.Exception -import System.Mem.Weak ( deRefWeak ) #if defined(wasm32_HOST_ARCH) import GHC.Wasm.Prim @@ -16,55 +13,34 @@ import System.Posix.Signals import GHC.ConsoleHandler #endif --- | Install standard signal handlers for catching ^C, which just throw an --- exception in the target thread. The current target thread is the --- thread at the head of the list in the MVar passed to --- installSignalHandlers. +-- | Install standard signal handlers for catching ^C, which just ignore it. +-- See Note [interpreter redirectInterrupts and signal handling]. #if defined(wasm32_HOST_ARCH) -installSignalHandlers :: (JSVal -> IO ()) -> IO () -installSignalHandlers cb_sig = do -#else -installSignalHandlers :: IO () -installSignalHandlers = do -#endif - main_thread <- myThreadId - wtid <- mkWeakThreadId main_thread - - let interrupt = do - r <- deRefWeak wtid - case r of - Nothing -> return () - Just t -> throwTo t UserInterrupt - -#if defined(wasm32_HOST_ARCH) - cb_sig =<< js_export_signal_handler interrupt +ignoreInterrupts :: (JSVal -> IO ()) -> IO () +ignoreInterrupts cb_sig = do + -- See Note [wasm ghci signal handlers] + cb_sig =<< js_export_signal_handler (return ()) #elif !defined(mingw32_HOST_OS) - _ <- installHandler sigQUIT (Catch interrupt) Nothing - _ <- installHandler sigINT (Catch interrupt) Nothing +ignoreInterrupts :: IO () +ignoreInterrupts = do + -- use `Catch (return ())` instead of `Ignore`, because `Ignore` gets + -- inherited by subprocesses the server may spawn. + _ <- installHandler sigQUIT (Catch (return ())) Nothing + _ <- installHandler sigINT (Catch (return ())) Nothing + return () #else - -- GHC 6.3+ has support for console events on Windows - -- NOTE: running GHCi under a bash shell for some reason requires - -- you to press Ctrl-Break rather than Ctrl-C to provoke - -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know - -- why --SDM 17/12/2004 - let sig_handler ControlC = interrupt - sig_handler Break = interrupt - sig_handler _ = return () - - _ <- installHandler (Catch sig_handler) -#endif +ignoreInterrupts :: IO () +ignoreInterrupts = do + _ <- installHandler (Catch (\_ -> return ())) return () +#endif #if defined(wasm32_HOST_ARCH) - -- Note [wasm ghci signal handlers] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- -- For native ghc with -fexternal-interpreter, when you press ^C, --- SIGINT is delivered to both ghc/iserv. iserv SIGINT handler raises --- an async UserInterrupt exception in the main thread, which might --- handle it right away, or later since it's doing I/O under --- uninterruptibleMask. +-- SIGINT is delivered to both ghc/iserv. iserv SIGINT handler simply +-- ignores the SIGINT (see Note [interpreter redirectInterrupts and signal handling]). -- -- wasm is no different here. The node process needs to catch the same -- signals. Instead of calling process.on('SIGINT', handler) in @@ -73,15 +49,7 @@ installSignalHandlers = do -- callback to register the handler. This allows iserv to be run in -- non-nodejs environments as well, and the dyld script can pass a -- handler register callback other than process.on(). --- --- IMPORTANT: THE SIGNAL HANDLER MUST BE EXPORTED AS ASYNC!!!!!!! --- Otherwise, throwTo may block the handler thread, so the handler --- thread is removed from the run queue. Since the main thread may --- also be absent from the run queue (e.g. blocked on waiting for --- input message), the run queue is empty and then the RTS scheduler --- panics. foreign import javascript "wrapper" js_export_signal_handler :: IO () -> IO JSVal - #endif ===================================== testsuite/tests/concurrent/should_run/all.T ===================================== @@ -168,7 +168,11 @@ test('conc030', extra_run_opts('+RTS -K4M -RTS'), compile_and_run, ['']) test('conc031', exit_code(1), compile_and_run, ['']) test('conc032', normal, compile_and_run, ['']) -test('conc033', when(config.have_ext_interp, extra_ways(['ghci-ext'])), compile_and_run, ['']) +# You don't get any guarantee that the RTS ever throws a BlockedIndefinitely +# exception, so it's fine if ghci doesn't throw one to the sandboxed thread. +test('conc033', [when(config.have_ext_interp, extra_ways(['ghci-ext'])), + expect_fail_for(['ghci-ext'])], + compile_and_run, ['']) # Omit for GHCi, because it just sits there waiting for you to press ^C test('conc034', [ ===================================== testsuite/tests/ghc-api/T8628.hs ===================================== @@ -1,5 +1,6 @@ module Main where +import Control.Monad (join) import System.IO import GHC.Driver.Session import GHC @@ -25,10 +26,10 @@ main setContext [ IIDecl (simpleImportDecl pRELUDE_NAME) , IIDecl (simpleImportDecl (mkModuleNameFS (fsLit "System.IO")))] runDecls "data X = Y ()" - execStmt "print True" execOptions - MC.try $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult) + join $ execStmt "print True" execOptions + MC.try $ join $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult) runDecls "data X = Y () deriving Show" _ <- dynCompileExpr "'x'" - execStmt "print (Y ())" execOptions - execStmt "System.IO.hFlush System.IO.stdout" execOptions + join $ execStmt "print (Y ())" execOptions + join $ execStmt "System.IO.hFlush System.IO.stdout" execOptions print "done" ===================================== testsuite/tests/ghc-api/T8639_api.hs ===================================== @@ -1,5 +1,6 @@ module Main where +import Control.Monad (join) import GHC import GHC.Driver.Monad import GHC.Driver.Ppr @@ -20,8 +21,8 @@ main -- With the next line, you get an "Not in scope" exception. -- If you comment out this runStmt, it runs without error and prints the type. - execStmt "putStrLn (show 3)" execOptions - execStmt "hFlush stdout" execOptions + join $ execStmt "putStrLn (show 3)" execOptions + join $ execStmt "hFlush stdout" execOptions ty <- exprType TM_Inst "T8639_api_a.it" liftIO (putStrLn (showPpr flags ty)) ===================================== testsuite/tests/ghc-api/apirecomp001/myghc.hs ===================================== @@ -50,7 +50,7 @@ main = do setContext [IIModule mod] liftIO $ hFlush stdout -- make sure things above are printed before -- interactive output - r <- execStmt "main" execOptions + r <- join $ execStmt "main" execOptions case r of ExecComplete { execResult = Right _ } -> prn "ok" ExecComplete { execResult = Left _ } -> prn "exception" ===================================== testsuite/tests/ghci.debugger/scripts/break050ext.stdout ===================================== @@ -4,4 +4,3 @@ _result :: IO () = _ x :: Int = 0 forked thread: user interrupt main was not interrupted -Interrupted. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a7f092c07e2ba52870274afc1268b27c... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a7f092c07e2ba52870274afc1268b27c... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Rodrigo Mesquita (@alt-romes)