Andrea Vezzosi pushed to branch wip/andrea/async-rpc at Glasgow Haskell Compiler / GHC Commits: 000d737c by Andrea Vezzosi at 2026-11-16T17:27:25+01:00 interp: cleanup with stopInterp outside interpLoader lock - - - - - 4691cfdb by Andrea Vezzosi at 2026-11-17T13:05:22+01:00 interp: fix race between stopInterp and starting a new instance. On a PipeClosedException we stop the external interpreter and cleanup its state. With multiple threads sharing the same ghc session we could have had two threads getting the exception, one of them cleanup and start a new instance before the second thread gets to do its cleanup, which would then stop the new instance which is working fine. Now we check whether the 'Pipe' of the interpreter we are about to cleanup is closed, otherwise it must be a new one and we leave it be. - - - - - 5c310af6 by Andrea Vezzosi at 2026-11-17T13:16:12+01:00 interp: test concurrent use of one external interpreter Threads share a GHC session: concurrent requests, killing waiting threads, cancelling a running splice, and restarting after the interpreter dies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> - - - - - 17 changed files: - compiler/GHC/Driver/Env.hs - compiler/GHC/Driver/Env/Types.hs - compiler/GHC/Driver/Main/Passes.hs - compiler/GHC/Driver/Make.hs - compiler/GHC/Linker/Loader.hs - compiler/GHC/Runtime/Eval.hs - compiler/GHC/Runtime/Interpreter.hs - compiler/GHC/Runtime/Interpreter/Init.hs - compiler/GHC/Runtime/Interpreter/Types.hs - compiler/GHC/Runtime/Loader.hs - compiler/GHC/Tc/Gen/Splice.hs - ghc/GHCi/UI/Monad.hs - libraries/ghci/GHCi/Message.hs - libraries/ghci/GHCi/Message/Async.hs - testsuite/tests/ghci/interp-cancellation/all.T - + testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs - + testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout Changes: ===================================== compiler/GHC/Driver/Env.hs ===================================== @@ -56,7 +56,7 @@ import GHC.Driver.Config.Diagnostic (initDiagOpts, initPrintConfig) import GHC.Driver.Env.Types ( Hsc(..), HscEnv(..), HasHscEnv (..) ) import GHC.Runtime.Context -import GHC.Runtime.Interpreter.Types (Interp) +import GHC.Runtime.Interpreter.Types (SafeInterp) import GHC.Unit import GHC.Unit.External.Database @@ -410,7 +410,7 @@ mainModIs hue = mkHomeModule (expectJust $ homeUnitEnv_home_unit hue) (mainModul -- | Retrieve the target code interpreter -- -- Fails if no target code interpreter is available -hscInterp :: HscEnv -> Interp +hscInterp :: HscEnv -> SafeInterp hscInterp hsc_env = case hsc_interp hsc_env of Nothing -> throw (InstallationError "Couldn't find a target code interpreter. Try with -fexternal-interpreter") Just i -> i ===================================== compiler/GHC/Driver/Env/Types.hs ===================================== @@ -14,7 +14,7 @@ import GHC.Driver.LlvmConfigCache (LlvmConfigCache) import GHC.Prelude import GHC.Runtime.Context -import GHC.Runtime.Interpreter.Types ( Interp ) +import GHC.Runtime.Interpreter.Types ( SafeInterp ) import GHC.Types.Error ( Messages ) import GHC.Types.Name.Cache import GHC.Types.Target @@ -88,7 +88,7 @@ data HscEnv -- the 'IfGblEnv'. See 'tcg_knot_vars' in 'GHC.Tc.Utils.TcGblEnv'. -- See also Note [hsc_type_env_var hack] - , hsc_interp :: Maybe Interp + , hsc_interp :: Maybe SafeInterp -- ^ target code interpreter (if any) to use for TH and GHCi. -- See Note [Target code interpreter] ===================================== compiler/GHC/Driver/Main/Passes.hs ===================================== @@ -1604,10 +1604,9 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do let (stg_binds, _stg_deps) = unzip stg_binds_with_deps let interp = hscInterp hsc_env - - case interp of + case interpInstance interp of -- always generate JS code for the JS interpreter (no bytecode!) - Interp { interpInstance = ExternalInterp (ExtJS i) } -> + ExternalInterp (ExtJS i) -> jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id _ -> do @@ -1645,7 +1644,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do let logger = hsc_logger hsc_env tmpfs = hsc_tmpfs hsc_env dflags = hsc_dflags hsc_env - interp = hscInterp hsc_env + interp0 = hscInterp hsc_env tmp_dir = tmpDir dflags unit_env = hsc_unit_env hsc_env js_config = initStgToJSConfig dflags @@ -1671,10 +1670,10 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do -- by default, so we can safely ignore them here. -- Initialise the linker (if it's not been done already) - initLoaderState interp hsc_env + initLoaderState interp0 hsc_env -- Take lock for the actual work. - (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp $ \pls -> do + (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp0 $ \interp pls -> do let link_opts = initLinkDepsOpts hsc_env -- Find what packages and linkables are required @@ -1715,7 +1714,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do jsLinkObject logger tmpfs tmp_dir js_config unit_env (hsc_FC hsc_env) inst out_obj roots needed_units -- look up "id_sym" closure and create a StablePtr (HValue) from it - binding_fref <- lookupClosure interp (IFaststringSymbol id_sym) >>= \case + binding_fref <- withInterp interp0 $ \interp -> lookupClosure interp (IFaststringSymbol id_sym) >>= \case Nothing -> pprPanic "Couldn't find just linked TH closure" (ppr id_sym) Just r -> pure r ===================================== compiler/GHC/Driver/Make.hs ===================================== @@ -837,7 +837,7 @@ pruneCache hpt summ -- --------------------------------------------------------------------------- -- -- | Unloading -unload :: Interp -> HscEnv -> IO () +unload :: SafeInterp -> HscEnv -> IO () unload interp hsc_env = case ghcLink (hsc_dflags hsc_env) of LinkInMemory -> Linker.unload interp hsc_env ===================================== compiler/GHC/Linker/Loader.hs ===================================== @@ -170,19 +170,19 @@ import Foreign.Ptr (nullPtr) uninitialised :: a uninitialised = panic "Loader not initialised" -modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO () -modifyLoaderState_ interp f = +modifyLoaderState_ :: SafeInterp -> (Interp -> LoaderState -> IO LoaderState) -> IO () +modifyLoaderState_ interp0 f = withInterp interp0 $ \ interp -> modifyMVar_ (loader_state (interpLoader interp)) - (fmap pure . f . fromMaybe uninitialised) + (fmap pure . f interp . fromMaybe uninitialised) -modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a -modifyLoaderState interp f = +modifyLoaderState :: SafeInterp -> (Interp -> LoaderState -> IO (LoaderState, a)) -> IO a +modifyLoaderState interp0 f = withInterp interp0 $ \ interp -> modifyMVar (loader_state (interpLoader interp)) - (fmapFst pure . f . fromMaybe uninitialised) + (fmapFst pure . f interp . fromMaybe uninitialised) where fmapFst f = fmap (\(x, y) -> (f x, y)) -getLoaderState :: Interp -> IO (Maybe LoaderState) -getLoaderState interp = readMVar (loader_state (interpLoader interp)) +getLoaderState :: SafeInterp -> IO (Maybe LoaderState) +getLoaderState (SafeInterp interp) = readMVar (loader_state (interpLoader interp)) emptyLoaderState :: UnitEnv -> LoaderState @@ -206,21 +206,21 @@ emptyLoaderState unit_env = LoaderState pkg_to_dfm rtsUnitId ] ++ fmap pkg_to_dfm deps -extendLoadedEnv :: Interp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO () +extendLoadedEnv :: SafeInterp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO () extendLoadedEnv interp modify_bytecode_loader_state new_bindings = - modifyLoaderState_ interp $ \pls -> do + modifyLoaderState_ interp $ \_ pls -> do return $! modifyBytecodeLoaderState modify_bytecode_loader_state pls $ \bco_loader_state -> modifyClosureEnv bco_loader_state $ \ce -> extendClosureEnv ce new_bindings -- strictness is important for not retaining old copies of the pls -deleteFromLoadedHomeEnv :: Interp -> [Name] -> IO () +deleteFromLoadedHomeEnv :: SafeInterp -> [Name] -> IO () deleteFromLoadedHomeEnv interp to_remove = - modifyLoaderState_ interp $ \pls -> do + modifyLoaderState_ interp $ \_ pls -> do return $ modifyBytecodeLoaderState modifyHomePackageBytecodeState pls $ \bco_state -> modifyClosureEnv bco_state $ \ce -> delListFromNameEnv ce to_remove -- | Have we already loaded a name into the interpreter? -lookupFromLoadedEnv :: Interp -> Name -> IO (Maybe ForeignHValue) +lookupFromLoadedEnv :: SafeInterp -> Name -> IO (Maybe ForeignHValue) lookupFromLoadedEnv interp name = do mstate <- getLoaderState interp return $ do @@ -231,10 +231,10 @@ lookupFromLoadedEnv interp name = do -- | Load the module containing the given Name and get its associated 'HValue'. -- -- Throws a 'ProgramError' if loading fails or the name cannot be found. -loadName :: Interp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded) -loadName interp hsc_env name = do - initLoaderState interp hsc_env - modifyLoaderState interp $ \pls0 -> do +loadName :: SafeInterp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded) +loadName interp0 hsc_env name = do + initLoaderState interp0 hsc_env + modifyLoaderState interp0 $ \interp pls0 -> do (pls, links, pkgs) <- if not (isExternalName name) then return (pls0, [], emptyUDFM) else do @@ -248,6 +248,7 @@ loadName interp hsc_env name = do Just (_,aa) -> return (pls,(aa, links, pkgs)) Nothing -> assertPpr (isExternalName name) (ppr name) $ do let sym_to_find = IClosureSymbol name + -- TODO: does not take loader state lock m <- lookupClosure interp sym_to_find r <- case m of Just fhv -> return fhv @@ -295,7 +296,7 @@ loadDependencies interp hsc_env pls span needed_mods = do -- | Temporarily extend the loaded env. withExtendedLoadedEnv :: (ExceptionMonad m) - => Interp + => SafeInterp -> [(Name,ForeignHValue)] -> m a -> m a @@ -314,9 +315,9 @@ withExtendedLoadedEnv interp new_env action -- | Display the loader state. -showLoaderState :: Interp -> IO SDoc +showLoaderState :: SafeInterp -> IO SDoc showLoaderState interp = do - ls <- readMVar (loader_state (interpLoader interp)) + ls <- getLoaderState interp let docs = case ls of Nothing -> [ text "Loader not initialised"] Just pls -> [ text "Pkgs:" <+> ppr (map loaded_pkg_uid $ eltsUDFM $ pkgs_loaded pls) @@ -352,8 +353,8 @@ showLoaderState interp = do -- nothing. This is useful in Template Haskell, where we call it before -- trying to link. -- -initLoaderState :: Interp -> HscEnv -> IO () -initLoaderState interp hsc_env = do +initLoaderState :: SafeInterp -> HscEnv -> IO () +initLoaderState interp0 hsc_env = withInterp interp0 $ \ interp -> do modifyMVar_ (loader_state (interpLoader interp)) $ \pls -> do case pls of Just _ -> return pls @@ -382,10 +383,10 @@ reallyInitLoaderState interp hsc_env = do loadCmdLineLibs' interp hsc_env pls -loadCmdLineLibs :: Interp -> HscEnv -> IO () -loadCmdLineLibs interp hsc_env = do - initLoaderState interp hsc_env - modifyLoaderState_ interp $ \pls -> +loadCmdLineLibs :: SafeInterp -> HscEnv -> IO () +loadCmdLineLibs interp0 hsc_env = do + initLoaderState interp0 hsc_env + modifyLoaderState_ interp0 $ \interp pls -> loadCmdLineLibs' interp hsc_env pls @@ -730,13 +731,13 @@ get_reachable_nodes hsc_env mods ********************************************************************* -} -- | Load the dependencies of a linkable, and then load the linkable itself. -loadDecls :: Interp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded) -loadDecls interp hsc_env span linkable = do +loadDecls :: SafeInterp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded) +loadDecls interp0 hsc_env span linkable = do -- Initialise the linker (if it's not been done already) - initLoaderState interp hsc_env + initLoaderState interp0 hsc_env -- Take lock for the actual work. - modifyLoaderState interp $ \pls0 -> do + modifyLoaderState interp0 $ \interp pls0 -> do -- Link the packages and modules required (pls, ok, links_needed, units_needed) <- loadDependencies interp hsc_env pls0 span needed_mods if failed ok @@ -770,10 +771,10 @@ loadDecls interp hsc_env span linkable = do ********************************************************************* -} -loadModule :: Interp -> HscEnv -> Module -> IO () -loadModule interp hsc_env mod = do - initLoaderState interp hsc_env - modifyLoaderState_ interp $ \pls -> do +loadModule :: SafeInterp -> HscEnv -> Module -> IO () +loadModule interp0 hsc_env mod = do + initLoaderState interp0 hsc_env + modifyLoaderState_ interp0 $ \interp pls -> do (pls', ok, _, _) <- loadDependencies interp hsc_env pls noSrcSpan [mod] if failed ok then throwGhcExceptionIO (ProgramError "could not load module") @@ -1158,16 +1159,16 @@ gets actually written to the loader state, the failure to do so is tracked by -- * we also implicitly unload all temporary bindings at this point. -- unload - :: Interp + :: SafeInterp -> HscEnv -> IO () -unload interp hsc_env +unload interp0 hsc_env = mask_ $ do -- mask, so we're safe from Ctrl-C in here -- Initialise the linker (if it's not been done already) - initLoaderState interp hsc_env + initLoaderState interp0 hsc_env - _new_pls <- modifyLoaderState interp $ \pls -> do + _new_pls <- modifyLoaderState interp0 $ \interp pls -> do pls1 <- unload_wkr interp pls return (pls1, pls1) @@ -1234,7 +1235,7 @@ showLS (BytecodeLibrary nm) = "(bytecode) " ++ nm -- automatically, and it doesn't matter what order you specify the input -- packages. -- -loadPackages :: Interp -> HscEnv -> [UnitId] -> IO () +loadPackages :: SafeInterp -> HscEnv -> [UnitId] -> IO () -- NOTE: in fact, since each module tracks all the packages it depends on, -- we don't really need to use the package-config dependencies. -- @@ -1243,11 +1244,11 @@ loadPackages :: Interp -> HscEnv -> [UnitId] -> IO () -- perhaps makes the error message a bit more localised if we get a link -- failure. So the dependency walking code is still here. -loadPackages interp hsc_env new_pkgs = do +loadPackages interp0 hsc_env new_pkgs = do -- It's probably not safe to try to load packages concurrently, so we take -- a lock. - initLoaderState interp hsc_env - modifyLoaderState_ interp $ \pls -> + initLoaderState interp0 hsc_env + modifyLoaderState_ interp0 $ \interp pls -> loadPackages' interp hsc_env new_pkgs pls -- | Compute 'LoadedPkgInfo' metadata (with transitive deps) for new packages, ===================================== compiler/GHC/Runtime/Eval.hs ===================================== @@ -468,7 +468,7 @@ resumeExec step mbCnt r = do | otherwise -> pure prevHistoryLst handleRunStatus step eval_opts expr bindings final_ids status =<< hist' -setupBreakpoint :: GhcMonad m => Interp -> InternalBreakpointId -> Int -> m () -- #19157 +setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157 setupBreakpoint interp ibi cnt = do hug <- hsc_HUG <$> getSession liftIO $ do @@ -476,18 +476,18 @@ setupBreakpoint interp ibi cnt = do breakArray <- getBreakArray interp ibi modBreaks GHCi.storeBreakpoint interp breakArray (ibi_info_index ibi) cnt -getBreakArray :: Interp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray) +getBreakArray :: SafeInterp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray) getBreakArray interp InternalBreakpointId{ibi_info_mod} imbs = do breaks0 <- bco_linked_breaks . homePackage_loaded . bco_loader_state . fromMaybe (panic "Loader not initialised") <$> getLoaderState interp case lookupModuleEnv (breakarray_env breaks0) ibi_info_mod of Just ba -> return ba Nothing -> do - modifyLoaderState interp $ \ld_st -> do + modifyLoaderState interp $ \interp' ld_st -> do let lb = bco_linked_breaks . homePackage_loaded . bco_loader_state $ ld_st -- Recall that BreakArrays are allocated only at BCO link time, so if we -- haven't linked the BCOs we intend to break at yet, we allocate the arrays here. - ba_env <- allocateBreakArrays interp (breakarray_env lb) [imbs] + ba_env <- allocateBreakArrays interp' (breakarray_env lb) [imbs] let ld_st' = modifyBytecodeLoaderState modifyHomePackageBytecodeState ld_st $ \bco_state -> bco_state { bco_linked_breaks = (bco_linked_breaks bco_state) { breakarray_env = ba_env } } let ba = expectJust {- just computed -} $ lookupModuleEnv ba_env ibi_info_mod ===================================== compiler/GHC/Runtime/Interpreter.hs ===================================== @@ -64,6 +64,9 @@ module GHC.Runtime.Interpreter -- * Reexport for convenience , Message (..) , module GHC.Runtime.Interpreter.Process + + -- * High-level interface to the interpreter + , withInterp ) where import GHC.Prelude @@ -107,6 +110,7 @@ import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import Control.Monad.Catch as MC (mask, handle, MonadThrow (..)) +import Control.Monad.STM import Data.Binary import Data.ByteString (ByteString) import qualified Data.ByteString.Short as SBS @@ -198,7 +202,7 @@ interpCmd interp msg = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> run msg -- Just run it directly #endif - ExternalInterp ext -> withExtInterp interp ext $ \inst -> + ExternalInterp ext -> withExtInterp ext $ \inst -> sendMessage inst msg -- | Calls `interpCmd` and the continuation while masked. @@ -208,13 +212,22 @@ interpCmd interp msg = case interpInstance interp of withInterpCmdMasked :: Binary a => Interp -> Message a -> (a -> IO b) -> IO b withInterpCmdMasked interp msg own = mask_ $ interpCmd interp msg >>= own -withExtInterp :: ExceptionMonad m => Interp -> ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a -withExtInterp interp ext action = stopInterpOnPipeClosed $ case ext of +-- | Passes the `Interp` to the continuation while setting up a +-- 'PipeClosedException' handler that calls 'stopInterp'. +-- +-- Will take the 'interpLoader' lock on a 'PipeClosedException'. +withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a +withInterp interp0@(SafeInterp interp) k = stopInterpOnPipeClosed $ k interp + where + stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> do + liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0 + MC.throwM e + +withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a +withExtInterp ext action = case ext of ExtJS i -> withJSInterp i action ExtWasm i -> withWasmInterp i action ExtIServ i -> withIServ i action - where - stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> liftIO (stopInterp interp) >> MC.throwM e withExtInterpStatus :: ExtInterp -> (forall d. ExtInterpStatusVar d -> m a) -> m a withExtInterpStatus ext action = case ext of @@ -294,11 +307,11 @@ withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do -- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for -- each of the results. evalStmt - :: Interp + :: SafeInterp -> EvalOpts -> EvalExpr ForeignHValue -> IO (EvalStatus_ [ForeignHValue] [HValueRef]) -evalStmt interp opts foreign_expr = do +evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do status <- withExpr foreign_expr $ \expr -> interpCmd interp (EvalStmt opts expr) handleEvalStatus interp status @@ -312,17 +325,17 @@ evalStmt interp opts foreign_expr = do cont (EvalApp fl' fr') resumeStmt - :: Interp + :: SafeInterp -> EvalOpts -> ForeignRef (ResumeContext [HValueRef]) -> IO (EvalStatus_ [ForeignHValue] [HValueRef]) -resumeStmt interp opts resume_ctxt = do +resumeStmt interp0 opts resume_ctxt = withInterp interp0 $ \interp -> do status <- withForeignRef resume_ctxt $ \rhv -> interpCmd interp (ResumeStmt opts rhv) handleEvalStatus interp status -abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO () -abandonStmt interp resume_ctxt = +abandonStmt :: SafeInterp -> ForeignRef (ResumeContext [HValueRef]) -> IO () +abandonStmt interp0 resume_ctxt = withInterp interp0 $ \ interp -> withForeignRef resume_ctxt $ \rhv -> interpCmd interp (AbandonStmt rhv) @@ -341,20 +354,20 @@ handleEvalStatus interp status = EvalSuccess <$> mapM (mkFinalizedHValue interp) rs -- | Execute an action of type @IO ()@ -evalIO :: Interp -> ForeignHValue -> IO () -evalIO interp fhv = +evalIO :: SafeInterp -> ForeignHValue -> IO () +evalIO interp0 fhv = withInterp interp0 $ \ interp -> liftIO $ withForeignRef fhv $ \fhv -> interpCmd interp (EvalIO fhv) >>= fromEvalResult -- | Execute an action of type @IO String@ -evalString :: Interp -> ForeignHValue -> IO String -evalString interp fhv = +evalString :: SafeInterp -> ForeignHValue -> IO String +evalString interp0 fhv = withInterp interp0 $ \ interp -> liftIO $ withForeignRef fhv $ \fhv -> interpCmd interp (EvalString fhv) >>= fromEvalResult -- | Execute an action of type @String -> IO String@ -evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String -evalStringToIOString interp fhv str = +evalStringToIOString :: SafeInterp -> ForeignHValue -> String -> IO String +evalStringToIOString interp0 fhv str = withInterp interp0 $ \ interp -> liftIO $ withForeignRef fhv $ \fhv -> interpCmd interp (EvalStringToString fhv str) >>= fromEvalResult @@ -388,44 +401,44 @@ addHpcModule :: Interp -> SBS.ShortByteString -> Int -> Int -> SBS.ShortByteStri addHpcModule interp modLabel tickNo hash tickboxes = interpCmd interp (AddHpcModule modLabel tickNo hash tickboxes) -costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String] -costCentreStackInfo interp ccs = +costCentreStackInfo :: SafeInterp -> RemotePtr CostCentreStack -> IO [String] +costCentreStackInfo interp0 ccs = withInterp interp0 $ \interp -> interpCmd interp (CostCentreStackInfo ccs) newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray) newBreakArray interp size = withInterpCmdMasked interp (NewBreakArray size) (mkFinalizedHValue interp) -storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO () -storeBreakpoint interp ref ix cnt = do -- #19157 +storeBreakpoint :: SafeInterp -> ForeignRef BreakArray -> Int -> Int -> IO () +storeBreakpoint interp0 ref ix cnt = withInterp interp0 $ \ interp -> do -- #19157 withForeignRef ref $ \breakarray -> interpCmd interp (SetupBreakpoint breakarray ix cnt) -breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool -breakpointStatus interp ref ix = +breakpointStatus :: SafeInterp -> ForeignRef BreakArray -> Int -> IO Bool +breakpointStatus interp0 ref ix = withInterp interp0 $ \ interp -> withForeignRef ref $ \breakarray -> interpCmd interp (BreakpointStatus breakarray ix) -getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue) -getBreakpointVar interp ref ix = +getBreakpointVar :: SafeInterp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue) +getBreakpointVar interp0 ref ix = withInterp interp0 $ \ interp -> withForeignRef ref $ \apStack -> withInterpCmdMasked interp (GetBreakpointVar apStack ix) (mapM (mkFinalizedHValue interp)) -getClosure :: Interp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue) -getClosure interp ref = +getClosure :: SafeInterp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue) +getClosure interp0 ref = withInterp interp0 $ \ interp -> withForeignRef ref $ \hval -> withInterpCmdMasked interp (GetClosure hval) $ mapM (mkFinalizedHValue interp) -whereFrom :: Interp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv) -whereFrom interp ref = +whereFrom :: SafeInterp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv) +whereFrom interp0 ref = withInterp interp0 $ \ interp -> withForeignRef ref $ \hval -> do interpCmd interp (WhereFrom hval) -- | Send a Seq message to the iserv process to force a value #2950 -seqHValue :: Interp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ()) -seqHValue interp unit_env logger ref = +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) handleSeqHValueStatus interp unit_env logger status @@ -649,23 +662,35 @@ spawnIServ conf = do pure inst -- | Stop the interpreter -stopInterp :: Interp -> IO () -stopInterp interp = case interpInstance interp of +stopInterp :: SafeInterp -> IO () +stopInterp = stopInterpWhen (const $ pure True) + +-- | Stop the interpreter if predicate returns 'True'. +stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO () +stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> pure () #endif - ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> do - MC.mask $ \restore -> modifyMVar mstate $ \state -> do + ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do + -- takes interpLoader lock before ExternalInterp lock to avoid deadlocks. + -- commits emptied values before 'gracefulShutdown' so we don't hold locks + -- more than necessary. + mi <- modifyMVar (loader_state (interpLoader interp)) $ \l_st -> do + modifyMVar mstate $ \state -> do case state of - InterpPending -> pure (state, Nothing) -- already stopped - InterpRunning i -> do - e <- getProcessExitCode (interpHandle (instProcess i)) >>= \case - Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing - Nothing -> gracefulShutdown i restore - modifyMVar_ (loader_state (interpLoader interp)) (const $ pure Nothing) - purgeInterpSymbolCache (interpSymbolCache interp) - modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv) - pure (InterpPending,e) + InterpPending -> pure (state, (l_st, Nothing)) -- already stopped + InterpRunning i -> shouldStop (instProcess i) >>= \case + False -> pure (state, (l_st, Nothing)) + True -> do + purgeInterpSymbolCache (interpSymbolCache interp) + modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv) + pure (InterpPending,(Nothing,Just i)) + case mi of + Nothing -> pure Nothing + Just i -> getProcessExitCode (interpHandle (instProcess i)) >>= \case + Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing + Nothing -> gracefulShutdown i restore + where gracefulShutdown i restore = do x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i))))) @@ -731,7 +756,7 @@ principle it would probably be ok, but it seems less hairy this way. -- | Creates a 'ForeignRef' that will automatically release the -- 'RemoteRef' when it is no longer referenced. -mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a) +mkFinalizedHValue :: HasInterpInstance i => i -> RemoteRef a -> IO (ForeignRef a) mkFinalizedHValue interp rref = do case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) @@ -754,13 +779,13 @@ freeHValueRefs interp refs = interpCmd interp (FreeHValueRefs refs) -- | Convert a 'ForeignRef' to the value it references directly. This -- only works when the interpreter is running in the same process as -- the compiler, so it fails when @-fexternal-interpreter@ is on. -wormhole :: Interp -> ForeignRef a -> IO a +wormhole :: SafeInterp -> ForeignRef a -> IO a wormhole interp r = wormholeRef interp (unsafeForeignRefToRemoteRef r) -- | Convert an 'RemoteRef' to the value it references directly. This -- only works when the interpreter is running in the same process as -- the compiler, so it fails when @-fexternal-interpreter@ is on. -wormholeRef :: Interp -> RemoteRef a -> IO a +wormholeRef :: SafeInterp -> RemoteRef a -> IO a wormholeRef interp _r = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> localRef _r ===================================== compiler/GHC/Runtime/Interpreter/Init.hs ===================================== @@ -29,7 +29,9 @@ import GHC.Utils.Monad import GHC.Utils.Outputable import GHC.Utils.Logger import GHC.Utils.Error + import Control.Concurrent +import Data.Coerce import System.Process data InterpOpts = InterpOpts @@ -67,8 +69,8 @@ initInterpreter -> FinderCache -> UnitEnv -> InterpOpts - -> IO (Maybe Interp) -initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = do + -> IO (Maybe SafeInterp) +initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = coerce $ do lookup_cache <- liftIO $ mkInterpSymbolCache ===================================== compiler/GHC/Runtime/Interpreter/Types.hs ===================================== @@ -4,6 +4,8 @@ -- | Types used by the runtime interpreter module GHC.Runtime.Interpreter.Types ( Interp(..) + , SafeInterp(..) + , HasInterpInstance(..) , InterpInstance(..) , InterpProcess (..) , ExtInterp (..) @@ -66,9 +68,36 @@ import System.Process ( ProcessHandle, CreateProcess ) import System.IO import GHC.Unit.Finder.Types (FinderCache, FinderOpts) +{- +Note [Interpreter locks order] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To avoid deadlocks, the 'interpLoader' lock should be taken before the lock that +contains the 'InterpStatus'. + +Further, you should wrap the code that takes the 'interpLoader' lock with +'withInterp', as it will cleanup the whole interpreter state in case the +external interpreter pipe died: +``` +withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a +``` + +'SafeInterp' is a newtype introduced to aid with the discipline: only code that +has ownership over a 'SafeInterp' should take its 'interpLoader' lock. + +-} + + + + +-- | An 'Interp' where we have not taken the 'interpLoader' lock in this thread. +-- +-- See Note [Interpreter locks order] +newtype SafeInterp = SafeInterp Interp + -- | Interpreter data Interp = Interp - { interpInstance :: !InterpInstance + { _interpInstance :: !InterpInstance -- ^ Interpreter instance (internal, external) , interpLoader :: !Loader @@ -81,6 +110,13 @@ data Interp = Interp -- ^ MallocStrings cache } +class HasInterpInstance a where + interpInstance :: a -> InterpInstance +instance HasInterpInstance SafeInterp where + interpInstance (SafeInterp interp) = interpInstance interp +instance HasInterpInstance Interp where + interpInstance = _interpInstance + data InterpInstance = ExternalInterp !ExtInterp -- ^ External interpreter #if defined(HAVE_INTERNAL_INTERPRETER) @@ -143,7 +179,7 @@ data ExtInterpInstance c = ExtInterpInstance } -- | Interpreter uses Profiling way -interpreterProfiled :: Interp -> Bool +interpreterProfiled :: HasInterpInstance a => a -> Bool interpreterProfiled interp = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> hostIsProfiled @@ -154,7 +190,7 @@ interpreterProfiled interp = case interpInstance interp of ExtWasm i -> wasmInterpProfiled $ interpConfig i -- | Interpreter uses Dynamic way -interpreterDynamic :: Interp -> Bool +interpreterDynamic :: HasInterpInstance a => a -> Bool interpreterDynamic interp = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> hostIsDynamic ===================================== compiler/GHC/Runtime/Loader.hs ===================================== @@ -283,7 +283,7 @@ getValueSafely hsc_env val_name expected_type = do logger = hsc_logger hsc_env hooks = hsc_hooks hsc_env -getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded)) +getHValueSafely :: SafeInterp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded)) getHValueSafely interp hsc_env val_name expected_type = do forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name -- Now look up the names for the value and type constructor in the type environment ===================================== compiler/GHC/Tc/Gen/Splice.hs ===================================== @@ -1151,16 +1151,16 @@ runRemoteModFinalizers (ThModFinalizers finRefs) = do let withForeignRefs [] f = f [] withForeignRefs (x : xs) f = withForeignRef x $ \r -> withForeignRefs xs $ \rs -> f (r : rs) - interp <- tcGetInterp + interp0 <- tcGetInterp - case interpInstance interp of + withInterp interp0 $ \interp -> case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> do qs <- liftIO (withForeignRefs finRefs $ mapM localRef) runQinTcM $ sequence_ qs #endif - ExternalInterp ext -> withExtInterp interp ext $ \inst -> do + ExternalInterp ext -> withExtInterp ext $ \inst -> do tcg <- getGblEnv th_state <- readTcRef (tcg_th_remote_state tcg) case th_state of @@ -1807,17 +1807,17 @@ runTHDec = runTH THDec runTH :: Binary a => THResultType -> ForeignHValue -> TcM a runTH ty fhv = do - interp <- tcGetInterp - case interpInstance interp of + interp0 <- tcGetInterp + withInterp interp0 $ \ interp -> case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> do -- Run it in the local TcM - hv <- liftIO $ wormhole interp fhv + hv <- liftIO $ wormhole interp0 fhv r <- runQinTcM (unsafeCoerce hv :: TH.Q a) return r #endif - ExternalInterp ext -> withExtInterp interp ext $ \inst -> do + ExternalInterp ext -> withExtInterp ext $ \inst -> do -- Run it on the server. For an overview of how TH works with -- Remote GHCi, see Note [Remote Template Haskell] in -- libraries/ghci/GHCi/TH.hs. @@ -3031,7 +3031,7 @@ mkThAppTs fun_ty arg_tys = foldl' TH.AppT fun_ty arg_tys noTH :: UnrepresentableTypeDescr -> Type -> TcM a noTH s d = failWithTc $ TcRnTHError $ THReifyError $ CannotRepresentType s d -tcGetInterp :: TcM Interp +tcGetInterp :: TcM SafeInterp tcGetInterp = do hsc_env <- getTopEnv case hsc_interp hsc_env of ===================================== ghc/GHCi/UI/Monad.hs ===================================== @@ -475,8 +475,8 @@ printStats dflags ActionStats{actionAllocs = mallocs, actionElapsedTime = secs} revertCAFs :: GhciMonad m => m () revertCAFs = do - interp <- hscInterp <$> GHC.getSession - liftIO $ interpCmd interp RtsRevertCAFs + interp0 <- hscInterp <$> GHC.getSession + liftIO $ withInterp interp0 $ \interp -> interpCmd interp RtsRevertCAFs s <- getGHCiState when (not (ghc_e s)) turnOffBuffering -- Have to turn off buffering again, because we just ===================================== libraries/ghci/GHCi/Message.hs ===================================== @@ -27,7 +27,7 @@ module GHCi.Message , QState(..) , getMessage, putMessage, getTHMessage, putTHMessage - , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe + , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe, isPipeOpen , remoteCall, remoteCallInterleaving, remoteTHCall , handleRemoteCall, handleRemoteTHCall, writeReply , RemoteProcessException(..), PipeClosedException(..) ===================================== libraries/ghci/GHCi/Message/Async.hs ===================================== @@ -8,6 +8,7 @@ module GHCi.Message.Async -- * Pipes Pipe(..), mkPipeFromHandles, mkPipeFromContinuations , closePipe, PipeClosedException(..) + , closingPipe, isPipeOpen -- * Interface for async bidirectional RPC , remoteAsyncReq, handleAsyncReq @@ -31,7 +32,7 @@ module GHCi.Message.Async -- * Serializable exceptions , SerializableException(..) - , toSerializableException, fromSerializableException, closingPipe + , toSerializableException, fromSerializableException ) where import Prelude -- See note [Why do we import Prelude here?] @@ -159,6 +160,11 @@ closePipe Pipe{..} = do throwTo (asyncFillTid pipeAsyncMngr) PipeWriteClosedException `finally` throwTo (asyncDrainTid pipeAsyncMngr) PipeReadClosedException +isPipeOpen :: Pipe -> STM Bool +isPipeOpen pipe = liftM2 (&&) + (isOpen <$> readTVar (pipeReadStatus pipe)) + (isOpen <$> readTVar (pipeWriteStatus pipe)) + closingPipeEnd :: TVar PipeEndStatus -> STM PipeEndStatus closingPipeEnd v = readTVar v >>= \ s -> do case s of ===================================== testsuite/tests/ghci/interp-cancellation/all.T ===================================== @@ -8,3 +8,14 @@ test('interp-cancellation', ], multimod_compile_and_run, ['Main.hs', '-package ghc -package ghci']) + +test('interp-concurrent', + [ extra_run_opts(f'"{config.libdir}"') + , windows_skip + , when(config.cross, skip) + , req_th + , unless(config.have_ext_interp, skip) + , only_ways(['normal']) + ], + compile_and_run, + ['-package ghc -threaded']) ===================================== testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs ===================================== @@ -0,0 +1,271 @@ +{-# LANGUAGE LambdaCase, ScopedTypeVariables #-} + +-- | Several threads share one GHC session, and so one external interpreter. +-- +-- Checks that concurrent requests get their own replies, that killing threads +-- waiting on the interpreter leaves it usable, that killing a thread running a +-- splice cancels the splice in the interpreter, and that when the interpreter +-- dies it is stopped and the next request starts a new one. +module Main (main) where + +import Control.Concurrent +import Control.Exception +import Control.Monad +import Control.Monad.IO.Class (liftIO) +import Data.Either (isLeft) +import Data.Maybe (isJust, isNothing) +import System.Directory (doesFileExist, removeFile) +import System.Environment (getArgs) +import System.Exit (exitFailure) +import System.IO +import System.Posix.Signals (sigKILL, signalProcess) +import System.Process (ProcessHandle, getPid, getProcessExitCode) +import System.Timeout (timeout) + +import GHC +import GHC.Driver.Env (hscInterp) +import GHC.Driver.Monad (Session, reflectGhc, reifyGhc) +import GHC.Driver.Session (gopt_set, xopt_set) +import qualified GHC.LanguageExtensions as LangExt +import GHC.Runtime.Interpreter (evalString, evalStringToIOString) +import GHC.Runtime.Interpreter.Types +import GHCi.Message (PipeClosedException) + +main :: IO () +main = do + hSetBuffering stdout LineBuffering + [libdir] <- getArgs + mapM_ removeIfExists markers + runGhc (Just libdir) $ do + -- compileExprRemote parses with the interactive flags but typechecks with + -- the session ones, so TH goes in both. xopt_set doesn't add implied + -- extensions, so the quotes one is set too. + let withTH fs = foldl xopt_set fs + [LangExt.TemplateHaskell, LangExt.TemplateHaskellQuotes] + dflags <- getSessionDynFlags + _ <- setSessionDynFlags (withTH (gopt_set dflags Opt_ExternalInterpreter)) + { ghcLink = LinkInMemory } + getInteractiveDynFlags >>= setInteractiveDynFlags . withTH + setContext [ IIDecl (simpleImportDecl (mkModuleName m)) + | m <- [ "Prelude", "Control.Concurrent", "Control.Exception" + , "System.IO", "System.IO.Error", "Language.Haskell.TH" ] ] + reifyGhc $ \s -> do + concurrentReplies s + killWaiting s + killSplice s + interpreterDies s + +-------------------------------------------------------------------------------- +-- Scenarios + +concurrentReplies :: Session -> IO () +concurrentReplies s = do + echo <- compile s echoExpr + ws <- forM [1 .. 16 :: Int] $ \n -> async $ + forM [1 .. 50 :: Int] $ \k -> do + let x = show (n, k) + (== reverse x) <$> evalEcho s echo x + rs <- mapM (within "concurrent requests" . readMVar . snd) ws + check "concurrent requests each get their own reply" + (all (either (const False) and) rs) + +-- | Kill threads waiting on two gated requests, and check a third request +-- made alongside them still gets its reply. +-- +-- Whether the interpreter runs b behind a or alongside it, and whether it +-- interrupts a cancelled one, b is still waiting when killed. The gates only +-- open after the kills, so whatever is still running in the interpreter can +-- finish and let c through. +killWaiting :: Session -> IO () +killWaiting s = do + echo <- compile s echoExpr + -- Compiled up front: compiling needs the interpreter, which a may hold up. + bAct <- compile s (gated "b.started" "b.gate" "pure \"b\"") + (a, aRes) <- async $ inSession s $ + execStmt (gated "a.started" "a.gate" "pure ()") execOptions + awaitStarted "the statement to start" "a.started" aRes + (b, bRes) <- async $ evalFHV s bAct + (_, cRes) <- async $ evalEcho s echo "c" + threadDelay 100000 -- let b and c send their requests + within "killing the thread waiting on the statement" (killThread a) + within "killing the thread waiting on the other one" (killThread b) + aR <- within "the killed statement thread to finish" (readMVar aRes) + bR <- within "the other killed thread to finish" (readMVar bRes) + check "killed threads stop waiting for their replies" + (isKilled aR && isKilled bR) + mapM_ (`writeFile` "") ["a.gate", "b.gate"] + cR <- within "the remaining request's reply" (readMVar cRes) + check "a request made alongside cancelled ones gets its reply" + (either (const False) (== reverse "c") cR) + stillAnswers s echo + +-- | Splices run in their own thread in the interpreter, so they don't hold up +-- other requests, and can be cancelled there. +killSplice :: Session -> IO () +killSplice s = do + echo <- compile s echoExpr + (t, tRes) <- async $ inSession s $ + compileExprRemote (blockingSplice "th.started" "th.cancelled") + awaitStarted "the splice to start" "th.started" tRes + r <- within "a request while a splice runs" (evalEcho s echo "during splice") + check "a running splice does not hold up other requests" + (r == reverse "during splice") + within "killing the thread running the splice" (killThread t) + tR <- within "the killed splice thread to finish" (readMVar tRes) + check "the thread running the splice is killed" (isKilled tR) + awaitFile "the splice to be cancelled in the interpreter" "th.cancelled" + check "the splice is cancelled in the interpreter" True + stillAnswers s echo + +-- | Kill the interpreter while one thread waits on a statement and another +-- runs a splice. +interpreterDies :: Session -> IO () +interpreterDies s = do + _ <- compile s echoExpr + ph <- runningInterp s >>= maybe (failWith "no interpreter running") pure + pid <- getPid ph >>= maybe (failWith "interpreter has no pid") pure + + -- Splice first: compiling it needs the interpreter, which the statement + -- may hold up. + (_, fRes) <- async $ inSession s $ + compileExprRemote (blockingSplice "f.started" "f.cancelled") + awaitStarted "the splice to start" "f.started" fRes + (_, dRes) <- async $ evalIn s (gated "d.started" "d.gate" "pure \"d\"") + awaitStarted "the statement to start" "d.started" dRes + + signalProcess sigKILL pid + dR <- within "the statement thread to fail" (readMVar dRes) + check "a thread waiting on a dead interpreter gets PipeClosedException" + (isPipeClosed dR) + fR <- within "the splice thread to fail" (readMVar fRes) + check "a thread running a splice in a dead interpreter fails" (isLeft fR) + + st <- runningInterp s + check "the dead interpreter is stopped" (isNothing st) + ex <- getProcessExitCode ph + check "its process is reaped" (isJust ex) + + r <- within "a request after the interpreter died" + (evalIn s "pure \"alive\" :: IO String") + check "the next request starts a new interpreter" (r == "alive") + ph' <- runningInterp s >>= maybe (failWith "no interpreter running") pure + pid' <- getPid ph' + check "the new interpreter is a different process" (pid' /= Just pid) + +-------------------------------------------------------------------------------- +-- Talking to the interpreter through the session + +inSession :: Session -> Ghc a -> IO a +inSession = flip reflectGhc + +compile :: Session -> String -> IO ForeignHValue +compile s e = inSession s (compileExprRemote e) + +-- | Compile an @IO String@ and run it. +evalIn :: Session -> String -> IO String +evalIn s e = compile s e >>= evalFHV s + +-- | Run a compiled @IO String@. +evalFHV :: Session -> ForeignHValue -> IO String +evalFHV s fhv = inSession s $ do + hsc_env <- getSession + liftIO (evalString (hscInterp hsc_env) fhv) + +evalEcho :: Session -> ForeignHValue -> String -> IO String +evalEcho s echo x = inSession s $ do + hsc_env <- getSession + liftIO (evalStringToIOString (hscInterp hsc_env) echo x) + +stillAnswers :: Session -> ForeignHValue -> IO () +stillAnswers s echo = do + r <- within "a request after the cancellations" (evalEcho s echo "after") + check "the interpreter still answers" (r == reverse "after") + +runningInterp :: Session -> IO (Maybe ProcessHandle) +runningInterp s = do + interp <- inSession s (hscInterp <$> getSession) + case interpInstance interp of + ExternalInterp (ExtIServ st) -> readMVar (interpStatus st) >>= \case + InterpRunning inst -> pure (Just (interpHandle (instProcess inst))) + InterpPending -> pure Nothing + _ -> failWith "not using an external interpreter" + +-------------------------------------------------------------------------------- +-- Interpreted code + +echoExpr :: String +echoExpr = "(\\x -> pure (reverse x)) :: String -> IO String" + +-- | Creates @started@, waits for @gate@ to exist, then runs @k@. +gated :: FilePath -> FilePath -> String -> String +gated started gate k = concat + [ "let { waitFor p = catchIOError (withFile p ReadMode (\\_ -> pure ()))" + , " (\\_ -> threadDelay 10000 >> waitFor p) }" + , " in writeFile ", show started, " \"\" >> waitFor ", show gate, " >> ", k ] + +-- | Creates @started@, then blocks. Creates @cancelled@ if interrupted. +blockingSplice :: FilePath -> FilePath -> String +blockingSplice started cancelled = concat + [ "$(runIO (writeFile ", show started, " \"\"" + , " >> (threadDelay 100000000 `onException` writeFile ", show cancelled, " \"\"))" + , " >> [| () |])" ] + +markers :: [FilePath] +markers = [ "a.started", "a.gate", "b.started", "b.gate" + , "th.started", "th.cancelled" + , "d.started", "d.gate", "f.started", "f.cancelled" ] + +-------------------------------------------------------------------------------- +-- Utilities + +async :: IO a -> IO (ThreadId, MVar (Either SomeException a)) +async act = do + v <- newEmptyMVar + t <- forkFinally act (putMVar v) + pure (t, v) + +awaitFile :: String -> FilePath -> IO () +awaitFile what p = within what loop + where + loop = doesFileExist p >>= \b -> unless b (threadDelay 10000 >> loop) + +-- | Like 'awaitFile', but fails straight away if the thread that should +-- create the file ends first. +awaitStarted :: String -> FilePath -> MVar (Either SomeException a) -> IO () +awaitStarted what p res = within what loop + where + loop = do + b <- doesFileExist p + unless b $ tryReadMVar res >>= \case + Just r -> failWith ("waiting for " ++ what ++ ", the thread ended: " + ++ either show (const "no exception") r) + Nothing -> threadDelay 10000 >> loop + +removeIfExists :: FilePath -> IO () +removeIfExists p = removeFile p `catch` \(_ :: IOException) -> pure () + +isKilled :: Either SomeException a -> Bool +isKilled = \case + Left e | Just ThreadKilled <- fromException e -> True + _ -> False + +isPipeClosed :: Either SomeException a -> Bool +isPipeClosed = \case + Left e | Just (_ :: PipeClosedException) <- fromException e -> True + _ -> False + +-- | Fail rather than hang. +within :: String -> IO a -> IO a +within what act = + timeout (60 * 1000000) act >>= maybe (failWith ("timed out waiting for " ++ what)) pure + +failWith :: String -> IO a +failWith what = do + hPutStrLn stderr ("FAILED: " ++ what) + hFlush stderr + exitFailure + +check :: String -> Bool -> IO () +check what ok + | ok = putStrLn ("ok: " ++ what) + | otherwise = void (failWith what) ===================================== testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout ===================================== @@ -0,0 +1,14 @@ +ok: concurrent requests each get their own reply +ok: killed threads stop waiting for their replies +ok: a request made alongside cancelled ones gets its reply +ok: the interpreter still answers +ok: a running splice does not hold up other requests +ok: the thread running the splice is killed +ok: the splice is cancelled in the interpreter +ok: the interpreter still answers +ok: a thread waiting on a dead interpreter gets PipeClosedException +ok: a thread running a splice in a dead interpreter fails +ok: the dead interpreter is stopped +ok: its process is reaped +ok: the next request starts a new interpreter +ok: the new interpreter is a different process View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/a30a4599674b3609cc5701cb17247eb... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/a30a4599674b3609cc5701cb17247eb... 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