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
-
6de946f5
by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
-
0b9d2cf5
by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
-
43341d18
by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
-
5fbd333c
by Andrea Vezzosi at 2026-11-17T13:30:00+01:00
-
abdfbbf3
by Andrea Vezzosi at 2026-11-17T14:34:55+01:00
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:
| ... | ... | @@ -56,7 +56,7 @@ import GHC.Driver.Config.Diagnostic (initDiagOpts, initPrintConfig) |
| 56 | 56 | import GHC.Driver.Env.Types ( Hsc(..), HscEnv(..), HasHscEnv (..) )
|
| 57 | 57 | |
| 58 | 58 | import GHC.Runtime.Context
|
| 59 | -import GHC.Runtime.Interpreter.Types (Interp)
|
|
| 59 | +import GHC.Runtime.Interpreter.Types (SafeInterp)
|
|
| 60 | 60 | |
| 61 | 61 | import GHC.Unit
|
| 62 | 62 | import GHC.Unit.External.Database
|
| ... | ... | @@ -410,7 +410,7 @@ mainModIs hue = mkHomeModule (expectJust $ homeUnitEnv_home_unit hue) (mainModul |
| 410 | 410 | -- | Retrieve the target code interpreter
|
| 411 | 411 | --
|
| 412 | 412 | -- Fails if no target code interpreter is available
|
| 413 | -hscInterp :: HscEnv -> Interp
|
|
| 413 | +hscInterp :: HscEnv -> SafeInterp
|
|
| 414 | 414 | hscInterp hsc_env = case hsc_interp hsc_env of
|
| 415 | 415 | Nothing -> throw (InstallationError "Couldn't find a target code interpreter. Try with -fexternal-interpreter")
|
| 416 | 416 | Just i -> i
|
| ... | ... | @@ -14,7 +14,7 @@ import GHC.Driver.LlvmConfigCache (LlvmConfigCache) |
| 14 | 14 | |
| 15 | 15 | import GHC.Prelude
|
| 16 | 16 | import GHC.Runtime.Context
|
| 17 | -import GHC.Runtime.Interpreter.Types ( Interp )
|
|
| 17 | +import GHC.Runtime.Interpreter.Types ( SafeInterp )
|
|
| 18 | 18 | import GHC.Types.Error ( Messages )
|
| 19 | 19 | import GHC.Types.Name.Cache
|
| 20 | 20 | import GHC.Types.Target
|
| ... | ... | @@ -88,7 +88,7 @@ data HscEnv |
| 88 | 88 | -- the 'IfGblEnv'. See 'tcg_knot_vars' in 'GHC.Tc.Utils.TcGblEnv'.
|
| 89 | 89 | -- See also Note [hsc_type_env_var hack]
|
| 90 | 90 | |
| 91 | - , hsc_interp :: Maybe Interp
|
|
| 91 | + , hsc_interp :: Maybe SafeInterp
|
|
| 92 | 92 | -- ^ target code interpreter (if any) to use for TH and GHCi.
|
| 93 | 93 | -- See Note [Target code interpreter]
|
| 94 | 94 |
| ... | ... | @@ -1604,10 +1604,9 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do |
| 1604 | 1604 | let (stg_binds, _stg_deps) = unzip stg_binds_with_deps
|
| 1605 | 1605 | |
| 1606 | 1606 | let interp = hscInterp hsc_env
|
| 1607 | - |
|
| 1608 | - case interp of
|
|
| 1607 | + case interpInstance interp of
|
|
| 1609 | 1608 | -- always generate JS code for the JS interpreter (no bytecode!)
|
| 1610 | - Interp { interpInstance = ExternalInterp (ExtJS i) } ->
|
|
| 1609 | + ExternalInterp (ExtJS i) ->
|
|
| 1611 | 1610 | jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id
|
| 1612 | 1611 | |
| 1613 | 1612 | _ -> do
|
| ... | ... | @@ -1645,7 +1644,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do |
| 1645 | 1644 | let logger = hsc_logger hsc_env
|
| 1646 | 1645 | tmpfs = hsc_tmpfs hsc_env
|
| 1647 | 1646 | dflags = hsc_dflags hsc_env
|
| 1648 | - interp = hscInterp hsc_env
|
|
| 1647 | + interp0 = hscInterp hsc_env
|
|
| 1649 | 1648 | tmp_dir = tmpDir dflags
|
| 1650 | 1649 | unit_env = hsc_unit_env hsc_env
|
| 1651 | 1650 | js_config = initStgToJSConfig dflags
|
| ... | ... | @@ -1671,10 +1670,10 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do |
| 1671 | 1670 | -- by default, so we can safely ignore them here.
|
| 1672 | 1671 | |
| 1673 | 1672 | -- Initialise the linker (if it's not been done already)
|
| 1674 | - initLoaderState interp hsc_env
|
|
| 1673 | + initLoaderState interp0 hsc_env
|
|
| 1675 | 1674 | |
| 1676 | 1675 | -- Take lock for the actual work.
|
| 1677 | - (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp $ \pls -> do
|
|
| 1676 | + (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp0 $ \interp pls -> do
|
|
| 1678 | 1677 | let link_opts = initLinkDepsOpts hsc_env
|
| 1679 | 1678 | |
| 1680 | 1679 | -- 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 |
| 1715 | 1714 | jsLinkObject logger tmpfs tmp_dir js_config unit_env (hsc_FC hsc_env) inst out_obj roots needed_units
|
| 1716 | 1715 | |
| 1717 | 1716 | -- look up "id_sym" closure and create a StablePtr (HValue) from it
|
| 1718 | - binding_fref <- lookupClosure interp (IFaststringSymbol id_sym) >>= \case
|
|
| 1717 | + binding_fref <- withInterp interp0 $ \interp -> lookupClosure interp (IFaststringSymbol id_sym) >>= \case
|
|
| 1719 | 1718 | Nothing -> pprPanic "Couldn't find just linked TH closure" (ppr id_sym)
|
| 1720 | 1719 | Just r -> pure r
|
| 1721 | 1720 |
| ... | ... | @@ -837,7 +837,7 @@ pruneCache hpt summ |
| 837 | 837 | -- ---------------------------------------------------------------------------
|
| 838 | 838 | --
|
| 839 | 839 | -- | Unloading
|
| 840 | -unload :: Interp -> HscEnv -> IO ()
|
|
| 840 | +unload :: SafeInterp -> HscEnv -> IO ()
|
|
| 841 | 841 | unload interp hsc_env
|
| 842 | 842 | = case ghcLink (hsc_dflags hsc_env) of
|
| 843 | 843 | LinkInMemory -> Linker.unload interp hsc_env
|
| ... | ... | @@ -170,19 +170,19 @@ import Foreign.Ptr (nullPtr) |
| 170 | 170 | uninitialised :: a
|
| 171 | 171 | uninitialised = panic "Loader not initialised"
|
| 172 | 172 | |
| 173 | -modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()
|
|
| 174 | -modifyLoaderState_ interp f =
|
|
| 173 | +modifyLoaderState_ :: SafeInterp -> (Interp -> LoaderState -> IO LoaderState) -> IO ()
|
|
| 174 | +modifyLoaderState_ interp0 f = withInterp interp0 $ \ interp ->
|
|
| 175 | 175 | modifyMVar_ (loader_state (interpLoader interp))
|
| 176 | - (fmap pure . f . fromMaybe uninitialised)
|
|
| 176 | + (fmap pure . f interp . fromMaybe uninitialised)
|
|
| 177 | 177 | |
| 178 | -modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
|
|
| 179 | -modifyLoaderState interp f =
|
|
| 178 | +modifyLoaderState :: SafeInterp -> (Interp -> LoaderState -> IO (LoaderState, a)) -> IO a
|
|
| 179 | +modifyLoaderState interp0 f = withInterp interp0 $ \ interp ->
|
|
| 180 | 180 | modifyMVar (loader_state (interpLoader interp))
|
| 181 | - (fmapFst pure . f . fromMaybe uninitialised)
|
|
| 181 | + (fmapFst pure . f interp . fromMaybe uninitialised)
|
|
| 182 | 182 | where fmapFst f = fmap (\(x, y) -> (f x, y))
|
| 183 | 183 | |
| 184 | -getLoaderState :: Interp -> IO (Maybe LoaderState)
|
|
| 185 | -getLoaderState interp = readMVar (loader_state (interpLoader interp))
|
|
| 184 | +getLoaderState :: SafeInterp -> IO (Maybe LoaderState)
|
|
| 185 | +getLoaderState (SafeInterp interp) = readMVar (loader_state (interpLoader interp))
|
|
| 186 | 186 | |
| 187 | 187 | |
| 188 | 188 | emptyLoaderState :: UnitEnv -> LoaderState
|
| ... | ... | @@ -206,21 +206,21 @@ emptyLoaderState unit_env = LoaderState |
| 206 | 206 | pkg_to_dfm rtsUnitId
|
| 207 | 207 | ] ++ fmap pkg_to_dfm deps
|
| 208 | 208 | |
| 209 | -extendLoadedEnv :: Interp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
|
|
| 209 | +extendLoadedEnv :: SafeInterp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
|
|
| 210 | 210 | extendLoadedEnv interp modify_bytecode_loader_state new_bindings =
|
| 211 | - modifyLoaderState_ interp $ \pls -> do
|
|
| 211 | + modifyLoaderState_ interp $ \_ pls -> do
|
|
| 212 | 212 | return $! modifyBytecodeLoaderState modify_bytecode_loader_state pls $ \bco_loader_state ->
|
| 213 | 213 | modifyClosureEnv bco_loader_state $ \ce -> extendClosureEnv ce new_bindings
|
| 214 | 214 | -- strictness is important for not retaining old copies of the pls
|
| 215 | 215 | |
| 216 | -deleteFromLoadedHomeEnv :: Interp -> [Name] -> IO ()
|
|
| 216 | +deleteFromLoadedHomeEnv :: SafeInterp -> [Name] -> IO ()
|
|
| 217 | 217 | deleteFromLoadedHomeEnv interp to_remove =
|
| 218 | - modifyLoaderState_ interp $ \pls -> do
|
|
| 218 | + modifyLoaderState_ interp $ \_ pls -> do
|
|
| 219 | 219 | return $ modifyBytecodeLoaderState modifyHomePackageBytecodeState pls $ \bco_state ->
|
| 220 | 220 | modifyClosureEnv bco_state $ \ce -> delListFromNameEnv ce to_remove
|
| 221 | 221 | |
| 222 | 222 | -- | Have we already loaded a name into the interpreter?
|
| 223 | -lookupFromLoadedEnv :: Interp -> Name -> IO (Maybe ForeignHValue)
|
|
| 223 | +lookupFromLoadedEnv :: SafeInterp -> Name -> IO (Maybe ForeignHValue)
|
|
| 224 | 224 | lookupFromLoadedEnv interp name = do
|
| 225 | 225 | mstate <- getLoaderState interp
|
| 226 | 226 | return $ do
|
| ... | ... | @@ -231,10 +231,10 @@ lookupFromLoadedEnv interp name = do |
| 231 | 231 | -- | Load the module containing the given Name and get its associated 'HValue'.
|
| 232 | 232 | --
|
| 233 | 233 | -- Throws a 'ProgramError' if loading fails or the name cannot be found.
|
| 234 | -loadName :: Interp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
|
|
| 235 | -loadName interp hsc_env name = do
|
|
| 236 | - initLoaderState interp hsc_env
|
|
| 237 | - modifyLoaderState interp $ \pls0 -> do
|
|
| 234 | +loadName :: SafeInterp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
|
|
| 235 | +loadName interp0 hsc_env name = do
|
|
| 236 | + initLoaderState interp0 hsc_env
|
|
| 237 | + modifyLoaderState interp0 $ \interp pls0 -> do
|
|
| 238 | 238 | (pls, links, pkgs) <- if not (isExternalName name)
|
| 239 | 239 | then return (pls0, [], emptyUDFM)
|
| 240 | 240 | else do
|
| ... | ... | @@ -248,6 +248,7 @@ loadName interp hsc_env name = do |
| 248 | 248 | Just (_,aa) -> return (pls,(aa, links, pkgs))
|
| 249 | 249 | Nothing -> assertPpr (isExternalName name) (ppr name) $
|
| 250 | 250 | do let sym_to_find = IClosureSymbol name
|
| 251 | + -- TODO: does not take loader state lock
|
|
| 251 | 252 | m <- lookupClosure interp sym_to_find
|
| 252 | 253 | r <- case m of
|
| 253 | 254 | Just fhv -> return fhv
|
| ... | ... | @@ -295,7 +296,7 @@ loadDependencies interp hsc_env pls span needed_mods = do |
| 295 | 296 | -- | Temporarily extend the loaded env.
|
| 296 | 297 | withExtendedLoadedEnv
|
| 297 | 298 | :: (ExceptionMonad m)
|
| 298 | - => Interp
|
|
| 299 | + => SafeInterp
|
|
| 299 | 300 | -> [(Name,ForeignHValue)]
|
| 300 | 301 | -> m a
|
| 301 | 302 | -> m a
|
| ... | ... | @@ -314,9 +315,9 @@ withExtendedLoadedEnv interp new_env action |
| 314 | 315 | |
| 315 | 316 | |
| 316 | 317 | -- | Display the loader state.
|
| 317 | -showLoaderState :: Interp -> IO SDoc
|
|
| 318 | +showLoaderState :: SafeInterp -> IO SDoc
|
|
| 318 | 319 | showLoaderState interp = do
|
| 319 | - ls <- readMVar (loader_state (interpLoader interp))
|
|
| 320 | + ls <- getLoaderState interp
|
|
| 320 | 321 | let docs = case ls of
|
| 321 | 322 | Nothing -> [ text "Loader not initialised"]
|
| 322 | 323 | Just pls -> [ text "Pkgs:" <+> ppr (map loaded_pkg_uid $ eltsUDFM $ pkgs_loaded pls)
|
| ... | ... | @@ -352,8 +353,8 @@ showLoaderState interp = do |
| 352 | 353 | -- nothing. This is useful in Template Haskell, where we call it before
|
| 353 | 354 | -- trying to link.
|
| 354 | 355 | --
|
| 355 | -initLoaderState :: Interp -> HscEnv -> IO ()
|
|
| 356 | -initLoaderState interp hsc_env = do
|
|
| 356 | +initLoaderState :: SafeInterp -> HscEnv -> IO ()
|
|
| 357 | +initLoaderState interp0 hsc_env = withInterp interp0 $ \ interp -> do
|
|
| 357 | 358 | modifyMVar_ (loader_state (interpLoader interp)) $ \pls -> do
|
| 358 | 359 | case pls of
|
| 359 | 360 | Just _ -> return pls
|
| ... | ... | @@ -382,10 +383,10 @@ reallyInitLoaderState interp hsc_env = do |
| 382 | 383 | loadCmdLineLibs' interp hsc_env pls
|
| 383 | 384 | |
| 384 | 385 | |
| 385 | -loadCmdLineLibs :: Interp -> HscEnv -> IO ()
|
|
| 386 | -loadCmdLineLibs interp hsc_env = do
|
|
| 387 | - initLoaderState interp hsc_env
|
|
| 388 | - modifyLoaderState_ interp $ \pls ->
|
|
| 386 | +loadCmdLineLibs :: SafeInterp -> HscEnv -> IO ()
|
|
| 387 | +loadCmdLineLibs interp0 hsc_env = do
|
|
| 388 | + initLoaderState interp0 hsc_env
|
|
| 389 | + modifyLoaderState_ interp0 $ \interp pls ->
|
|
| 389 | 390 | loadCmdLineLibs' interp hsc_env pls
|
| 390 | 391 | |
| 391 | 392 | |
| ... | ... | @@ -730,13 +731,13 @@ get_reachable_nodes hsc_env mods |
| 730 | 731 | ********************************************************************* -}
|
| 731 | 732 | |
| 732 | 733 | -- | Load the dependencies of a linkable, and then load the linkable itself.
|
| 733 | -loadDecls :: Interp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
|
|
| 734 | -loadDecls interp hsc_env span linkable = do
|
|
| 734 | +loadDecls :: SafeInterp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
|
|
| 735 | +loadDecls interp0 hsc_env span linkable = do
|
|
| 735 | 736 | -- Initialise the linker (if it's not been done already)
|
| 736 | - initLoaderState interp hsc_env
|
|
| 737 | + initLoaderState interp0 hsc_env
|
|
| 737 | 738 | |
| 738 | 739 | -- Take lock for the actual work.
|
| 739 | - modifyLoaderState interp $ \pls0 -> do
|
|
| 740 | + modifyLoaderState interp0 $ \interp pls0 -> do
|
|
| 740 | 741 | -- Link the packages and modules required
|
| 741 | 742 | (pls, ok, links_needed, units_needed) <- loadDependencies interp hsc_env pls0 span needed_mods
|
| 742 | 743 | if failed ok
|
| ... | ... | @@ -770,10 +771,10 @@ loadDecls interp hsc_env span linkable = do |
| 770 | 771 | |
| 771 | 772 | ********************************************************************* -}
|
| 772 | 773 | |
| 773 | -loadModule :: Interp -> HscEnv -> Module -> IO ()
|
|
| 774 | -loadModule interp hsc_env mod = do
|
|
| 775 | - initLoaderState interp hsc_env
|
|
| 776 | - modifyLoaderState_ interp $ \pls -> do
|
|
| 774 | +loadModule :: SafeInterp -> HscEnv -> Module -> IO ()
|
|
| 775 | +loadModule interp0 hsc_env mod = do
|
|
| 776 | + initLoaderState interp0 hsc_env
|
|
| 777 | + modifyLoaderState_ interp0 $ \interp pls -> do
|
|
| 777 | 778 | (pls', ok, _, _) <- loadDependencies interp hsc_env pls noSrcSpan [mod]
|
| 778 | 779 | if failed ok
|
| 779 | 780 | 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 |
| 1158 | 1159 | -- * we also implicitly unload all temporary bindings at this point.
|
| 1159 | 1160 | --
|
| 1160 | 1161 | unload
|
| 1161 | - :: Interp
|
|
| 1162 | + :: SafeInterp
|
|
| 1162 | 1163 | -> HscEnv
|
| 1163 | 1164 | -> IO ()
|
| 1164 | -unload interp hsc_env
|
|
| 1165 | +unload interp0 hsc_env
|
|
| 1165 | 1166 | = mask_ $ do -- mask, so we're safe from Ctrl-C in here
|
| 1166 | 1167 | |
| 1167 | 1168 | -- Initialise the linker (if it's not been done already)
|
| 1168 | - initLoaderState interp hsc_env
|
|
| 1169 | + initLoaderState interp0 hsc_env
|
|
| 1169 | 1170 | |
| 1170 | - _new_pls <- modifyLoaderState interp $ \pls -> do
|
|
| 1171 | + _new_pls <- modifyLoaderState interp0 $ \interp pls -> do
|
|
| 1171 | 1172 | pls1 <- unload_wkr interp pls
|
| 1172 | 1173 | return (pls1, pls1)
|
| 1173 | 1174 | |
| ... | ... | @@ -1234,7 +1235,7 @@ showLS (BytecodeLibrary nm) = "(bytecode) " ++ nm |
| 1234 | 1235 | -- automatically, and it doesn't matter what order you specify the input
|
| 1235 | 1236 | -- packages.
|
| 1236 | 1237 | --
|
| 1237 | -loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
|
|
| 1238 | +loadPackages :: SafeInterp -> HscEnv -> [UnitId] -> IO ()
|
|
| 1238 | 1239 | -- NOTE: in fact, since each module tracks all the packages it depends on,
|
| 1239 | 1240 | -- we don't really need to use the package-config dependencies.
|
| 1240 | 1241 | --
|
| ... | ... | @@ -1243,11 +1244,11 @@ loadPackages :: Interp -> HscEnv -> [UnitId] -> IO () |
| 1243 | 1244 | -- perhaps makes the error message a bit more localised if we get a link
|
| 1244 | 1245 | -- failure. So the dependency walking code is still here.
|
| 1245 | 1246 | |
| 1246 | -loadPackages interp hsc_env new_pkgs = do
|
|
| 1247 | +loadPackages interp0 hsc_env new_pkgs = do
|
|
| 1247 | 1248 | -- It's probably not safe to try to load packages concurrently, so we take
|
| 1248 | 1249 | -- a lock.
|
| 1249 | - initLoaderState interp hsc_env
|
|
| 1250 | - modifyLoaderState_ interp $ \pls ->
|
|
| 1250 | + initLoaderState interp0 hsc_env
|
|
| 1251 | + modifyLoaderState_ interp0 $ \interp pls ->
|
|
| 1251 | 1252 | loadPackages' interp hsc_env new_pkgs pls
|
| 1252 | 1253 | |
| 1253 | 1254 | -- | Compute 'LoadedPkgInfo' metadata (with transitive deps) for new packages,
|
| ... | ... | @@ -468,7 +468,7 @@ resumeExec step mbCnt r = do |
| 468 | 468 | | otherwise -> pure prevHistoryLst
|
| 469 | 469 | handleRunStatus step eval_opts expr bindings final_ids status =<< hist'
|
| 470 | 470 | |
| 471 | -setupBreakpoint :: GhcMonad m => Interp -> InternalBreakpointId -> Int -> m () -- #19157
|
|
| 471 | +setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157
|
|
| 472 | 472 | setupBreakpoint interp ibi cnt = do
|
| 473 | 473 | hug <- hsc_HUG <$> getSession
|
| 474 | 474 | liftIO $ do
|
| ... | ... | @@ -476,18 +476,18 @@ setupBreakpoint interp ibi cnt = do |
| 476 | 476 | breakArray <- getBreakArray interp ibi modBreaks
|
| 477 | 477 | GHCi.storeBreakpoint interp breakArray (ibi_info_index ibi) cnt
|
| 478 | 478 | |
| 479 | -getBreakArray :: Interp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
|
|
| 479 | +getBreakArray :: SafeInterp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
|
|
| 480 | 480 | getBreakArray interp InternalBreakpointId{ibi_info_mod} imbs = do
|
| 481 | 481 | breaks0 <- bco_linked_breaks . homePackage_loaded . bco_loader_state . fromMaybe (panic "Loader not initialised") <$> getLoaderState interp
|
| 482 | 482 | case lookupModuleEnv (breakarray_env breaks0) ibi_info_mod of
|
| 483 | 483 | Just ba -> return ba
|
| 484 | 484 | Nothing -> do
|
| 485 | - modifyLoaderState interp $ \ld_st -> do
|
|
| 485 | + modifyLoaderState interp $ \interp' ld_st -> do
|
|
| 486 | 486 | let lb = bco_linked_breaks . homePackage_loaded . bco_loader_state $ ld_st
|
| 487 | 487 | |
| 488 | 488 | -- Recall that BreakArrays are allocated only at BCO link time, so if we
|
| 489 | 489 | -- haven't linked the BCOs we intend to break at yet, we allocate the arrays here.
|
| 490 | - ba_env <- allocateBreakArrays interp (breakarray_env lb) [imbs]
|
|
| 490 | + ba_env <- allocateBreakArrays interp' (breakarray_env lb) [imbs]
|
|
| 491 | 491 | |
| 492 | 492 | let ld_st' = modifyBytecodeLoaderState modifyHomePackageBytecodeState ld_st $ \bco_state -> bco_state { bco_linked_breaks = (bco_linked_breaks bco_state) { breakarray_env = ba_env } }
|
| 493 | 493 | let ba = expectJust {- just computed -} $ lookupModuleEnv ba_env ibi_info_mod
|
| ... | ... | @@ -64,6 +64,9 @@ module GHC.Runtime.Interpreter |
| 64 | 64 | -- * Reexport for convenience
|
| 65 | 65 | , Message (..)
|
| 66 | 66 | , module GHC.Runtime.Interpreter.Process
|
| 67 | + |
|
| 68 | + -- * High-level interface to the interpreter
|
|
| 69 | + , withInterp
|
|
| 67 | 70 | ) where
|
| 68 | 71 | |
| 69 | 72 | import GHC.Prelude
|
| ... | ... | @@ -107,6 +110,7 @@ import Control.Concurrent |
| 107 | 110 | import Control.Monad
|
| 108 | 111 | import Control.Monad.IO.Class
|
| 109 | 112 | import Control.Monad.Catch as MC (mask, handle, MonadThrow (..))
|
| 113 | +import Control.Monad.STM
|
|
| 110 | 114 | import Data.Binary
|
| 111 | 115 | import Data.ByteString (ByteString)
|
| 112 | 116 | import qualified Data.ByteString.Short as SBS
|
| ... | ... | @@ -198,7 +202,7 @@ interpCmd interp msg = case interpInstance interp of |
| 198 | 202 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 199 | 203 | InternalInterp -> run msg -- Just run it directly
|
| 200 | 204 | #endif
|
| 201 | - ExternalInterp ext -> withExtInterp interp ext $ \inst ->
|
|
| 205 | + ExternalInterp ext -> withExtInterp ext $ \inst ->
|
|
| 202 | 206 | sendMessage inst msg
|
| 203 | 207 | |
| 204 | 208 | -- | Calls `interpCmd` and the continuation while masked.
|
| ... | ... | @@ -208,13 +212,22 @@ interpCmd interp msg = case interpInstance interp of |
| 208 | 212 | withInterpCmdMasked :: Binary a => Interp -> Message a -> (a -> IO b) -> IO b
|
| 209 | 213 | withInterpCmdMasked interp msg own = mask_ $ interpCmd interp msg >>= own
|
| 210 | 214 | |
| 211 | -withExtInterp :: ExceptionMonad m => Interp -> ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
|
|
| 212 | -withExtInterp interp ext action = stopInterpOnPipeClosed $ case ext of
|
|
| 215 | +-- | Passes the `Interp` to the continuation while setting up a
|
|
| 216 | +-- 'PipeClosedException' handler that calls 'stopInterp'.
|
|
| 217 | +--
|
|
| 218 | +-- Will take the 'interpLoader' lock on a 'PipeClosedException'.
|
|
| 219 | +withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
|
|
| 220 | +withInterp interp0@(SafeInterp interp) k = stopInterpOnPipeClosed $ k interp
|
|
| 221 | + where
|
|
| 222 | + stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> do
|
|
| 223 | + liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0
|
|
| 224 | + MC.throwM e
|
|
| 225 | + |
|
| 226 | +withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
|
|
| 227 | +withExtInterp ext action = case ext of
|
|
| 213 | 228 | ExtJS i -> withJSInterp i action
|
| 214 | 229 | ExtWasm i -> withWasmInterp i action
|
| 215 | 230 | ExtIServ i -> withIServ i action
|
| 216 | - where
|
|
| 217 | - stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> liftIO (stopInterp interp) >> MC.throwM e
|
|
| 218 | 231 | |
| 219 | 232 | withExtInterpStatus :: ExtInterp -> (forall d. ExtInterpStatusVar d -> m a) -> m a
|
| 220 | 233 | withExtInterpStatus ext action = case ext of
|
| ... | ... | @@ -294,11 +307,11 @@ withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do |
| 294 | 307 | -- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for
|
| 295 | 308 | -- each of the results.
|
| 296 | 309 | evalStmt
|
| 297 | - :: Interp
|
|
| 310 | + :: SafeInterp
|
|
| 298 | 311 | -> EvalOpts
|
| 299 | 312 | -> EvalExpr ForeignHValue
|
| 300 | 313 | -> IO (EvalStatus_ [ForeignHValue] [HValueRef])
|
| 301 | -evalStmt interp opts foreign_expr = do
|
|
| 314 | +evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do
|
|
| 302 | 315 | status <- withExpr foreign_expr $ \expr ->
|
| 303 | 316 | interpCmd interp (EvalStmt opts expr)
|
| 304 | 317 | handleEvalStatus interp status
|
| ... | ... | @@ -312,17 +325,17 @@ evalStmt interp opts foreign_expr = do |
| 312 | 325 | cont (EvalApp fl' fr')
|
| 313 | 326 | |
| 314 | 327 | resumeStmt
|
| 315 | - :: Interp
|
|
| 328 | + :: SafeInterp
|
|
| 316 | 329 | -> EvalOpts
|
| 317 | 330 | -> ForeignRef (ResumeContext [HValueRef])
|
| 318 | 331 | -> IO (EvalStatus_ [ForeignHValue] [HValueRef])
|
| 319 | -resumeStmt interp opts resume_ctxt = do
|
|
| 332 | +resumeStmt interp0 opts resume_ctxt = withInterp interp0 $ \interp -> do
|
|
| 320 | 333 | status <- withForeignRef resume_ctxt $ \rhv ->
|
| 321 | 334 | interpCmd interp (ResumeStmt opts rhv)
|
| 322 | 335 | handleEvalStatus interp status
|
| 323 | 336 | |
| 324 | -abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
|
|
| 325 | -abandonStmt interp resume_ctxt =
|
|
| 337 | +abandonStmt :: SafeInterp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
|
|
| 338 | +abandonStmt interp0 resume_ctxt = withInterp interp0 $ \ interp ->
|
|
| 326 | 339 | withForeignRef resume_ctxt $ \rhv ->
|
| 327 | 340 | interpCmd interp (AbandonStmt rhv)
|
| 328 | 341 | |
| ... | ... | @@ -341,20 +354,20 @@ handleEvalStatus interp status = |
| 341 | 354 | EvalSuccess <$> mapM (mkFinalizedHValue interp) rs
|
| 342 | 355 | |
| 343 | 356 | -- | Execute an action of type @IO ()@
|
| 344 | -evalIO :: Interp -> ForeignHValue -> IO ()
|
|
| 345 | -evalIO interp fhv =
|
|
| 357 | +evalIO :: SafeInterp -> ForeignHValue -> IO ()
|
|
| 358 | +evalIO interp0 fhv = withInterp interp0 $ \ interp ->
|
|
| 346 | 359 | liftIO $ withForeignRef fhv $ \fhv ->
|
| 347 | 360 | interpCmd interp (EvalIO fhv) >>= fromEvalResult
|
| 348 | 361 | |
| 349 | 362 | -- | Execute an action of type @IO String@
|
| 350 | -evalString :: Interp -> ForeignHValue -> IO String
|
|
| 351 | -evalString interp fhv =
|
|
| 363 | +evalString :: SafeInterp -> ForeignHValue -> IO String
|
|
| 364 | +evalString interp0 fhv = withInterp interp0 $ \ interp ->
|
|
| 352 | 365 | liftIO $ withForeignRef fhv $ \fhv ->
|
| 353 | 366 | interpCmd interp (EvalString fhv) >>= fromEvalResult
|
| 354 | 367 | |
| 355 | 368 | -- | Execute an action of type @String -> IO String@
|
| 356 | -evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String
|
|
| 357 | -evalStringToIOString interp fhv str =
|
|
| 369 | +evalStringToIOString :: SafeInterp -> ForeignHValue -> String -> IO String
|
|
| 370 | +evalStringToIOString interp0 fhv str = withInterp interp0 $ \ interp ->
|
|
| 358 | 371 | liftIO $ withForeignRef fhv $ \fhv ->
|
| 359 | 372 | interpCmd interp (EvalStringToString fhv str) >>= fromEvalResult
|
| 360 | 373 | |
| ... | ... | @@ -388,44 +401,44 @@ addHpcModule :: Interp -> SBS.ShortByteString -> Int -> Int -> SBS.ShortByteStri |
| 388 | 401 | addHpcModule interp modLabel tickNo hash tickboxes =
|
| 389 | 402 | interpCmd interp (AddHpcModule modLabel tickNo hash tickboxes)
|
| 390 | 403 | |
| 391 | -costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String]
|
|
| 392 | -costCentreStackInfo interp ccs =
|
|
| 404 | +costCentreStackInfo :: SafeInterp -> RemotePtr CostCentreStack -> IO [String]
|
|
| 405 | +costCentreStackInfo interp0 ccs = withInterp interp0 $ \interp ->
|
|
| 393 | 406 | interpCmd interp (CostCentreStackInfo ccs)
|
| 394 | 407 | |
| 395 | 408 | newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray)
|
| 396 | 409 | newBreakArray interp size =
|
| 397 | 410 | withInterpCmdMasked interp (NewBreakArray size) (mkFinalizedHValue interp)
|
| 398 | 411 | |
| 399 | -storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO ()
|
|
| 400 | -storeBreakpoint interp ref ix cnt = do -- #19157
|
|
| 412 | +storeBreakpoint :: SafeInterp -> ForeignRef BreakArray -> Int -> Int -> IO ()
|
|
| 413 | +storeBreakpoint interp0 ref ix cnt = withInterp interp0 $ \ interp -> do -- #19157
|
|
| 401 | 414 | withForeignRef ref $ \breakarray ->
|
| 402 | 415 | interpCmd interp (SetupBreakpoint breakarray ix cnt)
|
| 403 | 416 | |
| 404 | -breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool
|
|
| 405 | -breakpointStatus interp ref ix =
|
|
| 417 | +breakpointStatus :: SafeInterp -> ForeignRef BreakArray -> Int -> IO Bool
|
|
| 418 | +breakpointStatus interp0 ref ix = withInterp interp0 $ \ interp ->
|
|
| 406 | 419 | withForeignRef ref $ \breakarray ->
|
| 407 | 420 | interpCmd interp (BreakpointStatus breakarray ix)
|
| 408 | 421 | |
| 409 | -getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
|
|
| 410 | -getBreakpointVar interp ref ix =
|
|
| 422 | +getBreakpointVar :: SafeInterp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
|
|
| 423 | +getBreakpointVar interp0 ref ix = withInterp interp0 $ \ interp ->
|
|
| 411 | 424 | withForeignRef ref $ \apStack ->
|
| 412 | 425 | withInterpCmdMasked interp (GetBreakpointVar apStack ix)
|
| 413 | 426 | (mapM (mkFinalizedHValue interp))
|
| 414 | 427 | |
| 415 | -getClosure :: Interp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
|
|
| 416 | -getClosure interp ref =
|
|
| 428 | +getClosure :: SafeInterp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
|
|
| 429 | +getClosure interp0 ref = withInterp interp0 $ \ interp ->
|
|
| 417 | 430 | withForeignRef ref $ \hval ->
|
| 418 | 431 | withInterpCmdMasked interp (GetClosure hval) $
|
| 419 | 432 | mapM (mkFinalizedHValue interp)
|
| 420 | 433 | |
| 421 | -whereFrom :: Interp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
|
|
| 422 | -whereFrom interp ref =
|
|
| 434 | +whereFrom :: SafeInterp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
|
|
| 435 | +whereFrom interp0 ref = withInterp interp0 $ \ interp ->
|
|
| 423 | 436 | withForeignRef ref $ \hval -> do
|
| 424 | 437 | interpCmd interp (WhereFrom hval)
|
| 425 | 438 | |
| 426 | 439 | -- | Send a Seq message to the iserv process to force a value #2950
|
| 427 | -seqHValue :: Interp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
|
|
| 428 | -seqHValue interp unit_env logger ref =
|
|
| 440 | +seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
|
|
| 441 | +seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp ->
|
|
| 429 | 442 | withForeignRef ref $ \hval -> do
|
| 430 | 443 | status <- interpCmd interp (Seq hval)
|
| 431 | 444 | handleSeqHValueStatus interp unit_env logger status
|
| ... | ... | @@ -649,26 +662,38 @@ spawnIServ conf = do |
| 649 | 662 | pure inst
|
| 650 | 663 | |
| 651 | 664 | -- | Stop the interpreter
|
| 652 | -stopInterp :: Interp -> IO ()
|
|
| 653 | -stopInterp interp = case interpInstance interp of
|
|
| 665 | +stopInterp :: SafeInterp -> IO ()
|
|
| 666 | +stopInterp = stopInterpWhen (const $ pure True)
|
|
| 667 | + |
|
| 668 | +-- | Stop the interpreter if predicate returns 'True'.
|
|
| 669 | +stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO ()
|
|
| 670 | +stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of
|
|
| 654 | 671 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 655 | 672 | InternalInterp -> pure ()
|
| 656 | 673 | #endif
|
| 657 | - ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> do
|
|
| 658 | - MC.mask $ \restore -> modifyMVar mstate $ \state -> do
|
|
| 674 | + ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do
|
|
| 675 | + -- takes interpLoader lock before ExternalInterp lock to avoid deadlocks.
|
|
| 676 | + -- commits emptied values before 'gracefulShutdown' so we don't hold locks
|
|
| 677 | + -- more than necessary.
|
|
| 678 | + mi <- modifyMVar (loader_state (interpLoader interp)) $ \l_st -> do
|
|
| 679 | + modifyMVar mstate $ \state -> do
|
|
| 659 | 680 | case state of
|
| 660 | - InterpPending -> pure (state, Nothing) -- already stopped
|
|
| 661 | - InterpRunning i -> do
|
|
| 662 | - e <- getProcessExitCode (interpHandle (instProcess i)) >>= \case
|
|
| 663 | - Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
|
|
| 664 | - Nothing -> gracefulShutdown i restore
|
|
| 665 | - modifyMVar_ (loader_state (interpLoader interp)) (const $ pure Nothing)
|
|
| 666 | - purgeInterpSymbolCache (interpSymbolCache interp)
|
|
| 667 | - modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
|
|
| 668 | - pure (InterpPending,e)
|
|
| 681 | + InterpPending -> pure (state, (l_st, Nothing)) -- already stopped
|
|
| 682 | + InterpRunning i -> shouldStop (instProcess i) >>= \case
|
|
| 683 | + False -> pure (state, (l_st, Nothing))
|
|
| 684 | + True -> do
|
|
| 685 | + purgeInterpSymbolCache (interpSymbolCache interp)
|
|
| 686 | + modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
|
|
| 687 | + pure (InterpPending,(Nothing,Just i))
|
|
| 688 | + case mi of
|
|
| 689 | + Nothing -> pure Nothing
|
|
| 690 | + Just i -> getProcessExitCode (interpHandle (instProcess i)) >>= \case
|
|
| 691 | + Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
|
|
| 692 | + Nothing -> gracefulShutdown i restore
|
|
| 693 | + |
|
| 669 | 694 | where
|
| 670 | 695 | gracefulShutdown i restore = do
|
| 671 | - x <- try (timeLimited restore $ sendMessage i Shutdown `finally` closePipe (interpPipe (instProcess i)))
|
|
| 696 | + x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i)))))
|
|
| 672 | 697 | let ph = interpHandle (instProcess i)
|
| 673 | 698 | e <- case x of
|
| 674 | 699 | -- 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. |
| 731 | 756 | |
| 732 | 757 | -- | Creates a 'ForeignRef' that will automatically release the
|
| 733 | 758 | -- 'RemoteRef' when it is no longer referenced.
|
| 734 | -mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a)
|
|
| 759 | +mkFinalizedHValue :: HasInterpInstance i => i -> RemoteRef a -> IO (ForeignRef a)
|
|
| 735 | 760 | mkFinalizedHValue interp rref = do
|
| 736 | 761 | case interpInstance interp of
|
| 737 | 762 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| ... | ... | @@ -754,13 +779,13 @@ freeHValueRefs interp refs = interpCmd interp (FreeHValueRefs refs) |
| 754 | 779 | -- | Convert a 'ForeignRef' to the value it references directly. This
|
| 755 | 780 | -- only works when the interpreter is running in the same process as
|
| 756 | 781 | -- the compiler, so it fails when @-fexternal-interpreter@ is on.
|
| 757 | -wormhole :: Interp -> ForeignRef a -> IO a
|
|
| 782 | +wormhole :: SafeInterp -> ForeignRef a -> IO a
|
|
| 758 | 783 | wormhole interp r = wormholeRef interp (unsafeForeignRefToRemoteRef r)
|
| 759 | 784 | |
| 760 | 785 | -- | Convert an 'RemoteRef' to the value it references directly. This
|
| 761 | 786 | -- only works when the interpreter is running in the same process as
|
| 762 | 787 | -- the compiler, so it fails when @-fexternal-interpreter@ is on.
|
| 763 | -wormholeRef :: Interp -> RemoteRef a -> IO a
|
|
| 788 | +wormholeRef :: SafeInterp -> RemoteRef a -> IO a
|
|
| 764 | 789 | wormholeRef interp _r = case interpInstance interp of
|
| 765 | 790 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 766 | 791 | InternalInterp -> localRef _r
|
| ... | ... | @@ -29,7 +29,9 @@ import GHC.Utils.Monad |
| 29 | 29 | import GHC.Utils.Outputable
|
| 30 | 30 | import GHC.Utils.Logger
|
| 31 | 31 | import GHC.Utils.Error
|
| 32 | + |
|
| 32 | 33 | import Control.Concurrent
|
| 34 | +import Data.Coerce
|
|
| 33 | 35 | import System.Process
|
| 34 | 36 | |
| 35 | 37 | data InterpOpts = InterpOpts
|
| ... | ... | @@ -67,8 +69,8 @@ initInterpreter |
| 67 | 69 | -> FinderCache
|
| 68 | 70 | -> UnitEnv
|
| 69 | 71 | -> InterpOpts
|
| 70 | - -> IO (Maybe Interp)
|
|
| 71 | -initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = do
|
|
| 72 | + -> IO (Maybe SafeInterp)
|
|
| 73 | +initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = coerce $ do
|
|
| 72 | 74 | |
| 73 | 75 | lookup_cache <- liftIO $ mkInterpSymbolCache
|
| 74 | 76 |
| ... | ... | @@ -4,6 +4,8 @@ |
| 4 | 4 | -- | Types used by the runtime interpreter
|
| 5 | 5 | module GHC.Runtime.Interpreter.Types
|
| 6 | 6 | ( Interp(..)
|
| 7 | + , SafeInterp(..)
|
|
| 8 | + , HasInterpInstance(..)
|
|
| 7 | 9 | , InterpInstance(..)
|
| 8 | 10 | , InterpProcess (..)
|
| 9 | 11 | , ExtInterp (..)
|
| ... | ... | @@ -66,9 +68,36 @@ import System.Process ( ProcessHandle, CreateProcess ) |
| 66 | 68 | import System.IO
|
| 67 | 69 | import GHC.Unit.Finder.Types (FinderCache, FinderOpts)
|
| 68 | 70 | |
| 71 | +{-
|
|
| 72 | +Note [Interpreter locks order]
|
|
| 73 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
| 74 | + |
|
| 75 | +To avoid deadlocks, the 'interpLoader' lock should be taken before the lock that
|
|
| 76 | +contains the 'InterpStatus'.
|
|
| 77 | + |
|
| 78 | +Further, you should wrap the code that takes the 'interpLoader' lock with
|
|
| 79 | +'withInterp', as it will cleanup the whole interpreter state in case the
|
|
| 80 | +external interpreter pipe died:
|
|
| 81 | +```
|
|
| 82 | +withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
|
|
| 83 | +```
|
|
| 84 | + |
|
| 85 | +'SafeInterp' is a newtype introduced to aid with the discipline: only code that
|
|
| 86 | +has ownership over a 'SafeInterp' should take its 'interpLoader' lock.
|
|
| 87 | + |
|
| 88 | +-}
|
|
| 89 | + |
|
| 90 | + |
|
| 91 | + |
|
| 92 | + |
|
| 93 | +-- | An 'Interp' where we have not taken the 'interpLoader' lock in this thread.
|
|
| 94 | +--
|
|
| 95 | +-- See Note [Interpreter locks order]
|
|
| 96 | +newtype SafeInterp = SafeInterp Interp
|
|
| 97 | + |
|
| 69 | 98 | -- | Interpreter
|
| 70 | 99 | data Interp = Interp
|
| 71 | - { interpInstance :: !InterpInstance
|
|
| 100 | + { _interpInstance :: !InterpInstance
|
|
| 72 | 101 | -- ^ Interpreter instance (internal, external)
|
| 73 | 102 | |
| 74 | 103 | , interpLoader :: !Loader
|
| ... | ... | @@ -81,6 +110,13 @@ data Interp = Interp |
| 81 | 110 | -- ^ MallocStrings cache
|
| 82 | 111 | }
|
| 83 | 112 | |
| 113 | +class HasInterpInstance a where
|
|
| 114 | + interpInstance :: a -> InterpInstance
|
|
| 115 | +instance HasInterpInstance SafeInterp where
|
|
| 116 | + interpInstance (SafeInterp interp) = interpInstance interp
|
|
| 117 | +instance HasInterpInstance Interp where
|
|
| 118 | + interpInstance = _interpInstance
|
|
| 119 | + |
|
| 84 | 120 | data InterpInstance
|
| 85 | 121 | = ExternalInterp !ExtInterp -- ^ External interpreter
|
| 86 | 122 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| ... | ... | @@ -143,7 +179,7 @@ data ExtInterpInstance c = ExtInterpInstance |
| 143 | 179 | }
|
| 144 | 180 | |
| 145 | 181 | -- | Interpreter uses Profiling way
|
| 146 | -interpreterProfiled :: Interp -> Bool
|
|
| 182 | +interpreterProfiled :: HasInterpInstance a => a -> Bool
|
|
| 147 | 183 | interpreterProfiled interp = case interpInstance interp of
|
| 148 | 184 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 149 | 185 | InternalInterp -> hostIsProfiled
|
| ... | ... | @@ -154,7 +190,7 @@ interpreterProfiled interp = case interpInstance interp of |
| 154 | 190 | ExtWasm i -> wasmInterpProfiled $ interpConfig i
|
| 155 | 191 | |
| 156 | 192 | -- | Interpreter uses Dynamic way
|
| 157 | -interpreterDynamic :: Interp -> Bool
|
|
| 193 | +interpreterDynamic :: HasInterpInstance a => a -> Bool
|
|
| 158 | 194 | interpreterDynamic interp = case interpInstance interp of
|
| 159 | 195 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 160 | 196 | InternalInterp -> hostIsDynamic
|
| ... | ... | @@ -283,7 +283,7 @@ getValueSafely hsc_env val_name expected_type = do |
| 283 | 283 | logger = hsc_logger hsc_env
|
| 284 | 284 | hooks = hsc_hooks hsc_env
|
| 285 | 285 | |
| 286 | -getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
|
|
| 286 | +getHValueSafely :: SafeInterp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
|
|
| 287 | 287 | getHValueSafely interp hsc_env val_name expected_type = do
|
| 288 | 288 | forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name
|
| 289 | 289 | -- Now look up the names for the value and type constructor in the type environment
|
| 1 | +{-# LANGUAGE CPP #-}
|
|
| 2 | + |
|
| 1 | 3 | module GHC.Runtime.Utils
|
| 2 | 4 | ( runWithPipes
|
| 3 | 5 | )
|
| ... | ... | @@ -10,6 +12,14 @@ import System.Process |
| 10 | 12 | import System.Process.CommunicationHandle
|
| 11 | 13 | import System.IO
|
| 12 | 14 | |
| 15 | +#if defined(mingw32_HOST_OS)
|
|
| 16 | +import Control.Concurrent (rtsSupportsBoundThreads)
|
|
| 17 | +import GHC.IO.Handle.Windows (handleToHANDLE)
|
|
| 18 | +import GHC.IO.SubSystem (isWindowsNativeIO)
|
|
| 19 | +import System.Process.CommunicationHandle.Internal (CommunicationHandle(..))
|
|
| 20 | +import qualified System.Win32 as Win32
|
|
| 21 | +#endif
|
|
| 22 | + |
|
| 13 | 23 | -- | Spawn a process connected to us by two pipes. Important to close our copy
|
| 14 | 24 | -- of the endpoints passed to the child so each side only keeps open copies it
|
| 15 | 25 | -- needs. If we don't do that, then closing one end wouldn't interrupt reads on
|
| ... | ... | @@ -17,14 +27,64 @@ import System.IO |
| 17 | 27 | runWithPipes :: (CreateProcess -> IO ProcessHandle)
|
| 18 | 28 | -> FilePath -> [String] -> [String] -> IO (ProcessHandle, Handle, Handle)
|
| 19 | 29 | runWithPipes createProc prog pre_opts opts = do
|
| 20 | - (rh, chTheyWrite) <- createWeReadTheyWritePipe
|
|
| 21 | - (chTheyRead, wh) <- createTheyReadWeWritePipe
|
|
| 30 | + (rh, chTheyWrite) <- fixedCreateWeReadTheyWritePipe
|
|
| 31 | + (chTheyRead, wh) <- fixedCreateTheyReadWeWritePipe
|
|
| 22 | 32 | let args = pre_opts ++ (show chTheyWrite : show chTheyRead : opts)
|
| 23 | 33 | closeTheirs = do
|
| 24 | - closeCommunicationHandle chTheyWrite
|
|
| 25 | - closeCommunicationHandle chTheyRead
|
|
| 34 | + closeTheirEnd chTheyWrite
|
|
| 35 | + closeTheirEnd chTheyRead
|
|
| 26 | 36 | -- These handles have no finalizers, so close them ourselves if the spawn fails.
|
| 27 | 37 | ph <- createProc (proc prog args)
|
| 28 | 38 | `onException` (closeTheirs >> hClose rh >> hClose wh)
|
| 29 | 39 | closeTheirs
|
| 30 | 40 | return (ph, rh, wh)
|
| 41 | + |
|
| 42 | +-- | 'createWeReadTheyWritePipe', except in a non-threaded runtime on Windows
|
|
| 43 | +-- without WinIO. There process gives us a synchronous native 'Handle', and
|
|
| 44 | +-- reading from it is a safe call to @ReadFile@, which blocks every Haskell
|
|
| 45 | +-- thread until data arrives. As 'GHCi.Message.Async' always has a thread
|
|
| 46 | +-- waiting to read the pipe, no other thread would get to run. So in that case
|
|
| 47 | +-- we swap our end for a file descriptor 'Handle', whose reads only block the
|
|
| 48 | +-- reading thread.
|
|
| 49 | +fixedCreateWeReadTheyWritePipe :: IO (Handle, CommunicationHandle)
|
|
| 50 | +fixedCreateWeReadTheyWritePipe = do
|
|
| 51 | + (h, ch) <- createWeReadTheyWritePipe
|
|
| 52 | + h' <- toFdHandleIfNeeded h
|
|
| 53 | + return (h', ch)
|
|
| 54 | + |
|
| 55 | +-- | 'createTheyReadWeWritePipe', with the same exception as
|
|
| 56 | +-- 'fixedCreateWeReadTheyWritePipe'.
|
|
| 57 | +fixedCreateTheyReadWeWritePipe :: IO (CommunicationHandle, Handle)
|
|
| 58 | +fixedCreateTheyReadWeWritePipe = do
|
|
| 59 | + (ch, h) <- createTheyReadWeWritePipe
|
|
| 60 | + h' <- toFdHandleIfNeeded h
|
|
| 61 | + return (ch, h')
|
|
| 62 | + |
|
| 63 | +toFdHandleIfNeeded :: Handle -> IO Handle
|
|
| 64 | +#if defined(mingw32_HOST_OS)
|
|
| 65 | +-- The native 'Handle' has a finalizer that closes its @HANDLE@, so we wrap a
|
|
| 66 | +-- duplicate and close the original.
|
|
| 67 | +toFdHandleIfNeeded h
|
|
| 68 | + | not rtsSupportsBoundThreads && not isWindowsNativeIO = do
|
|
| 69 | + me <- Win32.getCurrentProcess
|
|
| 70 | + hh <- handleToHANDLE h
|
|
| 71 | + dup <- Win32.duplicateHandle me hh me 0 False Win32.dUPLICATE_SAME_ACCESS
|
|
| 72 | + hClose h
|
|
| 73 | + Win32.hANDLEToHandle dup
|
|
| 74 | + | otherwise = return h
|
|
| 75 | +#else
|
|
| 76 | +toFdHandleIfNeeded = return
|
|
| 77 | +#endif
|
|
| 78 | + |
|
| 79 | +-- | Workaround for locking prone closeCommunicationHandle on windows
|
|
| 80 | +--
|
|
| 81 | +-- Called after a createProcess: the subprocess might start reading from the
|
|
| 82 | +-- inherited raw handle before this close is scheduled, and, on windows,
|
|
| 83 | +-- closeCommunicationHandle will block on a pending read during its conversion
|
|
| 84 | +-- to Handle. Calling Win32.closeHandle directly avoids the blocking.
|
|
| 85 | +closeTheirEnd :: CommunicationHandle -> IO ()
|
|
| 86 | +#if defined(mingw32_HOST_OS)
|
|
| 87 | +closeTheirEnd (CommunicationHandle h) = Win32.closeHandle h
|
|
| 88 | +#else
|
|
| 89 | +closeTheirEnd = closeCommunicationHandle
|
|
| 90 | +#endif |
| ... | ... | @@ -1151,16 +1151,16 @@ runRemoteModFinalizers (ThModFinalizers finRefs) = do |
| 1151 | 1151 | let withForeignRefs [] f = f []
|
| 1152 | 1152 | withForeignRefs (x : xs) f = withForeignRef x $ \r ->
|
| 1153 | 1153 | withForeignRefs xs $ \rs -> f (r : rs)
|
| 1154 | - interp <- tcGetInterp
|
|
| 1154 | + interp0 <- tcGetInterp
|
|
| 1155 | 1155 | |
| 1156 | - case interpInstance interp of
|
|
| 1156 | + withInterp interp0 $ \interp -> case interpInstance interp of
|
|
| 1157 | 1157 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 1158 | 1158 | InternalInterp -> do
|
| 1159 | 1159 | qs <- liftIO (withForeignRefs finRefs $ mapM localRef)
|
| 1160 | 1160 | runQinTcM $ sequence_ qs
|
| 1161 | 1161 | #endif
|
| 1162 | 1162 | |
| 1163 | - ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
|
|
| 1163 | + ExternalInterp ext -> withExtInterp ext $ \inst -> do
|
|
| 1164 | 1164 | tcg <- getGblEnv
|
| 1165 | 1165 | th_state <- readTcRef (tcg_th_remote_state tcg)
|
| 1166 | 1166 | case th_state of
|
| ... | ... | @@ -1807,17 +1807,17 @@ runTHDec = runTH THDec |
| 1807 | 1807 | |
| 1808 | 1808 | runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
|
| 1809 | 1809 | runTH ty fhv = do
|
| 1810 | - interp <- tcGetInterp
|
|
| 1811 | - case interpInstance interp of
|
|
| 1810 | + interp0 <- tcGetInterp
|
|
| 1811 | + withInterp interp0 $ \ interp -> case interpInstance interp of
|
|
| 1812 | 1812 | #if defined(HAVE_INTERNAL_INTERPRETER)
|
| 1813 | 1813 | InternalInterp -> do
|
| 1814 | 1814 | -- Run it in the local TcM
|
| 1815 | - hv <- liftIO $ wormhole interp fhv
|
|
| 1815 | + hv <- liftIO $ wormhole interp0 fhv
|
|
| 1816 | 1816 | r <- runQinTcM (unsafeCoerce hv :: TH.Q a)
|
| 1817 | 1817 | return r
|
| 1818 | 1818 | #endif
|
| 1819 | 1819 | |
| 1820 | - ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
|
|
| 1820 | + ExternalInterp ext -> withExtInterp ext $ \inst -> do
|
|
| 1821 | 1821 | -- Run it on the server. For an overview of how TH works with
|
| 1822 | 1822 | -- Remote GHCi, see Note [Remote Template Haskell] in
|
| 1823 | 1823 | -- libraries/ghci/GHCi/TH.hs.
|
| ... | ... | @@ -3031,7 +3031,7 @@ mkThAppTs fun_ty arg_tys = foldl' TH.AppT fun_ty arg_tys |
| 3031 | 3031 | noTH :: UnrepresentableTypeDescr -> Type -> TcM a
|
| 3032 | 3032 | noTH s d = failWithTc $ TcRnTHError $ THReifyError $ CannotRepresentType s d
|
| 3033 | 3033 | |
| 3034 | -tcGetInterp :: TcM Interp
|
|
| 3034 | +tcGetInterp :: TcM SafeInterp
|
|
| 3035 | 3035 | tcGetInterp = do
|
| 3036 | 3036 | hsc_env <- getTopEnv
|
| 3037 | 3037 | case hsc_interp hsc_env of
|
| ... | ... | @@ -475,8 +475,8 @@ printStats dflags ActionStats{actionAllocs = mallocs, actionElapsedTime = secs} |
| 475 | 475 | |
| 476 | 476 | revertCAFs :: GhciMonad m => m ()
|
| 477 | 477 | revertCAFs = do
|
| 478 | - interp <- hscInterp <$> GHC.getSession
|
|
| 479 | - liftIO $ interpCmd interp RtsRevertCAFs
|
|
| 478 | + interp0 <- hscInterp <$> GHC.getSession
|
|
| 479 | + liftIO $ withInterp interp0 $ \interp -> interpCmd interp RtsRevertCAFs
|
|
| 480 | 480 | s <- getGHCiState
|
| 481 | 481 | when (not (ghc_e s)) turnOffBuffering
|
| 482 | 482 | -- Have to turn off buffering again, because we just
|
| ... | ... | @@ -27,7 +27,7 @@ module GHCi.Message |
| 27 | 27 | , QState(..)
|
| 28 | 28 | , getMessage, putMessage, getTHMessage, putTHMessage
|
| 29 | 29 | |
| 30 | - , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe
|
|
| 30 | + , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe, isPipeOpen
|
|
| 31 | 31 | , remoteCall, remoteCallInterleaving, remoteTHCall
|
| 32 | 32 | , handleRemoteCall, handleRemoteTHCall, writeReply
|
| 33 | 33 | , RemoteProcessException(..), PipeClosedException(..)
|
| ... | ... | @@ -8,6 +8,7 @@ module GHCi.Message.Async |
| 8 | 8 | -- * Pipes
|
| 9 | 9 | Pipe(..), mkPipeFromHandles, mkPipeFromContinuations
|
| 10 | 10 | , closePipe, PipeClosedException(..)
|
| 11 | + , closingPipe, isPipeOpen
|
|
| 11 | 12 | |
| 12 | 13 | -- * Interface for async bidirectional RPC
|
| 13 | 14 | , remoteAsyncReq, handleAsyncReq
|
| ... | ... | @@ -31,7 +32,7 @@ module GHCi.Message.Async |
| 31 | 32 | |
| 32 | 33 | -- * Serializable exceptions
|
| 33 | 34 | , SerializableException(..)
|
| 34 | - , toSerializableException, fromSerializableException, closingPipe
|
|
| 35 | + , toSerializableException, fromSerializableException
|
|
| 35 | 36 | ) where
|
| 36 | 37 | |
| 37 | 38 | import Prelude -- See note [Why do we import Prelude here?]
|
| ... | ... | @@ -159,6 +160,11 @@ closePipe Pipe{..} = do |
| 159 | 160 | throwTo (asyncFillTid pipeAsyncMngr) PipeWriteClosedException
|
| 160 | 161 | `finally` throwTo (asyncDrainTid pipeAsyncMngr) PipeReadClosedException
|
| 161 | 162 | |
| 163 | +isPipeOpen :: Pipe -> STM Bool
|
|
| 164 | +isPipeOpen pipe = liftM2 (&&)
|
|
| 165 | + (isOpen <$> readTVar (pipeReadStatus pipe))
|
|
| 166 | + (isOpen <$> readTVar (pipeWriteStatus pipe))
|
|
| 167 | + |
|
| 162 | 168 | closingPipeEnd :: TVar PipeEndStatus -> STM PipeEndStatus
|
| 163 | 169 | closingPipeEnd v = readTVar v >>= \ s -> do
|
| 164 | 170 | case s of
|
| ... | ... | @@ -598,9 +604,8 @@ drainPipe p unmask = catch loop (void . replyToPendings) where |
| 598 | 604 | Just q -> writeTQueue q (uq,bs)
|
| 599 | 605 | Cancel uq -> cancelRequest am uq
|
| 600 | 606 | |
| 601 | - replyToPendings e = do
|
|
| 602 | - atomically $ failPendingReplies p e
|
|
| 603 | - pipeCloseRead p `catch` \(_ :: IOException) -> pure ()
|
|
| 607 | + replyToPendings e = finally (pipeCloseRead p `catch` \(_ :: IOException) -> pure ()) -- TODO: log with verbose.
|
|
| 608 | + . atomically $ failPendingReplies p e
|
|
| 604 | 609 | |
| 605 | 610 | am = pipeAsyncMngr p
|
| 606 | 611 | |
| ... | ... | @@ -669,8 +674,8 @@ fillPipe p unmask = loop `catch` cleanup Nothing where |
| 669 | 674 | |
| 670 | 675 | am = pipeAsyncMngr p
|
| 671 | 676 | |
| 672 | - cleanup last_write e0 = do
|
|
| 673 | - atomically $ do
|
|
| 677 | + cleanup last_write e0 = finally (pipeCloseWrite p `catch` \(_ :: IOException) -> pure ()) -- TODO: log with verbose
|
|
| 678 | + . atomically $ do
|
|
| 674 | 679 | -- deactivate here too so we keep track of the exception if end still 'Open'.
|
| 675 | 680 | s <- deactivatePipeEnd (pipeWriteStatus p) (Just e0)
|
| 676 | 681 | case last_write of
|
| ... | ... | @@ -680,7 +685,6 @@ fillPipe p unmask = loop `catch` cleanup Nothing where |
| 680 | 685 | putTMVar var . Left $ if isOpen s then e0 else toException PipeWriteClosedException
|
| 681 | 686 | -- real exception already reported once
|
| 682 | 687 | failPendingWrites p $ toException PipeWriteClosedException
|
| 683 | - pipeCloseWrite p `catch` \(_ :: IOException) -> pure ()
|
|
| 684 | 688 | |
| 685 | 689 | failPendingWrites :: Pipe -> SomeException -> STM ()
|
| 686 | 690 | failPendingWrites p e = do
|
| ... | ... | @@ -8,3 +8,14 @@ test('interp-cancellation', |
| 8 | 8 | ],
|
| 9 | 9 | multimod_compile_and_run,
|
| 10 | 10 | ['Main.hs', '-package ghc -package ghci'])
|
| 11 | + |
|
| 12 | +test('interp-concurrent',
|
|
| 13 | + [ extra_run_opts(f'"{config.libdir}"')
|
|
| 14 | + , windows_skip
|
|
| 15 | + , when(config.cross, skip)
|
|
| 16 | + , req_th
|
|
| 17 | + , unless(config.have_ext_interp, skip)
|
|
| 18 | + , only_ways(['normal'])
|
|
| 19 | + ],
|
|
| 20 | + compile_and_run,
|
|
| 21 | + ['-package ghc -threaded']) |
| 1 | +{-# LANGUAGE LambdaCase, ScopedTypeVariables #-}
|
|
| 2 | + |
|
| 3 | +-- | Several threads share one GHC session, and so one external interpreter.
|
|
| 4 | +--
|
|
| 5 | +-- Checks that concurrent requests get their own replies, that killing threads
|
|
| 6 | +-- waiting on the interpreter leaves it usable, that killing a thread running a
|
|
| 7 | +-- splice cancels the splice in the interpreter, and that when the interpreter
|
|
| 8 | +-- dies it is stopped and the next request starts a new one.
|
|
| 9 | +module Main (main) where
|
|
| 10 | + |
|
| 11 | +import Control.Concurrent
|
|
| 12 | +import Control.Exception
|
|
| 13 | +import Control.Monad
|
|
| 14 | +import Control.Monad.IO.Class (liftIO)
|
|
| 15 | +import Data.Either (isLeft)
|
|
| 16 | +import Data.Maybe (isJust, isNothing)
|
|
| 17 | +import System.Directory (doesFileExist, removeFile)
|
|
| 18 | +import System.Environment (getArgs)
|
|
| 19 | +import System.Exit (exitFailure)
|
|
| 20 | +import System.IO
|
|
| 21 | +import System.Posix.Signals (sigKILL, signalProcess)
|
|
| 22 | +import System.Process (ProcessHandle, getPid, getProcessExitCode)
|
|
| 23 | +import System.Timeout (timeout)
|
|
| 24 | + |
|
| 25 | +import GHC
|
|
| 26 | +import GHC.Driver.Env (hscInterp)
|
|
| 27 | +import GHC.Driver.Monad (Session, reflectGhc, reifyGhc)
|
|
| 28 | +import GHC.Driver.Session (gopt_set, xopt_set)
|
|
| 29 | +import qualified GHC.LanguageExtensions as LangExt
|
|
| 30 | +import GHC.Runtime.Interpreter (evalString, evalStringToIOString)
|
|
| 31 | +import GHC.Runtime.Interpreter.Types
|
|
| 32 | +import GHCi.Message (PipeClosedException)
|
|
| 33 | + |
|
| 34 | +main :: IO ()
|
|
| 35 | +main = do
|
|
| 36 | + hSetBuffering stdout LineBuffering
|
|
| 37 | + [libdir] <- getArgs
|
|
| 38 | + mapM_ removeIfExists markers
|
|
| 39 | + runGhc (Just libdir) $ do
|
|
| 40 | + let withTH fs = foldl xopt_set fs
|
|
| 41 | + [LangExt.TemplateHaskell, LangExt.TemplateHaskellQuotes]
|
|
| 42 | + dflags <- getSessionDynFlags
|
|
| 43 | + _ <- setSessionDynFlags (withTH (gopt_set dflags Opt_ExternalInterpreter))
|
|
| 44 | + { ghcLink = LinkInMemory }
|
|
| 45 | + setContext [ IIDecl (simpleImportDecl (mkModuleName m))
|
|
| 46 | + | m <- [ "Prelude", "Control.Concurrent", "Control.Exception"
|
|
| 47 | + , "System.IO", "System.IO.Error", "Language.Haskell.TH" ] ]
|
|
| 48 | + reifyGhc $ \s -> do
|
|
| 49 | + concurrentReplies s
|
|
| 50 | + killWaiting s
|
|
| 51 | + killSplice s
|
|
| 52 | + interpreterDies s
|
|
| 53 | + |
|
| 54 | +--------------------------------------------------------------------------------
|
|
| 55 | +-- Scenarios
|
|
| 56 | + |
|
| 57 | +concurrentReplies :: Session -> IO ()
|
|
| 58 | +concurrentReplies s = do
|
|
| 59 | + echo <- compile s echoExpr
|
|
| 60 | + ws <- forM [1 .. 16 :: Int] $ \n -> async $
|
|
| 61 | + forM [1 .. 50 :: Int] $ \k -> do
|
|
| 62 | + let x = show (n, k)
|
|
| 63 | + (== x) <$> evalEcho s echo x
|
|
| 64 | + rs <- mapM (waiting "concurrent requests" . readMVar . snd) ws
|
|
| 65 | + check "concurrent requests each get their own reply"
|
|
| 66 | + (all (either (const False) and) rs)
|
|
| 67 | + |
|
| 68 | +-- | Kill threads waiting on two gated requests, and check a third request
|
|
| 69 | +-- made alongside them still gets its reply.
|
|
| 70 | +killWaiting :: Session -> IO ()
|
|
| 71 | +killWaiting s = do
|
|
| 72 | + echo <- compile s echoExpr
|
|
| 73 | + -- Compiled up front: compiling needs the interpreter, which 'a' may hold up.
|
|
| 74 | + bAct <- compile s (gated "b.started" "b.gate" "pure \"b\"")
|
|
| 75 | + (a, aRes) <- async $ inSession s $
|
|
| 76 | + execStmt (gated "a.started" "a.gate" "pure ()") execOptions
|
|
| 77 | + awaitFileUntil "the statement to start" "a.started" aRes
|
|
| 78 | + (b, bRes) <- async $ evalFHV s bAct
|
|
| 79 | + (_, cRes) <- async $ evalEcho s echo "c"
|
|
| 80 | + threadDelay 100000 -- let b and c send their requests
|
|
| 81 | + waiting "killing the thread waiting on the statement" (killThread a)
|
|
| 82 | + waiting "killing the thread waiting on the other one" (killThread b)
|
|
| 83 | + aR <- waiting "the killed statement thread to finish" (readMVar aRes)
|
|
| 84 | + bR <- waiting "the other killed thread to finish" (readMVar bRes)
|
|
| 85 | + check "killed threads stop waiting for their replies"
|
|
| 86 | + (isKilled aR && isKilled bR)
|
|
| 87 | + -- Let the server side evaluation of 'a' and 'b' go through, since eval
|
|
| 88 | + -- requests ignore canceling atm.
|
|
| 89 | + mapM_ (`writeFile` "") ["a.gate", "b.gate"]
|
|
| 90 | + cR <- waiting "the remaining request's reply" (readMVar cRes)
|
|
| 91 | + check "a request made alongside cancelled ones gets its reply"
|
|
| 92 | + (either (const False) (== "c") cR)
|
|
| 93 | + stillAnswers s echo
|
|
| 94 | + |
|
| 95 | +-- | Splices run in their own thread in the interpreter, so they don't hold up
|
|
| 96 | +-- other requests, and can be cancelled there.
|
|
| 97 | +killSplice :: Session -> IO ()
|
|
| 98 | +killSplice s = do
|
|
| 99 | + echo <- compile s echoExpr
|
|
| 100 | + (t, tRes) <- async $ inSession s $
|
|
| 101 | + compileExprRemote (blockingSplice "th.started" "th.cancelled")
|
|
| 102 | + awaitFileUntil "the splice to start" "th.started" tRes
|
|
| 103 | + r <- waiting "a request while a splice runs" (evalEcho s echo "during splice")
|
|
| 104 | + check "a running splice does not hold up other requests"
|
|
| 105 | + (r == "during splice")
|
|
| 106 | + waiting "killing the thread running the splice" (killThread t)
|
|
| 107 | + tR <- waiting "the killed splice thread to finish" (readMVar tRes)
|
|
| 108 | + check "the thread running the splice is killed" (isKilled tR)
|
|
| 109 | + awaitFile "the splice to be cancelled in the interpreter" "th.cancelled"
|
|
| 110 | + -- just printing what we can infer from the previous line.
|
|
| 111 | + check "the splice is cancelled in the interpreter" True
|
|
| 112 | + stillAnswers s echo
|
|
| 113 | + |
|
| 114 | +-- | Kill the interpreter while one thread waits on a statement and another
|
|
| 115 | +-- runs a splice.
|
|
| 116 | +interpreterDies :: Session -> IO ()
|
|
| 117 | +interpreterDies s = do
|
|
| 118 | + _ <- compile s echoExpr
|
|
| 119 | + ph <- runningInterp s >>= maybe (failWith "no interpreter running") pure
|
|
| 120 | + pid <- getPid ph >>= maybe (failWith "interpreter has no pid") pure
|
|
| 121 | + |
|
| 122 | + -- Splice first: compiling it needs the interpreter, which the statement
|
|
| 123 | + -- may hold up.
|
|
| 124 | + (_, fRes) <- async $ inSession s $
|
|
| 125 | + compileExprRemote (blockingSplice "f.started" "f.cancelled")
|
|
| 126 | + awaitFileUntil "the splice to start" "f.started" fRes
|
|
| 127 | + (_, dRes) <- async $ evalIn s (gated "d.started" "d.gate" "pure \"d\"")
|
|
| 128 | + awaitFileUntil "the statement to start" "d.started" dRes
|
|
| 129 | + |
|
| 130 | + signalProcess sigKILL pid
|
|
| 131 | + dR <- waiting "the statement thread to fail" (readMVar dRes)
|
|
| 132 | + check "a thread waiting on a dead interpreter gets PipeClosedException"
|
|
| 133 | + (isPipeClosed dR)
|
|
| 134 | + fR <- waiting "the splice thread to fail" (readMVar fRes)
|
|
| 135 | + check "a thread running a splice in a dead interpreter fails" (isLeft fR)
|
|
| 136 | + |
|
| 137 | + st <- runningInterp s
|
|
| 138 | + check "the dead interpreter is stopped" (isNothing st)
|
|
| 139 | + ex <- getProcessExitCode ph
|
|
| 140 | + check "its process is reaped" (isJust ex)
|
|
| 141 | + |
|
| 142 | + r <- waiting "a request after the interpreter died"
|
|
| 143 | + (evalIn s "pure \"alive\" :: IO String")
|
|
| 144 | + check "the next request starts a new interpreter" (r == "alive")
|
|
| 145 | + ph' <- runningInterp s >>= maybe (failWith "no interpreter running") pure
|
|
| 146 | + pid' <- getPid ph'
|
|
| 147 | + check "the new interpreter is a different process" (pid' /= Just pid)
|
|
| 148 | + |
|
| 149 | +--------------------------------------------------------------------------------
|
|
| 150 | +-- Talking to the interpreter through the session
|
|
| 151 | + |
|
| 152 | +inSession :: Session -> Ghc a -> IO a
|
|
| 153 | +inSession = flip reflectGhc
|
|
| 154 | + |
|
| 155 | +compile :: Session -> String -> IO ForeignHValue
|
|
| 156 | +compile s e = inSession s (compileExprRemote e)
|
|
| 157 | + |
|
| 158 | +-- | Compile an @IO String@ and run it.
|
|
| 159 | +evalIn :: Session -> String -> IO String
|
|
| 160 | +evalIn s e = compile s e >>= evalFHV s
|
|
| 161 | + |
|
| 162 | +-- | Run a compiled @IO String@.
|
|
| 163 | +evalFHV :: Session -> ForeignHValue -> IO String
|
|
| 164 | +evalFHV s fhv = inSession s $ do
|
|
| 165 | + hsc_env <- getSession
|
|
| 166 | + liftIO (evalString (hscInterp hsc_env) fhv)
|
|
| 167 | + |
|
| 168 | +evalEcho :: Session -> ForeignHValue -> String -> IO String
|
|
| 169 | +evalEcho s echo x = inSession s $ do
|
|
| 170 | + hsc_env <- getSession
|
|
| 171 | + liftIO (evalStringToIOString (hscInterp hsc_env) echo x)
|
|
| 172 | + |
|
| 173 | +stillAnswers :: Session -> ForeignHValue -> IO ()
|
|
| 174 | +stillAnswers s echo = do
|
|
| 175 | + r <- waiting "a request after the cancellations" (evalEcho s echo "after")
|
|
| 176 | + check "the interpreter still answers" (r == "after")
|
|
| 177 | + |
|
| 178 | +runningInterp :: Session -> IO (Maybe ProcessHandle)
|
|
| 179 | +runningInterp s = do
|
|
| 180 | + interp <- inSession s (hscInterp <$> getSession)
|
|
| 181 | + case interpInstance interp of
|
|
| 182 | + ExternalInterp (ExtIServ st) -> readMVar (interpStatus st) >>= \case
|
|
| 183 | + InterpRunning inst -> pure (Just (interpHandle (instProcess inst)))
|
|
| 184 | + InterpPending -> pure Nothing
|
|
| 185 | + _ -> failWith "not using an external interpreter"
|
|
| 186 | + |
|
| 187 | +--------------------------------------------------------------------------------
|
|
| 188 | +-- Interpreted code
|
|
| 189 | + |
|
| 190 | +echoExpr :: String
|
|
| 191 | +echoExpr = "(\\x -> pure x) :: String -> IO String"
|
|
| 192 | + |
|
| 193 | +-- | Creates @started@, waits for @gate@ to exist, then runs @k@.
|
|
| 194 | +gated :: FilePath -> FilePath -> String -> String
|
|
| 195 | +gated started gate k = concat
|
|
| 196 | + [ "let { waitFor p = catchIOError (withFile p ReadMode (\\_ -> pure ()))"
|
|
| 197 | + , " (\\_ -> threadDelay 10000 >> waitFor p) }"
|
|
| 198 | + , " in writeFile ", show started, " \"\" >> waitFor ", show gate, " >> ", k ]
|
|
| 199 | + |
|
| 200 | +-- | Creates @started@, then blocks. Creates @cancelled@ if interrupted.
|
|
| 201 | +blockingSplice :: FilePath -> FilePath -> String
|
|
| 202 | +blockingSplice started cancelled = concat
|
|
| 203 | + [ "$(runIO (writeFile ", show started, " \"\""
|
|
| 204 | + , " >> (threadDelay maxBound `onException` writeFile ", show cancelled, " \"\"))"
|
|
| 205 | + , " >> [| () |])" ]
|
|
| 206 | + |
|
| 207 | +markers :: [FilePath]
|
|
| 208 | +markers = [ "a.started", "a.gate", "b.started", "b.gate"
|
|
| 209 | + , "th.started", "th.cancelled"
|
|
| 210 | + , "d.started", "d.gate", "f.started", "f.cancelled" ]
|
|
| 211 | + |
|
| 212 | +--------------------------------------------------------------------------------
|
|
| 213 | +-- Utilities
|
|
| 214 | + |
|
| 215 | +async :: IO a -> IO (ThreadId, MVar (Either SomeException a))
|
|
| 216 | +async act = do
|
|
| 217 | + v <- newEmptyMVar
|
|
| 218 | + t <- forkFinally act (putMVar v)
|
|
| 219 | + pure (t, v)
|
|
| 220 | + |
|
| 221 | +awaitFile :: String -> FilePath -> IO ()
|
|
| 222 | +awaitFile what p = waiting what loop
|
|
| 223 | + where
|
|
| 224 | + loop = doesFileExist p >>= \b -> unless b (threadDelay 10000 >> loop)
|
|
| 225 | + |
|
| 226 | +-- | Like 'awaitFile', but fails straight away if the thread that should
|
|
| 227 | +-- create the file ends first.
|
|
| 228 | +awaitFileUntil :: String -> FilePath -> MVar (Either SomeException a) -> IO ()
|
|
| 229 | +awaitFileUntil what p res = waiting what loop
|
|
| 230 | + where
|
|
| 231 | + loop = do
|
|
| 232 | + b <- doesFileExist p
|
|
| 233 | + unless b $ tryReadMVar res >>= \case
|
|
| 234 | + Just r -> failWith ("waiting for " ++ what ++ ", the thread ended: "
|
|
| 235 | + ++ either show (const "no exception") r)
|
|
| 236 | + Nothing -> threadDelay 10000 >> loop
|
|
| 237 | + |
|
| 238 | +removeIfExists :: FilePath -> IO ()
|
|
| 239 | +removeIfExists p = removeFile p `catch` \(_ :: IOException) -> pure ()
|
|
| 240 | + |
|
| 241 | +isKilled :: Either SomeException a -> Bool
|
|
| 242 | +isKilled = \case
|
|
| 243 | + Left e | Just ThreadKilled <- fromException e -> True
|
|
| 244 | + _ -> False
|
|
| 245 | + |
|
| 246 | +isPipeClosed :: Either SomeException a -> Bool
|
|
| 247 | +isPipeClosed = \case
|
|
| 248 | + Left e | Just (_ :: PipeClosedException) <- fromException e -> True
|
|
| 249 | + _ -> False
|
|
| 250 | + |
|
| 251 | +-- | Adds a timeout so we fail with a message rather than hang the whole test.
|
|
| 252 | +waiting :: String -> IO a -> IO a
|
|
| 253 | +waiting what act =
|
|
| 254 | + timeout (60 * 1000000) act >>= maybe (failWith ("timed out waiting for " ++ what)) pure
|
|
| 255 | + |
|
| 256 | +failWith :: String -> IO a
|
|
| 257 | +failWith what = do
|
|
| 258 | + hPutStrLn stderr ("FAILED: " ++ what)
|
|
| 259 | + hFlush stderr
|
|
| 260 | + exitFailure
|
|
| 261 | + |
|
| 262 | +check :: String -> Bool -> IO ()
|
|
| 263 | +check what ok
|
|
| 264 | + | ok = putStrLn ("ok: " ++ what)
|
|
| 265 | + | otherwise = void (failWith what) |
| 1 | +ok: concurrent requests each get their own reply
|
|
| 2 | +ok: killed threads stop waiting for their replies
|
|
| 3 | +ok: a request made alongside cancelled ones gets its reply
|
|
| 4 | +ok: the interpreter still answers
|
|
| 5 | +ok: a running splice does not hold up other requests
|
|
| 6 | +ok: the thread running the splice is killed
|
|
| 7 | +ok: the splice is cancelled in the interpreter
|
|
| 8 | +ok: the interpreter still answers
|
|
| 9 | +ok: a thread waiting on a dead interpreter gets PipeClosedException
|
|
| 10 | +ok: a thread running a splice in a dead interpreter fails
|
|
| 11 | +ok: the dead interpreter is stopped
|
|
| 12 | +ok: its process is reaped
|
|
| 13 | +ok: the next request starts a new interpreter
|
|
| 14 | +ok: the new interpreter is a different process |