Zubin pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC Commits: 3e66b59c by Andrea Vezzosi at 2026-11-23T12:52:30+05:30 test case for #28104 (cherry picked from commit c032076a9cd2a6ce2fea66df98fd5f5c85e81aac) - - - - - d991ab3c by Zubin Duggal at 2026-11-23T14:02:49+05:30 loader: fix #28104 Ensure LoaderState is recorded accurately and consistent in the presence of failures * loadObjects: when resolveObjs fails, unload only the objects freshly loaded and return the old LoaderState. Before this we used to unload every home module with unload_wkr, but then its callers threw inside `modifyLoaderState`, which restored the old state, which contained objects that were already unloaded. The objects loaded by `loadObjects` are also unloaded if loading or resolving fails. * loadName, loadDecls, loadModule: report failure after the transaction has committed, so we don't mangle the loader state by restoring the old state. * unload: Keep track of things that were succefully unloaded on exception and unload each object of a module only once. The foreign stub objects of a bytecode module are recorded in both objs_loaded and bcos_loaded, so with a non-dynamic interpreter unloading such a module called unloadObj twice on the same object and failed. Fixes #28104 - - - - - 19a4dfcd by Zubin Duggal at 2026-11-23T14:02:49+05:30 loader: make crucial sequences uninterruptible Add masks so that we don't observe async exceptions during sequences that can't deal with them. - - - - - 10 changed files: - compiler/GHC/Linker/Loader.hs - compiler/GHC/Runtime/Interpreter.hs - + testsuite/tests/ghci/linking/UnloadWkrA.hs - + testsuite/tests/ghci/linking/UnloadWkrB.hs - testsuite/tests/ghci/linking/all.T - + testsuite/tests/ghci/linking/unload_wkr-throw-ext.stderr - + testsuite/tests/ghci/linking/unload_wkr-throw-ext.stdout - + testsuite/tests/ghci/linking/unload_wkr-throw.script - + testsuite/tests/ghci/linking/unload_wkr-throw.stderr - + testsuite/tests/ghci/linking/unload_wkr-throw.stdout Changes: ===================================== compiler/GHC/Linker/Loader.hs ===================================== @@ -111,6 +111,7 @@ import GHC.Linker.Types import Control.Monad import Data.Array +import Data.Containers.ListUtils (nubOrd) import Data.ByteString (ByteString) import qualified Data.Set as Set import Data.Char (isSpace) @@ -172,12 +173,12 @@ uninitialised = panic "Loader not initialised" modifyLoaderState_ :: SafeInterp -> (Interp -> LoaderState -> IO LoaderState) -> IO () modifyLoaderState_ interp0 f = withInterp interp0 $ \ interp -> - modifyMVar_ (loader_state (interpLoader interp)) + modifyMVarMasked_ (loader_state (interpLoader interp)) (fmap pure . f interp . fromMaybe uninitialised) modifyLoaderState :: SafeInterp -> (Interp -> LoaderState -> IO (LoaderState, a)) -> IO a modifyLoaderState interp0 f = withInterp interp0 $ \ interp -> - modifyMVar (loader_state (interpLoader interp)) + modifyMVarMasked (loader_state (interpLoader interp)) (fmapFst pure . f interp . fromMaybe uninitialised) where fmapFst f = fmap (\(x, y) -> (f x, y)) @@ -234,27 +235,27 @@ lookupFromLoadedEnv interp name = 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 - (pls', ok, links, pkgs) <- loadDependencies interp hsc_env pls0 noSrcSpan - [nameModule name] - if failed ok - then throwGhcExceptionIO (ProgramError "") - else return (pls', links, pkgs) - - case lookupNameBytecodeState (bco_loader_state pls) name of - Just (_,aa) -> return (pls,(aa, links, pkgs)) + (ok, m, links, pkgs) <- modifyLoaderState interp0 $ \interp pls0 -> do + (pls, ok, links, pkgs) <- if not (isExternalName name) + then return (pls0, Succeeded, [], emptyUDFM) + else loadDependencies interp hsc_env pls0 noSrcSpan [nameModule name] + + m <- case lookupNameBytecodeState (bco_loader_state pls) name of + _ | failed ok -> return Nothing + Just (_,aa) -> return (Just aa) 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 - Nothing -> linkFail "GHC.Linker.Loader.loadName" - (ppr sym_to_find) - return (pls,(r, links, pkgs)) + -- TODO: does not take loader state lock + interpUninterruptibleMask_ interp $ + lookupClosure interp sym_to_find + return (pls, (ok, m, links, pkgs)) + + when (failed ok) $ throwGhcExceptionIO (ProgramError "") + case m of + Just fhv -> return (fhv, links, pkgs) + Nothing -> linkFail "GHC.Linker.Loader.loadName" + (ppr sym_to_find) + where + sym_to_find = IClosureSymbol name -- | Restrict a 'PkgsLoaded' map to the packages directly needed and their -- full transitive closure (via 'loaded_pkg_trans_deps'). @@ -465,7 +466,7 @@ loadCmdLineLibs'' interp hsc_env pls = ++ map Framework frameworks if null cmdline_lib_specs then return pls - else do + else interpUninterruptibleMask_ interp $ do -- Add directories to library search paths, this only has an effect -- on Windows. On Unix OSes this function is a NOP. let all_paths = let paths = takeDirectory (pgm_c dflags) @@ -737,16 +738,19 @@ loadDecls interp0 hsc_env span linkable = do initLoaderState interp0 hsc_env -- Take lock for the actual work. - modifyLoaderState interp0 $ \interp pls0 -> do + (ok, ok2, links_needed, units_needed) <- 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 - then throwGhcExceptionIO (ProgramError "could not load dependencies for decls") - else do - (pls2, ok2) <- loadInternalModuleLinkables interp hsc_env pls [linkable] - when (failed ok2) $ - throwGhcExceptionIO (ProgramError "could not load linkable for decls") - return (pls2, (links_needed, units_needed)) + (pls2, ok2) <- if failed ok + then return (pls, Failed) + else loadInternalModuleLinkables interp hsc_env pls [linkable] + return (pls2, (ok, ok2, links_needed, units_needed)) + + when (failed ok) $ + throwGhcExceptionIO (ProgramError "could not load dependencies for decls") + when (failed ok2) $ + throwGhcExceptionIO (ProgramError "could not load linkable for decls") + return (links_needed, units_needed) where cbcs = linkableBCOs linkable @@ -774,11 +778,11 @@ loadDecls interp0 hsc_env span linkable = do loadModule :: SafeInterp -> HscEnv -> Module -> IO () loadModule interp0 hsc_env mod = do initLoaderState interp0 hsc_env - modifyLoaderState_ interp0 $ \interp pls -> do + ok <- modifyLoaderState interp0 $ \interp pls -> do (pls', ok, _, _) <- loadDependencies interp hsc_env pls noSrcSpan [mod] - if failed ok - then throwGhcExceptionIO (ProgramError "could not load module") - else return pls' + return (pls', ok) + when (failed ok) $ + throwGhcExceptionIO (ProgramError "could not load module") {- ********************************************************************** @@ -811,7 +815,7 @@ loadInternalModuleLinkables interp hsc_env pls linkables = loadModuleLinkables :: Interp -> HscEnv -> LoaderState -> KeepModuleLinkableDefinitions -> [Linkable] -> IO (LoaderState, SuccessFlag) loadModuleLinkables interp hsc_env pls keep_spec linkables - = mask_ $ do -- don't want to be interrupted by ^C in here + = interpUninterruptibleMask_ interp $ do -- don't want to be interrupted by ^C in here debugTraceMsg (hsc_logger hsc_env) 3 $ hang (text "Loading module linkables") 2 $ vcat [ @@ -862,18 +866,19 @@ loadObjects interp hsc_env pls objs = do if interpreterDynamic interp then do pls2 <- dynLoadObjs interp hsc_env pls1 wanted_objs return (pls2, Succeeded) - else do mapM_ (loadObj interp) wanted_objs + else do loaded <- newIORef [] + let load obj = loadObj interp obj >> modifyIORef' loaded (obj :) + undo = readIORef loaded >>= mapM_ (unloadObj interp) -- Link them all together - ok <- resolveObjs interp + ok <- (mapM_ load wanted_objs >> resolveObjs interp) + `onException` undo - -- If resolving failed, unload all our - -- object modules and carry on if succeeded ok then return (pls1, Succeeded) else do - pls2 <- unload_wkr interp pls1 - return (pls2, Failed) + undo + return (pls, Failed) -- | Create a shared library containing the given object files @@ -1146,10 +1151,6 @@ What we need to avoid is having more in the 'LoaderState' than is actually loaded. This can only happen while unloading, which is why purge the symbol cache before the unload. -We should also make sure the emptied out loader state returned from unload_wkr -gets actually written to the loader state, the failure to do so is tracked by -#28104. - -} -- --------------------------------------------------------------------------- @@ -1168,16 +1169,15 @@ unload interp0 hsc_env -- Initialise the linker (if it's not been done already) initLoaderState interp0 hsc_env - _new_pls <- modifyLoaderState interp0 $ \interp pls -> do - pls1 <- unload_wkr interp pls - return (pls1, pls1) - - return () + withInterp interp0 $ \_ -> do + err <- modifyLoaderState interp0 $ \interp -> + interpUninterruptibleMask_ interp . unload_wkr interp + mapM_ throwIO err unload_wkr :: Interp -> LoaderState - -> IO LoaderState + -> IO (LoaderState, Maybe SomeException) -- Does the core unload business -- (the wrapper blocks exceptions and deals with the LS get and put) @@ -1186,41 +1186,47 @@ unload_wkr interp pls@LoaderState{..} = do -- we're unloading some code. -fghci-leak-check with the tests in -- testsuite/ghci can detect space leaks here. - let linkables_to_unload = moduleEnvElts objs_loaded ++ moduleEnvElts bcos_loaded + let objs_to_unload = mapModuleEnv nubOrd $ + plusModuleEnv_C (++) (mapModuleEnv linkableUsageObjs objs_loaded) + (mapModuleEnv linkableUsageObjs bcos_loaded) -- If we unloaded any object files at all, we need to purge the cache -- of lookupSymbol results. -- We do so before actually unloading, so the cache is never stale. -- -- See Note [LoaderState may lag the interpreter] - when (not (null (filter (not . null . linkableUsageObjs) linkables_to_unload))) $ + when (any (not . null) (moduleEnvElts objs_to_unload)) $ purgeLookupSymbolCache interp - mapM_ unloadObjs linkables_to_unload + (objs_left, err) <- foldM unloadObjs (objs_loaded, Nothing) (moduleEnvToList objs_to_unload) - -- FIXME: this emptied state should be committed even on exceptions, see #28104 let !new_pls = pls { bco_loader_state = modifyHomePackageBytecodeState bco_loader_state $ \_ -> emptyBytecodeState, -- NB: we don't unload the external package bcos_loaded = emptyModuleEnv, - objs_loaded = emptyModuleEnv } + objs_loaded = objs_left } - return new_pls + return (new_pls, err) where - unloadObjs :: LinkableUsage -> IO () - unloadObjs lnk - | interpreterDynamic interp = return () + unloadObjs + :: (LinkableSet LinkableUsage, Maybe SomeException) + -> (Module, [FilePath]) + -> IO (LinkableSet LinkableUsage, Maybe SomeException) + unloadObjs acc@(_, Just _) _ = return acc + unloadObjs (objs_left, Nothing) (mod, objs) + | interpreterDynamic interp = return (delModuleEnv objs_left mod, Nothing) -- We don't do any cleanup when linking objects with the -- dynamic linker. Doing so introduces extra complexity for -- not much benefit. | otherwise - = mapM_ (unloadObj interp) (linkableUsageObjs lnk) + = do r <- try $ mapM_ (unloadObj interp) objs -- The components of a BCO linkable may contain -- dot-o files (generated from C stubs). -- -- But the BCO parts can be unlinked just by -- letting go of them (plus of course depopulating -- the symbol table which is done in the main body) + return (delModuleEnv objs_left mod, either Just (const Nothing) r) showLS :: LibrarySpec -> String showLS (Objects nms) = "(static) [" ++ intercalate ", " nms ++ "]" @@ -1315,7 +1321,8 @@ loadPackages' :: Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState loadPackages' interp hsc_env new_pks pls = do (reverse -> pkgs_info_list, pkgs_almost_loaded) <- loadMoreUnits hsc_env new_pks (pkgs_loaded pls) - loadPackage interp hsc_env pkgs_info_list (pls { pkgs_loaded = pkgs_almost_loaded }) + interpUninterruptibleMask_ interp $ + loadPackage interp hsc_env pkgs_info_list (pls { pkgs_loaded = pkgs_almost_loaded }) loadPackage :: Interp -> HscEnv -> [UnitInfo] -> LoaderState -> IO LoaderState ===================================== compiler/GHC/Runtime/Interpreter.hs ===================================== @@ -49,6 +49,7 @@ module GHC.Runtime.Interpreter , interpCmd , withInterpCmdMasked + , interpUninterruptibleMask_ , withExtInterp , withExtInterpStatus , withIServ @@ -212,6 +213,17 @@ 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 +interpUninterruptibleMask_ :: Interp -> IO a -> IO a +interpUninterruptibleMask_ interp act = do + case interpInstance interp of +#if defined(HAVE_INTERNAL_INTERPRETER) + InternalInterp -> pure () +#endif + -- make sure the external interpreter process is running, so that the + -- interpreter is spawned outside the uninterruptibleMask + ExternalInterp ext -> withExtInterp ext $ \_ -> pure () + uninterruptibleMask_ act + -- | Passes the `Interp` to the continuation while setting up a -- 'PipeClosedException' handler that calls 'stopInterp'. -- ===================================== testsuite/tests/ghci/linking/UnloadWkrA.hs ===================================== @@ -0,0 +1,4 @@ +module UnloadWkrA where + +hello :: String +hello = "hello from UnloadWkrA" ===================================== testsuite/tests/ghci/linking/UnloadWkrB.hs ===================================== @@ -0,0 +1,11 @@ +module UnloadWkrB where + +-- Deliberately refers to a symbol that does not exist anywhere, so that +-- resolveObjs fails when this module's object code is linked into the +-- interpreter. That is the only way to reach the unload_wkr call in +-- GHC.Linker.Loader.loadObjects. +foreign import ccall unsafe "unload_wkr_throw_missing_symbol" + c_boom :: IO () + +boom :: IO () +boom = c_boom ===================================== testsuite/tests/ghci/linking/all.T ===================================== @@ -77,3 +77,53 @@ test('big-obj', [extra_files(['big-obj-c.c', 'big-obj.hs']), makefile_test, ['big-obj']) test('T25155', [req_c, req_th, req_interp, req_rts_linker, extra_files(['T25155_iserv_main.c', 'T25155_iserv.hs', 'T25155_TH.hs'])], makefile_test, []) + +# unload_wkr-throw{,-ext}: a link failure in one module must not silently +# unload another module that was already linked. +# +# When resolveObjs fails, GHC.Linker.Loader.loadObjects calls unload_wkr, which +# empties objs_loaded/bcos_loaded/bco_loader_state and returns the new state. +# But every caller of unload_wkr except `unload` itself then throws on the +# Failed result, so modifyLoaderState's modifyMVar restores the *old* state and +# GHC goes on believing UnloadWkrA is loaded after the interpreter has dropped +# it. Evaluating UnloadWkrA.hello then fails, and the :reload after it calls +# unloadObj on an object the RTS has already unloaded. +# +# Only reachable when the interpreter is not dynamic: the dynamic branch of +# loadObjects goes through dynLoadObjs and never calls resolveObjs at all. +# For the internal interpreter that means a non-dynamic GHC (hostIsDynamic is +# fixed at build time), hence the ghc_dynamic skip. The external interpreter +# takes its way from the session, so -static is enough there. +# +# The expected output is the *fixed* behaviour: UnloadWkrB fails to link and +# nothing else does, so UnloadWkrA keeps working and :reload succeeds. + +def normalise_unload_wkr(s): + import re + # The failing object is named with the full path of the test directory. + s = re.sub(r'(Could not load Object Code ).*(UnloadWkrB\.o)', r'\1\2', s) + # With -fexternal-interpreter the messages are prefixed with the name of + # the iserv binary, which GHC generates into a temporary directory. + # normalise_errmsg only knows how to normalise the compiler's own name. + s = re.sub(r'^ghc_tmp_\d+\.iserv:', 'ghc:', s, flags=re.M) + return s + +test('unload_wkr-throw', + [extra_files(['UnloadWkrA.hs', 'UnloadWkrB.hs']), + extra_run_opts('-fobject-code'), + only_ways(['ghci']), + unless(doing_ghci, skip), + req_rts_linker, + when(ghc_dynamic(), skip), + normalise_errmsg_fun(normalise_unload_wkr)], + ghci_script, ['unload_wkr-throw.script']) + +test('unload_wkr-throw-ext', + [extra_files(['UnloadWkrA.hs', 'UnloadWkrB.hs', + 'unload_wkr-throw.script']), + extra_run_opts('-static -fexternal-interpreter -fobject-code'), + only_ways(['ghci']), + unless(doing_ghci, skip), + req_rts_linker, + normalise_errmsg_fun(normalise_unload_wkr)], + ghci_script, ['unload_wkr-throw.script']) ===================================== testsuite/tests/ghci/linking/unload_wkr-throw-ext.stderr ===================================== @@ -0,0 +1,5 @@ +ghc: Failed to lookup symbol: unload_wkr_throw_missing_symbol, you might consider using --optimistic-linking + +ghc: Could not load Object Code UnloadWkrB.o. + +could not load dependencies for decls ===================================== testsuite/tests/ghci/linking/unload_wkr-throw-ext.stdout ===================================== @@ -0,0 +1,3 @@ +hello from UnloadWkrA +hello from UnloadWkrA +hello from UnloadWkrA ===================================== testsuite/tests/ghci/linking/unload_wkr-throw.script ===================================== @@ -0,0 +1,6 @@ +:load UnloadWkrA UnloadWkrB +putStrLn UnloadWkrA.hello +UnloadWkrB.boom +putStrLn UnloadWkrA.hello +:reload +putStrLn UnloadWkrA.hello ===================================== testsuite/tests/ghci/linking/unload_wkr-throw.stderr ===================================== @@ -0,0 +1,5 @@ +ghc: Failed to lookup symbol: unload_wkr_throw_missing_symbol, you might consider using --optimistic-linking + +ghc: Could not load Object Code UnloadWkrB.o. + +could not load dependencies for decls ===================================== testsuite/tests/ghci/linking/unload_wkr-throw.stdout ===================================== @@ -0,0 +1,3 @@ +hello from UnloadWkrA +hello from UnloadWkrA +hello from UnloadWkrA View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/abdfbbf39d8704a3bccebca9ae231a0... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/abdfbbf39d8704a3bccebca9ae231a0... 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