Andrea Vezzosi pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC Commits: a30a4599 by Andrea Vezzosi at 2026-11-16T12:27:36+01:00 fixup! runWithPipes: avoid race to close their end on windows - - - - - 000d737c by Andrea Vezzosi at 2026-11-16T17:27:25+01:00 interp: cleanup with stopInterp outside interpLoader lock - - - - - 13 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 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 @@ -198,7 +201,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 +211,20 @@ 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) -> liftIO (stopInterp 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 +304,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 +322,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 +351,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 +398,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 +659,29 @@ spawnIServ conf = do pure inst -- | Stop the interpreter -stopInterp :: Interp -> IO () -stopInterp interp = case interpInstance interp of +stopInterp :: SafeInterp -> IO () +stopInterp (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 + InterpPending -> pure (state, (l_st, 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) + 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 +747,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 +770,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 ===================================== @@ -76,6 +76,12 @@ toFdHandleIfNeeded h 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 ===================================== 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 View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/76c49a91c44801ad9e4c9f5f6f957f4... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/76c49a91c44801ad9e4c9f5f6f957f4... 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