[Git][ghc/ghc][wip/romes/async-rpc] 6 commits: runWithPipes: fix on Windows when without -threaded
Andrea Vezzosi pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC Commits: 2bd5c810 by Andrea Vezzosi at 2026-11-17T13:27:47+01:00 runWithPipes: fix on Windows when without -threaded Test 'static-plugin-interp-panic' happens to build without -threaded and would timeout on Windows CI. Turns out that in such a configuration the 'Handle's we get from 'System.Process.CommunicationHandle' cause the whole process to lock. Rebuilding them with 'hANDLEToHandle' fixes it. - - - - - 6de946f5 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00 interp: close pipes more promptly - - - - - 0b9d2cf5 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00 interp: time limit closePipe in stopInterp - - - - - 43341d18 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00 runWithPipes: avoid race to close their end on windows `closeCommunicationHandle` will query info about the raw handle, using windows primitives that block while a ReadFile is pending. We call it right after createProcess for `iserv`, but `iserv` might still start reading from the pipe first. If that happens then there's a deadlock, because we won't write anything for iserv to read until we are done closing its read end in our process. The fix is to use `closeHandle` directly, as that won't block for pending reads. - - - - - 5fbd333c by Andrea Vezzosi at 2026-11-17T13:30:00+01:00 interp: cleanup with stopInterp outside interpLoader lock On a PipeClosedException we want to stop the running external interpreter and reset the state of the `Interp`, which includes the loader state. So, to avoid deadlocks, we now have the PipeClosedException handler outside of places where we take the loader state lock. A new `SafeInterp` type is introduced to aid with this discipline: functions that take a bare `Interp` must not take the loader state lock themselves. We also fix a race between restarting the interpreter and the PipeClosedException cleanup: if an interpreter's Pipe is open we don't terminate it, as it must be a new instance. - - - - - abdfbbf3 by Andrea Vezzosi at 2026-11-17T14:34:55+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. - - - - - 18 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/Runtime/Utils.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,26 +662,38 @@ 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 (timeLimited restore $ sendMessage i Shutdown `finally` closePipe (interpPipe (instProcess i))) + x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i))))) let ph = interpHandle (instProcess i) e <- case x of -- happy path: ext. interp. should be shutting down of its own accord. @@ -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/Runtime/Utils.hs ===================================== @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + module GHC.Runtime.Utils ( runWithPipes ) @@ -10,6 +12,14 @@ import System.Process import System.Process.CommunicationHandle import System.IO +#if defined(mingw32_HOST_OS) +import Control.Concurrent (rtsSupportsBoundThreads) +import GHC.IO.Handle.Windows (handleToHANDLE) +import GHC.IO.SubSystem (isWindowsNativeIO) +import System.Process.CommunicationHandle.Internal (CommunicationHandle(..)) +import qualified System.Win32 as Win32 +#endif + -- | Spawn a process connected to us by two pipes. Important to close our copy -- of the endpoints passed to the child so each side only keeps open copies it -- needs. If we don't do that, then closing one end wouldn't interrupt reads on @@ -17,14 +27,64 @@ import System.IO runWithPipes :: (CreateProcess -> IO ProcessHandle) -> FilePath -> [String] -> [String] -> IO (ProcessHandle, Handle, Handle) runWithPipes createProc prog pre_opts opts = do - (rh, chTheyWrite) <- createWeReadTheyWritePipe - (chTheyRead, wh) <- createTheyReadWeWritePipe + (rh, chTheyWrite) <- fixedCreateWeReadTheyWritePipe + (chTheyRead, wh) <- fixedCreateTheyReadWeWritePipe let args = pre_opts ++ (show chTheyWrite : show chTheyRead : opts) closeTheirs = do - closeCommunicationHandle chTheyWrite - closeCommunicationHandle chTheyRead + closeTheirEnd chTheyWrite + closeTheirEnd chTheyRead -- These handles have no finalizers, so close them ourselves if the spawn fails. ph <- createProc (proc prog args) `onException` (closeTheirs >> hClose rh >> hClose wh) closeTheirs return (ph, rh, wh) + +-- | 'createWeReadTheyWritePipe', except in a non-threaded runtime on Windows +-- without WinIO. There process gives us a synchronous native 'Handle', and +-- reading from it is a safe call to @ReadFile@, which blocks every Haskell +-- thread until data arrives. As 'GHCi.Message.Async' always has a thread +-- waiting to read the pipe, no other thread would get to run. So in that case +-- we swap our end for a file descriptor 'Handle', whose reads only block the +-- reading thread. +fixedCreateWeReadTheyWritePipe :: IO (Handle, CommunicationHandle) +fixedCreateWeReadTheyWritePipe = do + (h, ch) <- createWeReadTheyWritePipe + h' <- toFdHandleIfNeeded h + return (h', ch) + +-- | 'createTheyReadWeWritePipe', with the same exception as +-- 'fixedCreateWeReadTheyWritePipe'. +fixedCreateTheyReadWeWritePipe :: IO (CommunicationHandle, Handle) +fixedCreateTheyReadWeWritePipe = do + (ch, h) <- createTheyReadWeWritePipe + h' <- toFdHandleIfNeeded h + return (ch, h') + +toFdHandleIfNeeded :: Handle -> IO Handle +#if defined(mingw32_HOST_OS) +-- The native 'Handle' has a finalizer that closes its @HANDLE@, so we wrap a +-- duplicate and close the original. +toFdHandleIfNeeded h + | not rtsSupportsBoundThreads && not isWindowsNativeIO = do + me <- Win32.getCurrentProcess + hh <- handleToHANDLE h + dup <- Win32.duplicateHandle me hh me 0 False Win32.dUPLICATE_SAME_ACCESS + hClose h + Win32.hANDLEToHandle dup + | otherwise = return h +#else +toFdHandleIfNeeded = return +#endif + +-- | Workaround for locking prone closeCommunicationHandle on windows +-- +-- Called after a createProcess: the subprocess might start reading from the +-- inherited raw handle before this close is scheduled, and, on windows, +-- closeCommunicationHandle will block on a pending read during its conversion +-- to Handle. Calling Win32.closeHandle directly avoids the blocking. +closeTheirEnd :: CommunicationHandle -> IO () +#if defined(mingw32_HOST_OS) +closeTheirEnd (CommunicationHandle h) = Win32.closeHandle h +#else +closeTheirEnd = closeCommunicationHandle +#endif ===================================== 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 @@ -598,9 +604,8 @@ drainPipe p unmask = catch loop (void . replyToPendings) where Just q -> writeTQueue q (uq,bs) Cancel uq -> cancelRequest am uq - replyToPendings e = do - atomically $ failPendingReplies p e - pipeCloseRead p `catch` \(_ :: IOException) -> pure () + replyToPendings e = finally (pipeCloseRead p `catch` \(_ :: IOException) -> pure ()) -- TODO: log with verbose. + . atomically $ failPendingReplies p e am = pipeAsyncMngr p @@ -669,8 +674,8 @@ fillPipe p unmask = loop `catch` cleanup Nothing where am = pipeAsyncMngr p - cleanup last_write e0 = do - atomically $ do + cleanup last_write e0 = finally (pipeCloseWrite p `catch` \(_ :: IOException) -> pure ()) -- TODO: log with verbose + . atomically $ do -- deactivate here too so we keep track of the exception if end still 'Open'. s <- deactivatePipeEnd (pipeWriteStatus p) (Just e0) case last_write of @@ -680,7 +685,6 @@ fillPipe p unmask = loop `catch` cleanup Nothing where putTMVar var . Left $ if isOpen s then e0 else toException PipeWriteClosedException -- real exception already reported once failPendingWrites p $ toException PipeWriteClosedException - pipeCloseWrite p `catch` \(_ :: IOException) -> pure () failPendingWrites :: Pipe -> SomeException -> STM () failPendingWrites p e = do ===================================== 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,265 @@ +{-# 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 + let withTH fs = foldl xopt_set fs + [LangExt.TemplateHaskell, LangExt.TemplateHaskellQuotes] + dflags <- getSessionDynFlags + _ <- setSessionDynFlags (withTH (gopt_set dflags Opt_ExternalInterpreter)) + { ghcLink = LinkInMemory } + 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) + (== x) <$> evalEcho s echo x + rs <- mapM (waiting "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. +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 + awaitFileUntil "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 + waiting "killing the thread waiting on the statement" (killThread a) + waiting "killing the thread waiting on the other one" (killThread b) + aR <- waiting "the killed statement thread to finish" (readMVar aRes) + bR <- waiting "the other killed thread to finish" (readMVar bRes) + check "killed threads stop waiting for their replies" + (isKilled aR && isKilled bR) + -- Let the server side evaluation of 'a' and 'b' go through, since eval + -- requests ignore canceling atm. + mapM_ (`writeFile` "") ["a.gate", "b.gate"] + cR <- waiting "the remaining request's reply" (readMVar cRes) + check "a request made alongside cancelled ones gets its reply" + (either (const False) (== "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") + awaitFileUntil "the splice to start" "th.started" tRes + r <- waiting "a request while a splice runs" (evalEcho s echo "during splice") + check "a running splice does not hold up other requests" + (r == "during splice") + waiting "killing the thread running the splice" (killThread t) + tR <- waiting "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" + -- just printing what we can infer from the previous line. + 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") + awaitFileUntil "the splice to start" "f.started" fRes + (_, dRes) <- async $ evalIn s (gated "d.started" "d.gate" "pure \"d\"") + awaitFileUntil "the statement to start" "d.started" dRes + + signalProcess sigKILL pid + dR <- waiting "the statement thread to fail" (readMVar dRes) + check "a thread waiting on a dead interpreter gets PipeClosedException" + (isPipeClosed dR) + fR <- waiting "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 <- waiting "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 <- waiting "a request after the cancellations" (evalEcho s echo "after") + check "the interpreter still answers" (r == "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 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 maxBound `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 = waiting 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. +awaitFileUntil :: String -> FilePath -> MVar (Either SomeException a) -> IO () +awaitFileUntil what p res = waiting 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 + +-- | Adds a timeout so we fail with a message rather than hang the whole test. +waiting :: String -> IO a -> IO a +waiting 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/000d737cb934a9c0d0da206d23eb875... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/000d737cb934a9c0d0da206d23eb875... 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)
-
Andrea Vezzosi (@trac-Saizan)