Andrea Vezzosi pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC Commits: 6cd10a7b by Andrea Vezzosi at 2026-11-30T20:20:22+01:00 interp: print exit code if non-zero when iserv terminates - - - - - 600082b8 by Andrea Vezzosi at 2026-11-30T20:24:15+01:00 interp: throw exceptions while reading/writing as PipeClosedException too - - - - - 4 changed files: - compiler/GHC/Runtime/Interpreter.hs - compiler/GHC/Runtime/Interpreter/Types.hs - libraries/ghci/GHCi/Message/Async.hs - libraries/ghci/GHCi/Server.hs Changes: ===================================== compiler/GHC/Runtime/Interpreter.hs ===================================== @@ -115,12 +115,14 @@ import Control.Monad.STM import Data.Binary import Data.ByteString (ByteString) import qualified Data.ByteString.Short as SBS +import Data.IORef import qualified GHC.Exts.Heap as Heap import GHC.Stack.CCS (CostCentre,CostCentreStack) import System.Directory import System.Process import System.Timeout (timeout) import qualified GHC.InfoProv as InfoProv +import System.Exit import GHC.Builtin.Modules( gHC_PRIM, gHC_PRIMOPWRAPPERS ) import GHC.Types.Name @@ -232,8 +234,13 @@ 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 + mec <- liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0 + maybe (MC.throwM e) (liftIO . throwInterpreterTerminated . Just) mec + +throwInterpreterTerminated :: Maybe ExitCode -> IO a +throwInterpreterTerminated ec = do + throwIO $ InstallationError $ "External interpreter terminated" + ++ case ec of Just (ExitFailure n) -> " (" ++ show n ++ ")"; _ -> "" withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a withExtInterp ext action = case ext of @@ -281,6 +288,7 @@ spawnInterpMaybe cfg spawn mstatus = do -- readMVar first, so when the interp is running we don't take lock. -- Removes an interruptible point for concurrent calls. readMVar mstatus >>= \case + InterpStopped ec -> throwInterpreterTerminated =<< liftIO (readIORef ec) InterpRunning inst -> pure inst InterpPending{} -> modifyMVarMasked mstatus $ \case -- start the external iserv process if we haven't done so yet @@ -290,6 +298,7 @@ spawnInterpMaybe cfg spawn mstatus = do InterpRunning inst -> do pure (InterpRunning inst, inst) + InterpStopped ec -> throwInterpreterTerminated =<< liftIO (readIORef ec) -- free any ForeignRef that have been garbage collected. -- or any other pending RemoteResource. @@ -310,8 +319,9 @@ withExtInterpMaybe => ExtInterp -> (forall d. Maybe (ExtInterpInstance d) -> m a) -> m a withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do liftIO (readMVar mstate) >>= \case - InterpPending {} -> action Nothing -- already shut down or never launched + InterpPending {} -> action Nothing InterpRunning inst -> action (Just inst) + InterpStopped {} -> action Nothing -- ----------------------------------------------------------------------------- -- Wrappers around messages @@ -674,38 +684,47 @@ spawnIServ conf = do pure inst -- | Stop the interpreter -stopInterp :: SafeInterp -> IO () +stopInterp :: SafeInterp -> IO (Maybe ExitCode) stopInterp = stopInterpWhen (const $ pure True) -- | Stop the interpreter if predicate returns 'True'. -stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO () +stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO (Maybe ExitCode) stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) - InternalInterp -> pure () + InternalInterp -> pure Nothing #endif - ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do + ExternalInterp ext -> (either throwIO pure =<<) $ 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, (l_st, Nothing)) -- already stopped + InterpStopped{} -> pure (state, (l_st, Nothing)) -- already stopped + InterpPending -> newIORef Nothing >>= \ec -> pure (InterpStopped ec, (l_st, Nothing)) 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)) + ec <- newIORef Nothing + pure (InterpStopped ec,(Nothing,Just (i,ec))) 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 + Nothing -> pure $ Right Nothing + Just (i,ecRef) -> getProcessExitCode (interpHandle (instProcess i)) >>= \case + Just exitCode -> do + writeExitCode ecRef (Just exitCode) + closePipe (interpPipe (instProcess i)) + pure (Right $ Just exitCode) + Nothing -> gracefulShutdown i ecRef restore where - gracefulShutdown i restore = do + writeExitCode _ref Nothing = pure () + writeExitCode ref (Just ec) = atomicWriteIORef ref (Just ec) + gracefulShutdown :: ExtInterpInstance c -> IORef (Maybe ExitCode) -> (forall a. IO a -> IO a) -> IO (Either SomeException (Maybe ExitCode)) + gracefulShutdown i ecRef restore = do x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i))))) + print x let ph = interpHandle (instProcess i) e <- case x of -- happy path: ext. interp. should be shutting down of its own accord. @@ -718,8 +737,9 @@ stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of Left e -> do terminateProcess ph returnUnexpectedException e - void $ timeLimited restore $ void $ waitForProcess ph - pure e + mexitCode <- timeLimited restore $ waitForProcess ph + writeExitCode ecRef mexitCode + pure $ maybe (Right mexitCode) Left e timeLimited restore m = timeout 1_000_000 (restore m) returnUnexpectedException e | Just (_ :: PipeClosedException) <- fromException e = return Nothing ===================================== compiler/GHC/Runtime/Interpreter/Types.hs ===================================== @@ -64,6 +64,8 @@ import GHC.StgToJS.Linker.Types import GHC.Runtime.Interpreter.Types.SymbolCache import Control.Concurrent +import Data.IORef +import System.Exit import System.Process ( ProcessHandle, CreateProcess ) import System.IO import GHC.Unit.Finder.Types (FinderCache, FinderOpts) @@ -153,6 +155,7 @@ data InterpProcess = InterpProcess data InterpStatus inst = InterpPending -- ^ Not spawned yet | InterpRunning !inst -- ^ Running + | InterpStopped !(IORef (Maybe ExitCode)) -- ^ Died already. -- | Configuration needed to spawn an external interpreter data IServConfig = IServConfig ===================================== libraries/ghci/GHCi/Message/Async.hs ===================================== @@ -160,8 +160,8 @@ mkPipeFromContinuations getSome putAll pipeCloseRead pipeCloseWrite = mdo -- too. closePipe :: Pipe -> IO () closePipe Pipe{..} = do - throwTo (asyncFillTid pipeAsyncMngr) PipeWriteClosedException - `finally` throwTo (asyncDrainTid pipeAsyncMngr) PipeReadClosedException + throwTo (asyncFillTid pipeAsyncMngr) (PipeWriteClosedException Nothing) + `finally` throwTo (asyncDrainTid pipeAsyncMngr) (PipeReadClosedException Nothing) isPipeOpen :: Pipe -> STM Bool isPipeOpen pipe = liftM2 (&&) @@ -190,12 +190,11 @@ closingPipe p = atomically $ do -- | Exception thrown/reported when attempting to read or write on a closed pipe. -- --- Errors occurring while reading or writing will show up as the original --- exception instead (e.g. IOException). +-- Errors occurring while reading or writing are wrapped with this. data PipeClosedException - = PipeReadClosedException -- ^ We've closed the pipe read end on this process + = PipeReadClosedException {inner :: Maybe SomeException} -- ^ We've closed the pipe read end on this process - | PipeWriteClosedException -- ^ We've closed the pipe write end on this process + | PipeWriteClosedException {inner :: Maybe SomeException} -- ^ We've closed the pipe write end on this process deriving Show instance Exception PipeClosedException @@ -287,7 +286,7 @@ handleAsyncReq pipe getit mii k = mask $ \restore -> do (uq,bs) <- atomically $ do readTVar (pipeWriteStatus pipe) >>= \ s -> case isActive s of -- We will not be able to write the reply, so no point in continuiting. - False -> throwSTM PipeWriteClosedException + False -> throwSTM $ PipeWriteClosedException Nothing True -> pure () taken <- case mii of Nothing -> tryReadTQueue $ requestsQueue am @@ -295,7 +294,7 @@ handleAsyncReq pipe getit mii k = mask $ \restore -> do case taken of Just req -> pure req Nothing -> isActive <$> readTVar (pipeReadStatus pipe) >>= \case - False -> throwSTM PipeReadClosedException -- can't expect reqs + False -> throwSTM $ PipeReadClosedException Nothing -- can't expect reqs True -> retry let @@ -364,9 +363,9 @@ remoteAsyncReqWithResponse pipe msg ii = do wv <- newEmptyTMVarIO atomically $ readTVar (pipeReadStatus pipe) >>= \ readEnd -> case isActive readEnd of - False -> pure $ NotWritten PipeReadClosedException + False -> pure $ NotWritten $ PipeReadClosedException Nothing True -> writePipeAsync pipe (Request uq ii (runPut msg)) >>= \case - Nothing -> pure $ NotWritten PipeWriteClosedException + Nothing -> pure $ NotWritten $ PipeWriteClosedException Nothing Just waitWritten -> do -- request queued, so we register a pending reply. After this tx we -- always expect a reply, and when it arrives 'drainPipe' will clean up 'pendingReplies'. @@ -562,7 +561,7 @@ newAsyncManager pipe = do -- -- Closes the Pipe read end when done reading drainPipe :: Pipe -> (forall x. IO x -> IO x) -> IO () -drainPipe p unmask = catch loop (void . replyToPendings) where +drainPipe p unmask = catch loop (void . replyToPendings . toException . PipeReadClosedException . Just) where loop = do unmask (readPipe p) >>= \case Just msg -> do @@ -571,7 +570,7 @@ drainPipe p unmask = catch loop (void . replyToPendings) where -- EOF on read handle Nothing -> do -- exit loop - throwIO PipeReadClosedException + throwIO $ PipeReadClosedException Nothing handleMsg = \case -- Receive a reply to a pending notification Reply uq bs -> do @@ -676,9 +675,9 @@ fillPipe p unmask = loop `catch` cleanup Nothing where Nothing -> pure () Just var -> do -- report exception to the originating write - putTMVar var . Left $ if isOpen s then e0 else toException PipeWriteClosedException + putTMVar var . Left . toException $ PipeWriteClosedException $ if isOpen s then Just e0 else Nothing -- real exception already reported once - failPendingWrites p $ toException PipeWriteClosedException + failPendingWrites p $ toException $ PipeWriteClosedException Nothing failPendingWrites :: Pipe -> SomeException -> STM () failPendingWrites p e = do @@ -714,7 +713,7 @@ data ReplyResult replyResultMaybeThrow :: ReplyResult -> IO () replyResultMaybeThrow = \case - ReplyNotWritten -> throwIO PipeWriteClosedException + ReplyNotWritten -> throwIO $ PipeWriteClosedException Nothing ReplyWritingError e -> throwIO e ReplyWritingSuccess -> pure () ===================================== libraries/ghci/GHCi/Server.hs ===================================== @@ -105,7 +105,8 @@ servWithCustom verbose hook pipe restore customHandler = do -- reported as a different exception type. ignorePipeClosedException = \case ReplyWritingError e - | Just _ <- fromException @PipeClosedException e + | Just e' <- fromException @PipeClosedException e + , Nothing <- inner e' -> pure () | otherwise -> throwIO e View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/b2f8d4cf53c2e82775e3a88e23c9aa6... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/b2f8d4cf53c2e82775e3a88e23c9aa6... 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)