[Git][ghc/ghc][wip/sol/dont-use-global-variables] Don't use global variables to address concurrency bugs! (fixes #27234)
by Simon Hengel (@sol) 05 May '26
by Simon Hengel (@sol) 05 May '26
05 May '26
Simon Hengel pushed to branch wip/sol/dont-use-global-variables at Glasgow Haskell Compiler / GHC
Commits:
a3c8f7c8 by Simon Hengel at 2026-05-06T02:20:24+07:00
Don't use global variables to address concurrency bugs! (fixes #27234)
This was originally introduce with
88f38b03025386f0f1e8f5861eed67d80495168a to address #17922.
In this specific case a better fix would have been to synchronize on
stderr:
withHandle_ "stderrSupportsAnsiColors" stderr $ \ _ -> do
...
But apparently the dependency on `terminfo` was removed in
32ab07bf3d6ce45e8ea5b55e8095174a6b42a7f0, preventing #17922 in the first
place.
- - - - -
3 changed files:
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/SysTools/Terminal.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
Changes:
=====================================
compiler/GHC/Driver/DynFlags.hs
=====================================
@@ -545,6 +545,7 @@ initDynFlags dflags = do
`catchIOError` \_ -> return False
ghcNoUnicodeEnv <- lookupEnv "GHC_NO_UNICODE"
let useUnicode' = isNothing ghcNoUnicodeEnv && canUseUnicode
+ canUseColor <- stderrSupportsAnsiColors
maybeGhcColorsEnv <- lookupEnv "GHC_COLORS"
maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"
let adjustCols (Just env) = Col.parseScheme env
@@ -556,9 +557,9 @@ initDynFlags dflags = do
return dflags{
useUnicode = useUnicode',
useColor = useColor',
- canUseColor = stderrSupportsAnsiColors,
+ canUseColor = canUseColor,
-- if the terminal supports color, we assume it supports links as well
- canUseErrorLinks = stderrSupportsAnsiColors,
+ canUseErrorLinks = canUseColor,
colScheme = colScheme',
tmpDir = TempDir tmp_dir
}
=====================================
compiler/GHC/SysTools/Terminal.hs
=====================================
@@ -14,17 +14,9 @@ import qualified Graphics.Win32 as Win32
import qualified System.Win32 as Win32
#endif
-import System.IO.Unsafe
-
--- | Does the controlling terminal support ANSI color sequences?
--- This memoized to avoid thread-safety issues in ncurses (see #17922).
-stderrSupportsAnsiColors :: Bool
-stderrSupportsAnsiColors = unsafePerformIO stderrSupportsAnsiColors'
-{-# NOINLINE stderrSupportsAnsiColors #-}
-
-- | Check if ANSI escape sequences can be used to control color in stderr.
-stderrSupportsAnsiColors' :: IO Bool
-stderrSupportsAnsiColors' = do
+stderrSupportsAnsiColors :: IO Bool
+stderrSupportsAnsiColors = do
#if !defined(mingw32_HOST_OS)
-- Equivalent of https://hackage.haskell.org/package/ansi-terminal/docs/System-Console-ANSI.…
isTerminal <- hIsTerminalDevice stderr
=====================================
libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
=====================================
@@ -143,8 +143,8 @@ original handle is always replaced.
{-# INLINE withHandle #-}
withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
-withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act
-withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act
+withHandle fun h@(FileHandle _ m) = withHandle' fun h m
+withHandle fun h@(DuplexHandle _ m _) = withHandle' fun h m
withHandle' :: String -> Handle -> MVar Handle__
-> (Handle__ -> IO (Handle__,a)) -> IO a
@@ -157,8 +157,8 @@ withHandle' fun h m act =
{-# INLINE withHandle_ #-}
withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
-withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act
-withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act
+withHandle_ fun h@(FileHandle _ m) = withHandle_' fun h m
+withHandle_ fun h@(DuplexHandle _ m _) = withHandle_' fun h m
withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a
withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a3c8f7c88ecd3814ede806604eae0e4…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a3c8f7c88ecd3814ede806604eae0e4…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/marge_bot_batch_merge_job] 12 commits: Use __attribute__((dllimport)) for external RTS symbol declarations
by Marge Bot (@marge-bot) 05 May '26
by Marge Bot (@marge-bot) 05 May '26
05 May '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
9a9ae4df by Duncan Coutts at 2026-05-05T14:44:37-04:00
Use __attribute__((dllimport)) for external RTS symbol declarations
This is needed to be hygenic about DLL symbol imports and exports.
The attribute is ignored on platforms other than Windows.
Use of the attribute however means that external data symbols do not
have a compile-time constant address (they are loaded using an
indirection). This means we have to adjust the rtsSyms initial linker
table so that it is a local constant in a function, rather than a global
constant. We now define it within a function that pre-populates the
symbol table with the RTS symbols.
- - - - -
2ad3e01e by Duncan Coutts at 2026-05-05T14:44:37-04:00
Fix the rts linker declarations for a few data symbols
and ensure that the (windows only) rts_IOManagerIsWin32Native data
symbol is marked as externally visible.
- - - - -
8ff4fdb5 by David Eichmann at 2026-05-05T14:44:37-04:00
Hadrian: Disable runtime pseudo relocations for RTS on windows hosts
- - - - -
96974723 by Teo Camarasu at 2026-05-05T14:45:20-04:00
ghci/TH: refactor to use IORef QState
This is a pure refactor and shouldn't modify semantics at all
- - - - -
eff6bfaf by Teo Camarasu at 2026-05-05T14:45:20-04:00
iserv: recover/getQ/putQ should behave same as internal interpreter
The internal and external interpreter should behave the same when
handling `recover`, the exeception recovery method of Q.
In practice, they diverge. In case of failure, the internal interpreter
only restores error message state to before the computation, wheras the
external interperter restores error message state *and* the state of putQ/getQ.
As far as I can tell this is a simple mistake in the implementation.
Note [TH recover with -fexternal-interpreter] describes the correct
behaviour but the implementation doesn't mirror this.
This change restores the correct behaviour by keeping the effects of
putQ in the erroring computation.
This is a breaking change since it modifies the behaviour of programs
that rely on recover ignoring putQ from failling computations when used
with the external interpreter. Although I highly doubt anyone relies on
this behaviour.
This divergence was first introduced in d00c308633fe7d216d31a1087e00e63532d87d6d.
As far as I can tell this was unintentional and tha commit was trying to solve a different bug.
Resolves #27022
- - - - -
c05637f1 by Wen Kokke at 2026-05-05T15:17:15-04:00
rts: Add dynamic trace flags API
This commit adds an API to the RTS (exposed via Rts.h) that allows users to dynamically change the trace flags.
Prior to this commit, users were able to stop and start the profiling and heap profiling timers (via startProfTimer/stopProfTimer and startHeapProfTimer/stopHeapProfTimer).
This extends that functionality to also cover the core event types.
The getTraceFlag/setTraceFlag functions read and write the values of the trace flag cache, which is allocated by Trace.c, rather than modifying the members of RtsFlags.TraceFlags.
This is done under the assumption that the members of RtsFlags should not be modified after RTS initialisation.
Consequently, if the user modifies the trace flags using setTraceFlag, the object returned by getTraceFlags (from base) will not reflect these changes.
The trace flags are not protected by locks of any sort.
Hence, these functions are not thread-safe.
However, the trace flags are not modified by the RTS after initialisation, only read, so the race conditions introduced by one user modifying them are most likely benign.
This PR also puts the trace flag cache in a single global struct, as opposed to a collection of global variables, and changes the types of the individual flags from uint8_t to bool, as these have the same size on both Clang and GCC and are a better semantic match.
Prior to the change to uint8_t, they had type int, see 42c47cd6.
Even with its deprecation in C23, I don't think there should be any issue depending on stdbool.h.
The TRACE_X macros are redefined to access the global struct, with values cast to const bool to ensure they are read-only.
- - - - -
f45af756 by Wen Kokke at 2026-05-05T15:17:15-04:00
rts: Ensure TRACE_X values are used in place of RtsFlags.TraceFlags.X
- - - - -
5a48b387 by Wen Kokke at 2026-05-05T15:17:15-04:00
rts: Fix nonmoving-GC tracing
The current nonmoving-GC tracing functions were written in a different
style from the other tracing functions. They were directly implemented
as, e.g., a traceConcMarkEnd function that called postConcMarkEnd.
The other tracing functions are implemented as, e.g., traceThreadLabel_,
a function that posts the thread label event, and traceThreadLabel, a
macro that checks whether TRACE_scheduler is set. This commit fixes that
implementation, and ensures that the nonmoving-GC tracing functions only
emit events if nonmoving-GC tracing is enabled.
- - - - -
e9d7c55f by Wen Kokke at 2026-05-05T15:17:15-04:00
rts: Add SymI_HasProto for get/setTraceFlag
- - - - -
a8e8a1c7 by Wen Kokke at 2026-05-05T15:17:15-04:00
rts: Add SymI_HasProto for start/endEventLogging
- - - - -
fabfdfec by Wen Kokke at 2026-05-05T15:17:15-04:00
rts: Add changelog entry
- - - - -
2a3b220b by Teo Camarasu at 2026-05-05T15:17:16-04:00
interface-stability/base: don't distinguish ws-32
The interface of base is identical when the Word size is 32bits.
Therefore, there is no need to have another file for this case.
So, we delete it.
Step towards: #26752
- - - - -
18 changed files:
- + changelog.d/T27022
- + changelog.d/dynamic-trace-flags
- hadrian/src/Settings/Packages.hs
- libraries/ghci/GHCi/TH.hs
- rts/IOManager.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/Trace.c
- rts/Trace.h
- rts/include/rts/EventLogWriter.h
- rts/linker/Elf.c
- rts/sm/NonMoving.c
- − testsuite/tests/interface-stability/base-exports.stdout-ws-32
- + testsuite/tests/th/T27022.hs
- + testsuite/tests/th/T27022.stdout
- testsuite/tests/th/all.T
Changes:
=====================================
changelog.d/T27022
=====================================
@@ -0,0 +1,11 @@
+section: compiler
+synopsis: Fix a divergence in the interaction between ``recover`` and ``putQ`` between the internal and external interpreter
+description: The ``recover`` method in TemplateHaskell now behaves the same
+ with the internal and external interpreter.
+ In the past, when an error was encountered in a computation in a ``recover`` block,
+ the external interpreter would discard any state changes from ``putQ``,
+ whereas the internal interpreter would not.
+ This was a long-standing error in the implementation of the external interpreter.
+ Both now keep state changes from ``putQ`` in ``recover`` blocks.
+mrs: !15994
+issues: #27022
=====================================
changelog.d/dynamic-trace-flags
=====================================
@@ -0,0 +1,10 @@
+section: compiler
+synopsis: Support dynamic trace flags in RTS
+issues: #27186
+mrs: !15936
+
+description: {
+ The RTS API now exposes the `RUNTIME_TRACE_FLAG` type and
+ the `getTraceFlags` and `setTraceFlags` functions that can be used to
+ change the trace flags at runtime.
+}
=====================================
hadrian/src/Settings/Packages.hs
=====================================
@@ -322,6 +322,7 @@ rtsPackageArgs = package rts ? do
, Profiling `wayUnit` way ? arg "-DPROFILING"
, Threaded `wayUnit` way ? arg "-DTHREADED_RTS"
, notM targetSupportsSMP ? arg "-optc-DNOSMP"
+ , isWinHost ? arg "-optl-Wl,--disable-runtime-pseudo-reloc"
-- See Note [AutoApply.cmm for vectors] in genapply/Main.hs
--
=====================================
libraries/ghci/GHCi/TH.hs
=====================================
@@ -119,7 +119,7 @@ initQState :: Pipe -> QState
initQState p = QState M.empty Nothing p
-- | The monad in which we run TH computations on the server
-newtype GHCiQ a = GHCiQ { runGHCiQ :: QState -> IO (a, QState) }
+newtype GHCiQ a = GHCiQ { runGHCiQ :: IORef QState -> IO a }
-- | The exception thrown by "fail" in the GHCiQ monad
data GHCiQException = GHCiQException QState String
@@ -128,52 +128,54 @@ data GHCiQException = GHCiQException QState String
instance Exception GHCiQException
instance Functor GHCiQ where
- fmap f (GHCiQ s) = GHCiQ $ fmap (\(x,s') -> (f x,s')) . s
+ fmap f (GHCiQ m) = GHCiQ $ fmap f . m
instance Applicative GHCiQ where
f <*> a = GHCiQ $ \s ->
- do (f',s') <- runGHCiQ f s
- (a',s'') <- runGHCiQ a s'
- return (f' a', s'')
- pure x = GHCiQ (\s -> return (x,s))
+ do f' <- runGHCiQ f s
+ a' <- runGHCiQ a s
+ return $ f' a'
+ pure x = GHCiQ $ \_ -> return x
instance Monad GHCiQ where
m >>= f = GHCiQ $ \s ->
- do (m', s') <- runGHCiQ m s
- (a, s'') <- runGHCiQ (f m') s'
- return (a, s'')
+ do m' <- runGHCiQ m s
+ a <- runGHCiQ (f m') s
+ return a
instance MonadFail GHCiQ where
- fail err = GHCiQ $ \s -> throwIO (GHCiQException s err)
+ fail err = GHCiQ $ \sRef -> readIORef sRef >>= \s -> throwIO (GHCiQException s err)
getState :: GHCiQ QState
-getState = GHCiQ $ \s -> return (s,s)
+getState = GHCiQ $ \sRef -> readIORef sRef
noLoc :: TH.Loc
noLoc = TH.Loc "<no file>" "<no package>" "<no module>" (0,0) (0,0)
-- | Send a 'THMessage' to GHC and return the result.
ghcCmd :: Binary a => THMessage (THResult a) -> GHCiQ a
-ghcCmd m = GHCiQ $ \s -> do
+ghcCmd m = GHCiQ $ \sRef -> do
+ s <- readIORef sRef
r <- remoteTHCall (qsPipe s) m
case r of
THException str -> throwIO (GHCiQException s str)
- THComplete res -> return (res, s)
+ THComplete res -> return res
instance MonadIO GHCiQ where
- liftIO m = GHCiQ $ \s -> fmap (,s) m
+ liftIO m = GHCiQ $ \_ -> m
instance TH.Quasi GHCiQ where
qNewName str = ghcCmd (NewName str)
qReport isError msg = ghcCmd (Report isError msg)
-- See Note [TH recover with -fexternal-interpreter] in GHC.Tc.Gen.Splice
- qRecover (GHCiQ h) a = GHCiQ $ \s -> mask $ \unmask -> do
+ qRecover (GHCiQ h) a = GHCiQ $ \sRef -> mask $ \unmask -> do
+ s <- readIORef sRef
remoteTHCall (qsPipe s) StartRecover
- e <- try $ unmask $ runGHCiQ (a <* ghcCmd FailIfErrs) s
+ e <- try $ unmask $ runGHCiQ (a <* ghcCmd FailIfErrs) sRef
remoteTHCall (qsPipe s) (EndRecover (isLeft e))
case e of
- Left GHCiQException{} -> h s
+ Left GHCiQException{} -> h sRef
Right r -> return r
qLookupName isType occ = ghcCmd (LookupName isType occ)
qReify name = ghcCmd (Reify name)
@@ -200,15 +202,16 @@ instance TH.Quasi GHCiQ where
qAddTempFile suffix = ghcCmd (AddTempFile suffix)
qAddTopDecls decls = ghcCmd (AddTopDecls decls)
qAddForeignFilePath lang fp = ghcCmd (AddForeignFilePath lang fp)
- qAddModFinalizer fin = GHCiQ (\s -> mkRemoteRef fin >>= return . (, s)) >>=
+ qAddModFinalizer fin = GHCiQ (\_ -> mkRemoteRef fin) >>=
ghcCmd . AddModFinalizer
qAddCorePlugin str = ghcCmd (AddCorePlugin str)
- qGetQ = GHCiQ $ \s ->
+ qGetQ = do
+ s <- getState
let lookup :: forall a. Typeable a => Map TypeRep Dynamic -> Maybe a
lookup m = fromDynamic =<< M.lookup (typeOf (undefined::a)) m
- in return (lookup (qsMap s), s)
- qPutQ k = GHCiQ $ \s ->
- return ((), s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
+ return $ lookup (qsMap s)
+ qPutQ k = GHCiQ $ \sRef ->
+ modifyIORef' sRef (\s -> s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
qIsExtEnabled x = ghcCmd (IsExtEnabled x)
qExtsEnabled = ghcCmd ExtsEnabled
qPutDoc l s = ghcCmd (PutDoc l s)
@@ -231,7 +234,8 @@ runModFinalizerRefs pipe rstate qrefs = do
qs <- mapM localRef qrefs
qstateref <- localRef rstate
qstate <- readIORef qstateref
- _ <- runGHCiQ (TH.runQ $ sequence_ qs) qstate { qsPipe = pipe }
+ qstate' <- newIORef $ qstate { qsPipe = pipe }
+ _ <- runGHCiQ (TH.runQ $ sequence_ qs) qstate'
return ()
-- | The implementation of the 'RunTH' message
@@ -267,8 +271,6 @@ runTHQ
-> IO ByteString
runTHQ pipe rstate mb_loc ghciq = do
qstateref <- localRef rstate
- qstate <- readIORef qstateref
- let st = qstate { qsLocation = mb_loc, qsPipe = pipe }
- (r,new_state) <- runGHCiQ (TH.runQ ghciq) st
- writeIORef qstateref new_state
+ modifyIORef' qstateref (\qstate -> qstate { qsLocation = mb_loc, qsPipe = pipe })
+ r <- runGHCiQ (TH.runQ ghciq) qstateref
return $! LB.toStrict (runPut (put r))
=====================================
rts/IOManager.h
=====================================
@@ -21,6 +21,15 @@
#include "sm/GC.h" // for evac_fn
+#if defined(mingw32_HOST_OS)
+/* Global var (only on Windows) that is exported (hence before BeginPrivate.h)
+ * to be shared with the I/O code in the base library to tell us which style
+ * of I/O manager we are using: one that uses the Windows native API HANDLEs,
+ * or one that uses Posix style fds.
+ */
+extern bool rts_IOManagerIsWin32Native;
+#endif
+
#include "BeginPrivate.h"
/* The ./configure gives us a set of CPP flags, one for each named I/O manager:
@@ -160,14 +169,6 @@ typedef enum {
/* Global var to tell us which I/O manager impl we are using */
extern IOManagerType iomgr_type;
-#if defined(mingw32_HOST_OS)
-/* Global var (only on Windows) that is exported to be shared with the I/O code
- * in the base library to tell us which style of I/O manager we are using: one
- * that uses the Windows native API HANDLEs, or one that uses Posix style fds.
- */
-extern bool rts_IOManagerIsWin32Native;
-#endif
-
/* The CapIOManager is the per-capability data structure belonging to the I/O
* manager. It is defined in full in IOManagerInternals.h. The opaque forward
=====================================
rts/Linker.c
=====================================
@@ -478,16 +478,7 @@ initLinker_ (int retain_cafs)
symhash = allocStrHashTable();
/* populate the symbol table with stuff from the RTS */
- IF_DEBUG(linker, debugBelch("populating linker symbol table with built-in RTS symbols\n"));
- for (const RtsSymbolVal *sym = rtsSyms; sym->lbl != NULL; sym++) {
- IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
- if (! ghciInsertSymbolTable(WSTR("(GHCi built-in symbols)"),
- symhash, sym->lbl, sym->addr,
- sym->strength, sym->type, 0, NULL)) {
- barf("ghciInsertSymbolTable failed");
- }
- }
- IF_DEBUG(linker, debugBelch("done with built-in RTS symbols\n"));
+ initLinkerRtsSyms(symhash);
/* Add extra symbols. rtsExtraSyms() is a weakly defined symbol in the rts,
* that can be overrided by linking in an object with a corresponding
=====================================
rts/LinkerInternals.h
=====================================
@@ -502,4 +502,6 @@ ObjectCode* mkOc( ObjectType type, pathchar *path, char *image, int imageSize,
void initSegment(Segment *s, void *start, size_t size, SegmentProt prot, int n_sections);
void freeSegments(ObjectCode *oc);
+void initLinkerRtsSyms(StrHashTable *symhash);
+
#include "EndPrivate.h"
=====================================
rts/RtsSymbols.c
=====================================
@@ -9,6 +9,8 @@
#include "ghcplatform.h"
#include "Rts.h"
#include "RtsSymbols.h"
+#include "LinkerInternals.h"
+#include "PathUtils.h"
#include "TopHandler.h"
#include "HsFFI.h"
@@ -51,6 +53,20 @@ extern char **environ;
/* -----------------------------------------------------------------------------
* Symbols to be inserted into the RTS symbol table.
+ *
+ * Note [Naming Scheme for Symbol Macros]
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ *
+ * SymI_*: symbol is internal to the RTS. It resides in an object
+ * file/library that is linked into the RTS library (as a static
+ * archive or dynamic shared library).
+ * SymE_*: symbol is external to the RTS library. It might be linked
+ * dynamically.
+ *
+ * Sym*_HasProto : the symbol prototype is imported in an include file
+ * or defined explicitly
+ * Sym*_NeedsProto: the symbol is undefined and we add a dummy
+ * default proto extern void sym(void);
*/
#define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
@@ -162,7 +178,7 @@ extern char **environ;
SymI_HasProto(stg_asyncWritezh) \
SymI_HasProto(stg_asyncDoProczh) \
SymI_HasProto(rts_InstallConsoleEvent) \
- SymI_HasProto(rts_IOManagerIsWin32Native) \
+ SymI_HasDataProto(rts_IOManagerIsWin32Native) \
SymI_HasProto(rts_ConsoleHandlerDone) \
SymI_NeedsProto(__mingw_module_is_dll) \
RTS_WIN64_ONLY(SymI_NeedsProto(___chkstk_ms)) \
@@ -524,7 +540,12 @@ extern char **environ;
SymI_HasProto(__word_encodeFloat) \
SymI_HasDataProto(stg_atomicallyzh) \
SymI_HasProto(barf) \
+ SymI_HasProto(startEventLogging) \
+ SymI_HasProto(endEventLogging) \
SymI_HasProto(flushEventLog) \
+ SymI_HasProto(flushEventLog) \
+ SymI_HasProto(getTraceFlag) \
+ SymI_HasProto(setTraceFlag) \
SymI_HasProto(deRefStablePtr) \
SymI_HasProto(debugBelch) \
SymI_HasProto(errorBelch) \
@@ -914,7 +935,7 @@ extern char **environ;
SymI_HasProto(freeExecPage) \
SymI_HasProto(getAllocations) \
SymI_HasProto(revertCAFs) \
- SymI_HasProto(RtsFlags) \
+ SymI_HasDataProto(RtsFlags) \
SymI_NeedsDataProto(rts_breakpoint_io_action) \
SymI_NeedsDataProto(rts_stop_next_breakpoint) \
SymI_NeedsDataProto(rts_stop_on_exception) \
@@ -925,9 +946,9 @@ extern char **environ;
SymI_NeedsProto(rts_enableStopAfterReturn) \
SymI_NeedsProto(rts_disableStopAfterReturn) \
SymI_HasProto(stopTimer) \
- SymI_HasProto(n_capabilities) \
- SymI_HasProto(max_n_capabilities) \
- SymI_HasProto(enabled_capabilities) \
+ SymI_HasDataProto(n_capabilities) \
+ SymI_HasDataProto(max_n_capabilities) \
+ SymI_HasDataProto(enabled_capabilities) \
SymI_HasDataProto(stg_traceEventzh) \
SymI_HasDataProto(stg_traceMarkerzh) \
SymI_HasDataProto(stg_traceBinaryEventzh) \
@@ -1145,12 +1166,27 @@ extern char **environ;
SymI_HasProto(hs_word2float64)
-/* entirely bogus claims about types of these symbols */
-#define SymI_NeedsProto(vvv) extern void vvv(void);
-#define SymI_NeedsDataProto(vvv) extern StgWord vvv[];
-#define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
-#define SymE_NeedsDataProto(vvv) SymI_NeedsDataProto(vvv);
-#define SymE_HasProto(vvv) SymI_HasProto(vvv);
+/* Declare prototypes for the symbols that need it, so we can refer
+ * to them in the rtsSyms table below.
+ *
+ * In particular, for the external ones (SymE_*) we use the dllimport attribute
+ * to indicate that (on Windows) they come from external DLLs. This attribute
+ * is ignored on other platforms.
+ *
+ * The claims about the types of these symbols are entirely bogus.
+ */
+#if defined(mingw32_HOST_OS) && defined(DYNAMIC)
+#define DLLIMPORT __attribute__((dllimport))
+#else
+#define DLLIMPORT /**/
+#endif
+
+#define SymI_NeedsProto(vvv) extern void vvv(void);
+#define SymI_NeedsDataProto(vvv) extern StgWord vvv[];
+#define SymE_NeedsProto(vvv) extern DLLIMPORT void vvv(void);
+#define SymE_NeedsDataProto(vvv) extern DLLIMPORT StgWord vvv[];
+
+#define SymE_HasProto(vvv) /**/
#define SymI_HasProto(vvv) /**/
#define SymI_HasDataProto(vvv) /**/
#define SymI_HasProto_redirect(vvv,xxx,strength,ty) /**/
@@ -1179,6 +1215,8 @@ RTS_SYMBOLS_PRIM
#undef SymE_NeedsProto
#undef SymE_NeedsDataProto
+/* See Note [Naming Scheme for Symbol Macros] */
+
#define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
(void*)(&(vvv)), STRENGTH_NORMAL, SYM_TYPE_CODE },
#define SymI_HasDataProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
@@ -1199,7 +1237,16 @@ RTS_SYMBOLS_PRIM
{ MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
(void*)(&(xxx)), strength, ty },
-RtsSymbolVal rtsSyms[] = {
+
+
+/* Initialize (if not already initialized) and return an array of symbols with stuff from the RTS. */
+void initLinkerRtsSyms (StrHashTable *symhash) {
+ /* The address of data symbols with the dllimport attribute are not
+ * compile-time constants and so cannot be used in constant initialisers.
+ * For this reason, rtsSyms is a local variable within this function
+ * rather than a global constant (as it was historically).
+ */
+ const RtsSymbolVal rtsSyms[] = {
RTS_SYMBOLS
RTS_RET_SYMBOLS
RTS_POSIX_ONLY_SYMBOLS
@@ -1214,7 +1261,20 @@ RtsSymbolVal rtsSyms[] = {
RTS_SYMBOLS_PRIM
SymI_HasDataProto(nonmoving_write_barrier_enabled)
{ 0, 0, STRENGTH_NORMAL, SYM_TYPE_CODE } /* sentinel */
-};
+ };
+
+ IF_DEBUG(linker, debugBelch("populating linker symbol table with built-in RTS symbols\n"));
+ for (const RtsSymbolVal *sym = rtsSyms; sym->lbl != NULL; sym++) {
+ IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
+ if (! ghciInsertSymbolTable(WSTR("(GHCi built-in symbols)"),
+ symhash, sym->lbl, sym->addr,
+ sym->strength, sym->type, 0, NULL)) {
+ barf("ghciInsertSymbolTable failed");
+ }
+ }
+ IF_DEBUG(linker, debugBelch("done with built-in RTS symbols\n"));
+}
+
// Note [Extra RTS symbols]
=====================================
rts/RtsSymbols.h
=====================================
@@ -46,8 +46,6 @@ typedef struct _RtsSymbolVal {
SymType type;
} RtsSymbolVal;
-extern RtsSymbolVal rtsSyms[];
-
extern RtsSymbolVal* __attribute__((weak)) rtsExtraSyms(void);
/* See Note [_iob_func symbol]. */
=====================================
rts/Trace.c
=====================================
@@ -29,14 +29,54 @@
#include <unistd.h>
#endif
-// events
-uint8_t TRACE_sched;
-uint8_t TRACE_gc;
-uint8_t TRACE_nonmoving_gc;
-uint8_t TRACE_spark_sampled;
-uint8_t TRACE_spark_full;
-uint8_t TRACE_user;
-uint8_t TRACE_cap;
+RUNTIME_TRACE_FLAG_CACHE RuntimeTraceFlagCache = {0};
+
+bool getTraceFlag(RUNTIME_TRACE_FLAG flag) {
+ switch (flag) {
+ case TRACE_SCHEDULER:
+ return RuntimeTraceFlagCache.scheduler;
+ case TRACE_GC:
+ return RuntimeTraceFlagCache.gc;
+ case TRACE_NONMOVING_GC:
+ return RuntimeTraceFlagCache.nonmoving_gc;
+ case TRACE_SPARK_SAMPLED:
+ return RuntimeTraceFlagCache.spark_sampled;
+ case TRACE_SPARK_FULL:
+ return RuntimeTraceFlagCache.spark_full;
+ case TRACE_USER:
+ return RuntimeTraceFlagCache.user;
+ case TRACE_CAP:
+ return RuntimeTraceFlagCache.cap;
+ default:
+ return false;
+ }
+}
+
+void setTraceFlag(RUNTIME_TRACE_FLAG flag, bool value) {
+ switch (flag) {
+ case TRACE_SCHEDULER:
+ RuntimeTraceFlagCache.scheduler = value;
+ break;
+ case TRACE_GC:
+ RuntimeTraceFlagCache.gc = value;
+ break;
+ case TRACE_NONMOVING_GC:
+ RuntimeTraceFlagCache.nonmoving_gc = value;
+ break;
+ case TRACE_SPARK_SAMPLED:
+ RuntimeTraceFlagCache.spark_sampled = value;
+ break;
+ case TRACE_SPARK_FULL:
+ RuntimeTraceFlagCache.spark_full = value;
+ break;
+ case TRACE_USER:
+ RuntimeTraceFlagCache.user = value;
+ break;
+ case TRACE_CAP:
+ RuntimeTraceFlagCache.cap = value;
+ break;
+ }
+}
#if defined(THREADED_RTS)
static Mutex trace_utx;
@@ -51,43 +91,41 @@ static void traceCap_stderr(Capability *cap, char *msg, ...);
--------------------------------------------------------------------------- */
/*
- * Update the TRACE_* globals. Must be called whenever RtsFlags.TraceFlags is
- * modified.
+ * Initialise the runtime trace flags from RtsFlags.TraceFlags.
*/
-static void updateTraceFlagCache (void)
-{
- // -Ds turns on scheduler tracing too
- TRACE_sched =
- RtsFlags.TraceFlags.scheduler ||
- RtsFlags.DebugFlags.scheduler;
-
- // -Dg turns on gc tracing too
- TRACE_gc =
- RtsFlags.TraceFlags.gc ||
- RtsFlags.DebugFlags.gc ||
- RtsFlags.DebugFlags.scheduler;
-
- TRACE_nonmoving_gc =
- RtsFlags.TraceFlags.nonmoving_gc;
-
- TRACE_spark_sampled =
- RtsFlags.TraceFlags.sparks_sampled;
-
- // -Dr turns on full spark tracing
- TRACE_spark_full =
- RtsFlags.TraceFlags.sparks_full ||
- RtsFlags.DebugFlags.sparks;
-
- TRACE_user =
- RtsFlags.TraceFlags.user;
-
- // We trace cap events if we're tracing anything else
- TRACE_cap =
- TRACE_sched ||
- TRACE_gc ||
- TRACE_spark_sampled ||
- TRACE_spark_full ||
- TRACE_user;
+static void updateTraceFlagCache(void) {
+ // -Ds turns on scheduler tracing too
+ RuntimeTraceFlagCache.scheduler =
+ RtsFlags.TraceFlags.scheduler ||
+ RtsFlags.DebugFlags.scheduler;
+
+ // -Dg turns on gc tracing too
+ RuntimeTraceFlagCache.gc =
+ RtsFlags.TraceFlags.gc ||
+ RtsFlags.DebugFlags.gc ||
+ RtsFlags.DebugFlags.scheduler;
+
+ RuntimeTraceFlagCache.nonmoving_gc =
+ RtsFlags.TraceFlags.nonmoving_gc;
+
+ RuntimeTraceFlagCache.spark_sampled =
+ RtsFlags.TraceFlags.sparks_sampled;
+
+ // -Dr turns on full spark tracing
+ RuntimeTraceFlagCache.spark_full =
+ RtsFlags.TraceFlags.sparks_full ||
+ RtsFlags.DebugFlags.sparks;
+
+ RuntimeTraceFlagCache.user =
+ RtsFlags.TraceFlags.user;
+
+ // We trace cap events if we're tracing anything else
+ RuntimeTraceFlagCache.cap =
+ TRACE_sched ||
+ TRACE_gc ||
+ TRACE_spark_sampled ||
+ TRACE_spark_full ||
+ TRACE_user;
}
void initTracing (void)
@@ -880,59 +918,65 @@ void traceThreadLabel_(Capability *cap,
}
}
-void traceConcMarkBegin(void)
+void traceNonmovingGcEvent_ (EventTypeNum tag)
{
- if (eventlog_enabled)
- postEventNoCap(EVENT_CONC_MARK_BEGIN);
+#if defined(DEBUG)
+ if (RtsFlags.TraceFlags.tracing == TRACE_STDERR) {
+ /* nothing - no string representation for nonmoving GC events */
+ } else
+#endif
+ {
+ /* currently most non-moving GC events are nullary events */
+ postEventNoCap(tag);
+ }
}
-void traceConcMarkEnd(StgWord32 marked_obj_count)
+void traceConcMarkEnd_(StgWord32 marked_obj_count)
{
- if (eventlog_enabled)
+#if defined(DEBUG)
+ if (RtsFlags.TraceFlags.tracing == TRACE_STDERR) {
+ /* nothing - no string representation for nonmoving GC events */
+ } else
+#endif
+ {
postConcMarkEnd(marked_obj_count);
+ }
}
-void traceConcSyncBegin(void)
-{
- if (eventlog_enabled)
- postEventNoCap(EVENT_CONC_SYNC_BEGIN);
-}
-
-void traceConcSyncEnd(void)
-{
- if (eventlog_enabled)
- postEventNoCap(EVENT_CONC_SYNC_END);
-}
-
-void traceConcSweepBegin(void)
-{
- if (eventlog_enabled)
- postEventNoCap(EVENT_CONC_SWEEP_BEGIN);
-}
-
-void traceConcSweepEnd(void)
-{
- if (eventlog_enabled)
- postEventNoCap(EVENT_CONC_SWEEP_END);
-}
-
-void traceConcUpdRemSetFlush(Capability *cap)
+void traceConcUpdRemSetFlush_(Capability *cap)
{
- if (eventlog_enabled)
+#if defined(DEBUG)
+ if (RtsFlags.TraceFlags.tracing == TRACE_STDERR) {
+ /* nothing - no string representation for nonmoving GC events */
+ } else
+#endif
+ {
postConcUpdRemSetFlush(cap);
+ }
}
-void traceNonmovingHeapCensus(uint16_t blk_size,
- const struct NonmovingAllocCensus *census)
+void traceNonmovingHeapCensus_(uint16_t blk_size, const struct NonmovingAllocCensus *census)
{
- if (eventlog_enabled && TRACE_nonmoving_gc)
+#if defined(DEBUG)
+ if (RtsFlags.TraceFlags.tracing == TRACE_STDERR) {
+ /* nothing - no string representation for nonmoving GC events */
+ } else
+#endif
+ {
postNonmovingHeapCensus(blk_size, census);
+ }
}
-void traceNonmovingPrunedSegments(uint32_t pruned_segments, uint32_t free_segments)
+void traceNonmovingPrunedSegments_(uint32_t pruned_segments, uint32_t free_segments)
{
- if (eventlog_enabled && TRACE_nonmoving_gc)
+#if defined(DEBUG)
+ if (RtsFlags.TraceFlags.tracing == TRACE_STDERR) {
+ /* nothing - no string representation for nonmoving GC events */
+ } else
+#endif
+ {
postNonmovingPrunedSegments(pruned_segments, free_segments);
+ }
}
void traceThreadStatus_ (StgTSO *tso USED_IF_DEBUG)
=====================================
rts/Trace.h
=====================================
@@ -70,16 +70,35 @@ enum CapsetType { CapsetTypeCustom = CAPSET_TYPE_CUSTOM,
#define DEBUG_continuation RtsFlags.DebugFlags.continuation
#define DEBUG_iomanager RtsFlags.DebugFlags.iomanager
-// Event-enabled flags
-// These semantically booleans but we use a dense packing to minimize their
-// cache impact.
-extern uint8_t TRACE_sched;
-extern uint8_t TRACE_gc;
-extern uint8_t TRACE_nonmoving_gc;
-extern uint8_t TRACE_spark_sampled;
-extern uint8_t TRACE_spark_full;
-extern uint8_t TRACE_cap;
-/* extern uint8_t TRACE_user; */ // only used in Trace.c
+// These trace flags are shorthand for the members of the RuntimeTraceFlagCache
+// struct. Within the RTS, these should be treated as read-only variables.
+#define TRACE_sched ((const bool)RuntimeTraceFlagCache.scheduler)
+#define TRACE_gc ((const bool)RuntimeTraceFlagCache.gc)
+#define TRACE_nonmoving_gc ((const bool)RuntimeTraceFlagCache.nonmoving_gc)
+#define TRACE_spark_sampled ((const bool)RuntimeTraceFlagCache.spark_sampled)
+#define TRACE_spark_full ((const bool)RuntimeTraceFlagCache.spark_full)
+#define TRACE_user ((const bool)RuntimeTraceFlagCache.user)
+#define TRACE_cap ((const bool)RuntimeTraceFlagCache.cap)
+
+/*
+ * Runtime trace flags.
+ */
+typedef struct {
+ bool scheduler;
+ bool gc;
+ bool nonmoving_gc;
+ bool spark_sampled;
+ bool spark_full;
+ bool user;
+ bool cap;
+} RUNTIME_TRACE_FLAG_CACHE;
+
+/*
+ * These flags should be used to determine whether or not some value should
+ * be traced at runtime, rather than the values in RtsFlags. These flags can
+ * be modified at runtime using setTraceFlag in `rts/EventLogWriter.h`.
+ */
+extern RUNTIME_TRACE_FLAG_CACHE RuntimeTraceFlagCache;
// -----------------------------------------------------------------------------
// Posting events
@@ -136,6 +155,52 @@ void traceGcEvent_ (Capability *cap, EventTypeNum tag);
void traceGcEventAtT_ (Capability *cap, StgWord64 ts, EventTypeNum tag);
+/*
+ * Record a nonmoving GC event.
+ */
+#define traceConcMarkBegin() \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingGcEvent_(EVENT_CONC_MARK_BEGIN); \
+ }
+#define traceConcMarkEnd(marked_obj_count) \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceConcMarkEnd_(marked_obj_count); \
+ }
+#define traceConcSyncBegin() \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingGcEvent_(EVENT_CONC_SYNC_BEGIN); \
+ }
+#define traceConcSyncEnd() \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingGcEvent_(EVENT_CONC_SYNC_END); \
+ }
+#define traceConcSweepBegin() \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingGcEvent_(EVENT_CONC_SWEEP_BEGIN); \
+ }
+#define traceConcSweepEnd() \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingGcEvent_(EVENT_CONC_SWEEP_END); \
+ }
+#define traceConcUpdRemSetFlush(cap) \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceConcUpdRemSetFlush_(cap); \
+ }
+#define traceNonmovingHeapCensus(blk_size, census) \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingHeapCensus_(blk_size, census); \
+ }
+#define traceNonmovingPrunedSegments(pruned_segments, free_segments) \
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc)) { \
+ traceNonmovingPrunedSegments_(pruned_segments, free_segments); \
+ }
+
+void traceNonmovingGcEvent_ (EventTypeNum tag);
+void traceConcMarkEnd_(StgWord32 marked_obj_count);
+void traceConcUpdRemSetFlush_(Capability *cap);
+void traceNonmovingHeapCensus_(uint16_t blk_size, const struct NonmovingAllocCensus *census);
+void traceNonmovingPrunedSegments_(uint32_t pruned_segments, uint32_t free_segments);
+
/*
* Record a heap event
*/
@@ -321,17 +386,6 @@ void traceProfSampleCostCentre(Capability *cap,
void traceProfBegin(void);
#endif /* PROFILING */
-void traceConcMarkBegin(void);
-void traceConcMarkEnd(StgWord32 marked_obj_count);
-void traceConcSyncBegin(void);
-void traceConcSyncEnd(void);
-void traceConcSweepBegin(void);
-void traceConcSweepEnd(void);
-void traceConcUpdRemSetFlush(Capability *cap);
-void traceNonmovingHeapCensus(uint16_t blk_size,
- const struct NonmovingAllocCensus *census);
-void traceNonmovingPrunedSegments(uint32_t pruned_segments, uint32_t free_segments);
-
void traceIPE(const InfoProvEnt *ipe);
void flushTrace(void);
@@ -384,6 +438,7 @@ void flushTrace(void);
#define traceConcSweepEnd() /* nothing */
#define traceConcUpdRemSetFlush(cap) /* nothing */
#define traceNonmovingHeapCensus(blk_size, census) /* nothing */
+#define traceNonmovingPrunedSegments(pruned_segments, free_segments) /* nothing */
#define flushTrace() /* nothing */
=====================================
rts/include/rts/EventLogWriter.h
=====================================
@@ -78,3 +78,34 @@ void endEventLogging(void);
* Flush the eventlog. cap can be NULL if one is not held.
*/
void flushEventLog(Capability **cap);
+
+/*
+ * An enumeration for the runtime trace flags.
+ */
+typedef enum {
+ TRACE_SCHEDULER,
+ TRACE_GC,
+ TRACE_NONMOVING_GC,
+ TRACE_SPARK_SAMPLED,
+ TRACE_SPARK_FULL,
+ TRACE_USER,
+ TRACE_CAP,
+} RUNTIME_TRACE_FLAG;
+
+/*
+ * Get the value of the given runtime trace flag.
+ *
+ * Warning: The trace flag cache is not thread-safe. After initialisation, the
+ * RTS never writes to these values, but concurrently using getTraceFlag and
+ * setTraceFlag for the same flag is a race condition.
+ */
+bool getTraceFlag(RUNTIME_TRACE_FLAG flag);
+
+/*
+ * Set the value of the given runtime trace flag.
+ *
+ * Warning: The trace flag cache is not thread-safe. After initialisation, the
+ * RTS never writes to these values. However, inconsistent reads may lead to
+ * incorrect tracing for a short time after setting a trace flag.
+ */
+void setTraceFlag(RUNTIME_TRACE_FLAG flag, bool value);
=====================================
rts/linker/Elf.c
=====================================
@@ -76,18 +76,6 @@
*
* See bug #781
* See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
- *
- * Naming Scheme for Symbol Macros
- *
- * SymI_*: symbol is internal to the RTS. It resides in an object
- * file/library that is statically.
- * SymE_*: symbol is external to the RTS library. It might be linked
- * dynamically.
- *
- * Sym*_HasProto : the symbol prototype is imported in an include file
- * or defined explicitly
- * Sym*_NeedsProto: the symbol is undefined and we add a dummy
- * default proto extern void sym(void);
*/
#define X86_64_ELF_NONPIC_HACK (!RtsFlags.MiscFlags.linkerAlwaysPic)
=====================================
rts/sm/NonMoving.c
=====================================
@@ -1339,7 +1339,7 @@ concurrent_marking:
nonmovingPrintAllocatorCensus(!concurrent);
#endif
#if defined(TRACING)
- if (RtsFlags.TraceFlags.nonmoving_gc)
+ if (RTS_UNLIKELY(TRACE_nonmoving_gc))
nonmovingTraceAllocatorCensus();
#endif
=====================================
testsuite/tests/interface-stability/base-exports.stdout-ws-32 deleted
=====================================
The diff for this file was not included because it is too large.
=====================================
testsuite/tests/th/T27022.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE TemplateHaskell #-}
+-- | This tests the behaviour of TH's recover method.
+-- It should behave the same in the internal and external interperter.
+-- In the past, they have diverged, and the external interpreter would roll back the state of putQ/getQ whereas the internal interpreter would not.
+module Main where
+
+import Language.Haskell.TH.Syntax
+main = print $(putQ "0" >> recover (pure ()) (putQ "42" >> fail "oops") >> getQ @String >>= lift )
=====================================
testsuite/tests/th/T27022.stdout
=====================================
@@ -0,0 +1 @@
+Just "42"
=====================================
testsuite/tests/th/all.T
=====================================
@@ -650,3 +650,4 @@ test('GadtConSigs_th_dump1', normal, compile, ['-v0 -ddump-splices -dsuppress-un
test('T26099', normal, compile_fail, [''])
test('T8306_th', only_ways(['ghci']), ghci_script, ['T8306_th.script'])
test('T26862_th', only_ways(['ghci']), ghci_script, ['T26862_th.script'])
+test('T27022', normal, compile_and_run, [''])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/bce22879b7d59320fbd3cbd2cb4918…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/bce22879b7d59320fbd3cbd2cb4918…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/sol/dont-use-global-variables] Don't use global variables to address concurrency bugs! (fixes #27234)
by Simon Hengel (@sol) 05 May '26
by Simon Hengel (@sol) 05 May '26
05 May '26
Simon Hengel pushed to branch wip/sol/dont-use-global-variables at Glasgow Haskell Compiler / GHC
Commits:
7d6e970a by Simon Hengel at 2026-05-06T01:55:17+07:00
Don't use global variables to address concurrency bugs! (fixes #27234)
This was originally introduce with
88f38b03025386f0f1e8f5861eed67d80495168a to address #17922.
In this specific case a better fix would have been to synchronize on
stderr:
withHandle_ "stderrSupportsAnsiColors" stderr $ \ _ -> do
...
But apparently the dependency on `terminfo` was removed in
32ab07bf3d6ce45e8ea5b55e8095174a6b42a7f0, preventing #17922 in the first
place.
- - - - -
4 changed files:
- + clean.sh
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/SysTools/Terminal.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
Changes:
=====================================
clean.sh
=====================================
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+
+set -o nounset
+set -o errexit
+
+dst=$(git describe --tags | sed s/-release//)
+
+rm -rf "$dst" "$dst.tar.gz"
+
+mkdir -p "$dst"
+find _build/stage1/ -name '*.hie' -print0 | xargs -0 cp --parents -t "$dst"
+
+rm -r "$dst/_build/stage1/utils/"
+rm -r "$dst/_build/stage1/ghc/"
+
+mv "$dst/_build/stage1/compiler/build" "$dst/ghc"
+
+find "$dst/_build/" -type d -name build | while read -r dir
+do
+ pkg=$(basename "$(dirname "$dir")")
+ mv "$dir" "$dst/$pkg"
+done
+
+rm -r "$dst/_build/"
+
+tar -czvf "$dst.tar.gz" "$dst"
+
+rm -rf "$dst"
=====================================
compiler/GHC/Driver/DynFlags.hs
=====================================
@@ -545,6 +545,7 @@ initDynFlags dflags = do
`catchIOError` \_ -> return False
ghcNoUnicodeEnv <- lookupEnv "GHC_NO_UNICODE"
let useUnicode' = isNothing ghcNoUnicodeEnv && canUseUnicode
+ canUseColor <- stderrSupportsAnsiColors
maybeGhcColorsEnv <- lookupEnv "GHC_COLORS"
maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"
let adjustCols (Just env) = Col.parseScheme env
@@ -556,9 +557,9 @@ initDynFlags dflags = do
return dflags{
useUnicode = useUnicode',
useColor = useColor',
- canUseColor = stderrSupportsAnsiColors,
+ canUseColor = canUseColor,
-- if the terminal supports color, we assume it supports links as well
- canUseErrorLinks = stderrSupportsAnsiColors,
+ canUseErrorLinks = canUseColor,
colScheme = colScheme',
tmpDir = TempDir tmp_dir
}
=====================================
compiler/GHC/SysTools/Terminal.hs
=====================================
@@ -14,17 +14,9 @@ import qualified Graphics.Win32 as Win32
import qualified System.Win32 as Win32
#endif
-import System.IO.Unsafe
-
--- | Does the controlling terminal support ANSI color sequences?
--- This memoized to avoid thread-safety issues in ncurses (see #17922).
-stderrSupportsAnsiColors :: Bool
-stderrSupportsAnsiColors = unsafePerformIO stderrSupportsAnsiColors'
-{-# NOINLINE stderrSupportsAnsiColors #-}
-
-- | Check if ANSI escape sequences can be used to control color in stderr.
-stderrSupportsAnsiColors' :: IO Bool
-stderrSupportsAnsiColors' = do
+stderrSupportsAnsiColors :: IO Bool
+stderrSupportsAnsiColors = do
#if !defined(mingw32_HOST_OS)
-- Equivalent of https://hackage.haskell.org/package/ansi-terminal/docs/System-Console-ANSI.…
isTerminal <- hIsTerminalDevice stderr
=====================================
libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
=====================================
@@ -143,8 +143,8 @@ original handle is always replaced.
{-# INLINE withHandle #-}
withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
-withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act
-withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act
+withHandle fun h@(FileHandle _ m) = withHandle' fun h m
+withHandle fun h@(DuplexHandle _ m _) = withHandle' fun h m
withHandle' :: String -> Handle -> MVar Handle__
-> (Handle__ -> IO (Handle__,a)) -> IO a
@@ -157,8 +157,8 @@ withHandle' fun h m act =
{-# INLINE withHandle_ #-}
withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
-withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act
-withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act
+withHandle_ fun h@(FileHandle _ m) = withHandle_' fun h m
+withHandle_ fun h@(DuplexHandle _ m _) = withHandle_' fun h m
withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a
withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/7d6e970a5905db346ef4851ed51e732…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/7d6e970a5905db346ef4851ed51e732…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][master] 2 commits: ghci/TH: refactor to use IORef QState
by Marge Bot (@marge-bot) 05 May '26
by Marge Bot (@marge-bot) 05 May '26
05 May '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
96974723 by Teo Camarasu at 2026-05-05T14:45:20-04:00
ghci/TH: refactor to use IORef QState
This is a pure refactor and shouldn't modify semantics at all
- - - - -
eff6bfaf by Teo Camarasu at 2026-05-05T14:45:20-04:00
iserv: recover/getQ/putQ should behave same as internal interpreter
The internal and external interpreter should behave the same when
handling `recover`, the exeception recovery method of Q.
In practice, they diverge. In case of failure, the internal interpreter
only restores error message state to before the computation, wheras the
external interperter restores error message state *and* the state of putQ/getQ.
As far as I can tell this is a simple mistake in the implementation.
Note [TH recover with -fexternal-interpreter] describes the correct
behaviour but the implementation doesn't mirror this.
This change restores the correct behaviour by keeping the effects of
putQ in the erroring computation.
This is a breaking change since it modifies the behaviour of programs
that rely on recover ignoring putQ from failling computations when used
with the external interpreter. Although I highly doubt anyone relies on
this behaviour.
This divergence was first introduced in d00c308633fe7d216d31a1087e00e63532d87d6d.
As far as I can tell this was unintentional and tha commit was trying to solve a different bug.
Resolves #27022
- - - - -
5 changed files:
- + changelog.d/T27022
- libraries/ghci/GHCi/TH.hs
- + testsuite/tests/th/T27022.hs
- + testsuite/tests/th/T27022.stdout
- testsuite/tests/th/all.T
Changes:
=====================================
changelog.d/T27022
=====================================
@@ -0,0 +1,11 @@
+section: compiler
+synopsis: Fix a divergence in the interaction between ``recover`` and ``putQ`` between the internal and external interpreter
+description: The ``recover`` method in TemplateHaskell now behaves the same
+ with the internal and external interpreter.
+ In the past, when an error was encountered in a computation in a ``recover`` block,
+ the external interpreter would discard any state changes from ``putQ``,
+ whereas the internal interpreter would not.
+ This was a long-standing error in the implementation of the external interpreter.
+ Both now keep state changes from ``putQ`` in ``recover`` blocks.
+mrs: !15994
+issues: #27022
=====================================
libraries/ghci/GHCi/TH.hs
=====================================
@@ -119,7 +119,7 @@ initQState :: Pipe -> QState
initQState p = QState M.empty Nothing p
-- | The monad in which we run TH computations on the server
-newtype GHCiQ a = GHCiQ { runGHCiQ :: QState -> IO (a, QState) }
+newtype GHCiQ a = GHCiQ { runGHCiQ :: IORef QState -> IO a }
-- | The exception thrown by "fail" in the GHCiQ monad
data GHCiQException = GHCiQException QState String
@@ -128,52 +128,54 @@ data GHCiQException = GHCiQException QState String
instance Exception GHCiQException
instance Functor GHCiQ where
- fmap f (GHCiQ s) = GHCiQ $ fmap (\(x,s') -> (f x,s')) . s
+ fmap f (GHCiQ m) = GHCiQ $ fmap f . m
instance Applicative GHCiQ where
f <*> a = GHCiQ $ \s ->
- do (f',s') <- runGHCiQ f s
- (a',s'') <- runGHCiQ a s'
- return (f' a', s'')
- pure x = GHCiQ (\s -> return (x,s))
+ do f' <- runGHCiQ f s
+ a' <- runGHCiQ a s
+ return $ f' a'
+ pure x = GHCiQ $ \_ -> return x
instance Monad GHCiQ where
m >>= f = GHCiQ $ \s ->
- do (m', s') <- runGHCiQ m s
- (a, s'') <- runGHCiQ (f m') s'
- return (a, s'')
+ do m' <- runGHCiQ m s
+ a <- runGHCiQ (f m') s
+ return a
instance MonadFail GHCiQ where
- fail err = GHCiQ $ \s -> throwIO (GHCiQException s err)
+ fail err = GHCiQ $ \sRef -> readIORef sRef >>= \s -> throwIO (GHCiQException s err)
getState :: GHCiQ QState
-getState = GHCiQ $ \s -> return (s,s)
+getState = GHCiQ $ \sRef -> readIORef sRef
noLoc :: TH.Loc
noLoc = TH.Loc "<no file>" "<no package>" "<no module>" (0,0) (0,0)
-- | Send a 'THMessage' to GHC and return the result.
ghcCmd :: Binary a => THMessage (THResult a) -> GHCiQ a
-ghcCmd m = GHCiQ $ \s -> do
+ghcCmd m = GHCiQ $ \sRef -> do
+ s <- readIORef sRef
r <- remoteTHCall (qsPipe s) m
case r of
THException str -> throwIO (GHCiQException s str)
- THComplete res -> return (res, s)
+ THComplete res -> return res
instance MonadIO GHCiQ where
- liftIO m = GHCiQ $ \s -> fmap (,s) m
+ liftIO m = GHCiQ $ \_ -> m
instance TH.Quasi GHCiQ where
qNewName str = ghcCmd (NewName str)
qReport isError msg = ghcCmd (Report isError msg)
-- See Note [TH recover with -fexternal-interpreter] in GHC.Tc.Gen.Splice
- qRecover (GHCiQ h) a = GHCiQ $ \s -> mask $ \unmask -> do
+ qRecover (GHCiQ h) a = GHCiQ $ \sRef -> mask $ \unmask -> do
+ s <- readIORef sRef
remoteTHCall (qsPipe s) StartRecover
- e <- try $ unmask $ runGHCiQ (a <* ghcCmd FailIfErrs) s
+ e <- try $ unmask $ runGHCiQ (a <* ghcCmd FailIfErrs) sRef
remoteTHCall (qsPipe s) (EndRecover (isLeft e))
case e of
- Left GHCiQException{} -> h s
+ Left GHCiQException{} -> h sRef
Right r -> return r
qLookupName isType occ = ghcCmd (LookupName isType occ)
qReify name = ghcCmd (Reify name)
@@ -200,15 +202,16 @@ instance TH.Quasi GHCiQ where
qAddTempFile suffix = ghcCmd (AddTempFile suffix)
qAddTopDecls decls = ghcCmd (AddTopDecls decls)
qAddForeignFilePath lang fp = ghcCmd (AddForeignFilePath lang fp)
- qAddModFinalizer fin = GHCiQ (\s -> mkRemoteRef fin >>= return . (, s)) >>=
+ qAddModFinalizer fin = GHCiQ (\_ -> mkRemoteRef fin) >>=
ghcCmd . AddModFinalizer
qAddCorePlugin str = ghcCmd (AddCorePlugin str)
- qGetQ = GHCiQ $ \s ->
+ qGetQ = do
+ s <- getState
let lookup :: forall a. Typeable a => Map TypeRep Dynamic -> Maybe a
lookup m = fromDynamic =<< M.lookup (typeOf (undefined::a)) m
- in return (lookup (qsMap s), s)
- qPutQ k = GHCiQ $ \s ->
- return ((), s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
+ return $ lookup (qsMap s)
+ qPutQ k = GHCiQ $ \sRef ->
+ modifyIORef' sRef (\s -> s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
qIsExtEnabled x = ghcCmd (IsExtEnabled x)
qExtsEnabled = ghcCmd ExtsEnabled
qPutDoc l s = ghcCmd (PutDoc l s)
@@ -231,7 +234,8 @@ runModFinalizerRefs pipe rstate qrefs = do
qs <- mapM localRef qrefs
qstateref <- localRef rstate
qstate <- readIORef qstateref
- _ <- runGHCiQ (TH.runQ $ sequence_ qs) qstate { qsPipe = pipe }
+ qstate' <- newIORef $ qstate { qsPipe = pipe }
+ _ <- runGHCiQ (TH.runQ $ sequence_ qs) qstate'
return ()
-- | The implementation of the 'RunTH' message
@@ -267,8 +271,6 @@ runTHQ
-> IO ByteString
runTHQ pipe rstate mb_loc ghciq = do
qstateref <- localRef rstate
- qstate <- readIORef qstateref
- let st = qstate { qsLocation = mb_loc, qsPipe = pipe }
- (r,new_state) <- runGHCiQ (TH.runQ ghciq) st
- writeIORef qstateref new_state
+ modifyIORef' qstateref (\qstate -> qstate { qsLocation = mb_loc, qsPipe = pipe })
+ r <- runGHCiQ (TH.runQ ghciq) qstateref
return $! LB.toStrict (runPut (put r))
=====================================
testsuite/tests/th/T27022.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE TemplateHaskell #-}
+-- | This tests the behaviour of TH's recover method.
+-- It should behave the same in the internal and external interperter.
+-- In the past, they have diverged, and the external interpreter would roll back the state of putQ/getQ whereas the internal interpreter would not.
+module Main where
+
+import Language.Haskell.TH.Syntax
+main = print $(putQ "0" >> recover (pure ()) (putQ "42" >> fail "oops") >> getQ @String >>= lift )
=====================================
testsuite/tests/th/T27022.stdout
=====================================
@@ -0,0 +1 @@
+Just "42"
=====================================
testsuite/tests/th/all.T
=====================================
@@ -650,3 +650,4 @@ test('GadtConSigs_th_dump1', normal, compile, ['-v0 -ddump-splices -dsuppress-un
test('T26099', normal, compile_fail, [''])
test('T8306_th', only_ways(['ghci']), ghci_script, ['T8306_th.script'])
test('T26862_th', only_ways(['ghci']), ghci_script, ['T26862_th.script'])
+test('T27022', normal, compile_and_run, [''])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/8ff4fdb545703fba98b2b860b1b47d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/8ff4fdb545703fba98b2b860b1b47d…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][master] 3 commits: Use __attribute__((dllimport)) for external RTS symbol declarations
by Marge Bot (@marge-bot) 05 May '26
by Marge Bot (@marge-bot) 05 May '26
05 May '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
9a9ae4df by Duncan Coutts at 2026-05-05T14:44:37-04:00
Use __attribute__((dllimport)) for external RTS symbol declarations
This is needed to be hygenic about DLL symbol imports and exports.
The attribute is ignored on platforms other than Windows.
Use of the attribute however means that external data symbols do not
have a compile-time constant address (they are loaded using an
indirection). This means we have to adjust the rtsSyms initial linker
table so that it is a local constant in a function, rather than a global
constant. We now define it within a function that pre-populates the
symbol table with the RTS symbols.
- - - - -
2ad3e01e by Duncan Coutts at 2026-05-05T14:44:37-04:00
Fix the rts linker declarations for a few data symbols
and ensure that the (windows only) rts_IOManagerIsWin32Native data
symbol is marked as externally visible.
- - - - -
8ff4fdb5 by David Eichmann at 2026-05-05T14:44:37-04:00
Hadrian: Disable runtime pseudo relocations for RTS on windows hosts
- - - - -
7 changed files:
- hadrian/src/Settings/Packages.hs
- rts/IOManager.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/linker/Elf.c
Changes:
=====================================
hadrian/src/Settings/Packages.hs
=====================================
@@ -322,6 +322,7 @@ rtsPackageArgs = package rts ? do
, Profiling `wayUnit` way ? arg "-DPROFILING"
, Threaded `wayUnit` way ? arg "-DTHREADED_RTS"
, notM targetSupportsSMP ? arg "-optc-DNOSMP"
+ , isWinHost ? arg "-optl-Wl,--disable-runtime-pseudo-reloc"
-- See Note [AutoApply.cmm for vectors] in genapply/Main.hs
--
=====================================
rts/IOManager.h
=====================================
@@ -21,6 +21,15 @@
#include "sm/GC.h" // for evac_fn
+#if defined(mingw32_HOST_OS)
+/* Global var (only on Windows) that is exported (hence before BeginPrivate.h)
+ * to be shared with the I/O code in the base library to tell us which style
+ * of I/O manager we are using: one that uses the Windows native API HANDLEs,
+ * or one that uses Posix style fds.
+ */
+extern bool rts_IOManagerIsWin32Native;
+#endif
+
#include "BeginPrivate.h"
/* The ./configure gives us a set of CPP flags, one for each named I/O manager:
@@ -160,14 +169,6 @@ typedef enum {
/* Global var to tell us which I/O manager impl we are using */
extern IOManagerType iomgr_type;
-#if defined(mingw32_HOST_OS)
-/* Global var (only on Windows) that is exported to be shared with the I/O code
- * in the base library to tell us which style of I/O manager we are using: one
- * that uses the Windows native API HANDLEs, or one that uses Posix style fds.
- */
-extern bool rts_IOManagerIsWin32Native;
-#endif
-
/* The CapIOManager is the per-capability data structure belonging to the I/O
* manager. It is defined in full in IOManagerInternals.h. The opaque forward
=====================================
rts/Linker.c
=====================================
@@ -478,16 +478,7 @@ initLinker_ (int retain_cafs)
symhash = allocStrHashTable();
/* populate the symbol table with stuff from the RTS */
- IF_DEBUG(linker, debugBelch("populating linker symbol table with built-in RTS symbols\n"));
- for (const RtsSymbolVal *sym = rtsSyms; sym->lbl != NULL; sym++) {
- IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
- if (! ghciInsertSymbolTable(WSTR("(GHCi built-in symbols)"),
- symhash, sym->lbl, sym->addr,
- sym->strength, sym->type, 0, NULL)) {
- barf("ghciInsertSymbolTable failed");
- }
- }
- IF_DEBUG(linker, debugBelch("done with built-in RTS symbols\n"));
+ initLinkerRtsSyms(symhash);
/* Add extra symbols. rtsExtraSyms() is a weakly defined symbol in the rts,
* that can be overrided by linking in an object with a corresponding
=====================================
rts/LinkerInternals.h
=====================================
@@ -502,4 +502,6 @@ ObjectCode* mkOc( ObjectType type, pathchar *path, char *image, int imageSize,
void initSegment(Segment *s, void *start, size_t size, SegmentProt prot, int n_sections);
void freeSegments(ObjectCode *oc);
+void initLinkerRtsSyms(StrHashTable *symhash);
+
#include "EndPrivate.h"
=====================================
rts/RtsSymbols.c
=====================================
@@ -9,6 +9,8 @@
#include "ghcplatform.h"
#include "Rts.h"
#include "RtsSymbols.h"
+#include "LinkerInternals.h"
+#include "PathUtils.h"
#include "TopHandler.h"
#include "HsFFI.h"
@@ -51,6 +53,20 @@ extern char **environ;
/* -----------------------------------------------------------------------------
* Symbols to be inserted into the RTS symbol table.
+ *
+ * Note [Naming Scheme for Symbol Macros]
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ *
+ * SymI_*: symbol is internal to the RTS. It resides in an object
+ * file/library that is linked into the RTS library (as a static
+ * archive or dynamic shared library).
+ * SymE_*: symbol is external to the RTS library. It might be linked
+ * dynamically.
+ *
+ * Sym*_HasProto : the symbol prototype is imported in an include file
+ * or defined explicitly
+ * Sym*_NeedsProto: the symbol is undefined and we add a dummy
+ * default proto extern void sym(void);
*/
#define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
@@ -162,7 +178,7 @@ extern char **environ;
SymI_HasProto(stg_asyncWritezh) \
SymI_HasProto(stg_asyncDoProczh) \
SymI_HasProto(rts_InstallConsoleEvent) \
- SymI_HasProto(rts_IOManagerIsWin32Native) \
+ SymI_HasDataProto(rts_IOManagerIsWin32Native) \
SymI_HasProto(rts_ConsoleHandlerDone) \
SymI_NeedsProto(__mingw_module_is_dll) \
RTS_WIN64_ONLY(SymI_NeedsProto(___chkstk_ms)) \
@@ -914,7 +930,7 @@ extern char **environ;
SymI_HasProto(freeExecPage) \
SymI_HasProto(getAllocations) \
SymI_HasProto(revertCAFs) \
- SymI_HasProto(RtsFlags) \
+ SymI_HasDataProto(RtsFlags) \
SymI_NeedsDataProto(rts_breakpoint_io_action) \
SymI_NeedsDataProto(rts_stop_next_breakpoint) \
SymI_NeedsDataProto(rts_stop_on_exception) \
@@ -925,9 +941,9 @@ extern char **environ;
SymI_NeedsProto(rts_enableStopAfterReturn) \
SymI_NeedsProto(rts_disableStopAfterReturn) \
SymI_HasProto(stopTimer) \
- SymI_HasProto(n_capabilities) \
- SymI_HasProto(max_n_capabilities) \
- SymI_HasProto(enabled_capabilities) \
+ SymI_HasDataProto(n_capabilities) \
+ SymI_HasDataProto(max_n_capabilities) \
+ SymI_HasDataProto(enabled_capabilities) \
SymI_HasDataProto(stg_traceEventzh) \
SymI_HasDataProto(stg_traceMarkerzh) \
SymI_HasDataProto(stg_traceBinaryEventzh) \
@@ -1145,12 +1161,27 @@ extern char **environ;
SymI_HasProto(hs_word2float64)
-/* entirely bogus claims about types of these symbols */
-#define SymI_NeedsProto(vvv) extern void vvv(void);
-#define SymI_NeedsDataProto(vvv) extern StgWord vvv[];
-#define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
-#define SymE_NeedsDataProto(vvv) SymI_NeedsDataProto(vvv);
-#define SymE_HasProto(vvv) SymI_HasProto(vvv);
+/* Declare prototypes for the symbols that need it, so we can refer
+ * to them in the rtsSyms table below.
+ *
+ * In particular, for the external ones (SymE_*) we use the dllimport attribute
+ * to indicate that (on Windows) they come from external DLLs. This attribute
+ * is ignored on other platforms.
+ *
+ * The claims about the types of these symbols are entirely bogus.
+ */
+#if defined(mingw32_HOST_OS) && defined(DYNAMIC)
+#define DLLIMPORT __attribute__((dllimport))
+#else
+#define DLLIMPORT /**/
+#endif
+
+#define SymI_NeedsProto(vvv) extern void vvv(void);
+#define SymI_NeedsDataProto(vvv) extern StgWord vvv[];
+#define SymE_NeedsProto(vvv) extern DLLIMPORT void vvv(void);
+#define SymE_NeedsDataProto(vvv) extern DLLIMPORT StgWord vvv[];
+
+#define SymE_HasProto(vvv) /**/
#define SymI_HasProto(vvv) /**/
#define SymI_HasDataProto(vvv) /**/
#define SymI_HasProto_redirect(vvv,xxx,strength,ty) /**/
@@ -1179,6 +1210,8 @@ RTS_SYMBOLS_PRIM
#undef SymE_NeedsProto
#undef SymE_NeedsDataProto
+/* See Note [Naming Scheme for Symbol Macros] */
+
#define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
(void*)(&(vvv)), STRENGTH_NORMAL, SYM_TYPE_CODE },
#define SymI_HasDataProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
@@ -1199,7 +1232,16 @@ RTS_SYMBOLS_PRIM
{ MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
(void*)(&(xxx)), strength, ty },
-RtsSymbolVal rtsSyms[] = {
+
+
+/* Initialize (if not already initialized) and return an array of symbols with stuff from the RTS. */
+void initLinkerRtsSyms (StrHashTable *symhash) {
+ /* The address of data symbols with the dllimport attribute are not
+ * compile-time constants and so cannot be used in constant initialisers.
+ * For this reason, rtsSyms is a local variable within this function
+ * rather than a global constant (as it was historically).
+ */
+ const RtsSymbolVal rtsSyms[] = {
RTS_SYMBOLS
RTS_RET_SYMBOLS
RTS_POSIX_ONLY_SYMBOLS
@@ -1214,7 +1256,20 @@ RtsSymbolVal rtsSyms[] = {
RTS_SYMBOLS_PRIM
SymI_HasDataProto(nonmoving_write_barrier_enabled)
{ 0, 0, STRENGTH_NORMAL, SYM_TYPE_CODE } /* sentinel */
-};
+ };
+
+ IF_DEBUG(linker, debugBelch("populating linker symbol table with built-in RTS symbols\n"));
+ for (const RtsSymbolVal *sym = rtsSyms; sym->lbl != NULL; sym++) {
+ IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
+ if (! ghciInsertSymbolTable(WSTR("(GHCi built-in symbols)"),
+ symhash, sym->lbl, sym->addr,
+ sym->strength, sym->type, 0, NULL)) {
+ barf("ghciInsertSymbolTable failed");
+ }
+ }
+ IF_DEBUG(linker, debugBelch("done with built-in RTS symbols\n"));
+}
+
// Note [Extra RTS symbols]
=====================================
rts/RtsSymbols.h
=====================================
@@ -46,8 +46,6 @@ typedef struct _RtsSymbolVal {
SymType type;
} RtsSymbolVal;
-extern RtsSymbolVal rtsSyms[];
-
extern RtsSymbolVal* __attribute__((weak)) rtsExtraSyms(void);
/* See Note [_iob_func symbol]. */
=====================================
rts/linker/Elf.c
=====================================
@@ -76,18 +76,6 @@
*
* See bug #781
* See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
- *
- * Naming Scheme for Symbol Macros
- *
- * SymI_*: symbol is internal to the RTS. It resides in an object
- * file/library that is statically.
- * SymE_*: symbol is external to the RTS library. It might be linked
- * dynamically.
- *
- * Sym*_HasProto : the symbol prototype is imported in an include file
- * or defined explicitly
- * Sym*_NeedsProto: the symbol is undefined and we add a dummy
- * default proto extern void sym(void);
*/
#define X86_64_ELF_NONPIC_HACK (!RtsFlags.MiscFlags.linkerAlwaysPic)
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3b75cccdd3fd27b1d2544f729ed62d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3b75cccdd3fd27b1d2544f729ed62d…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/spj-reinstallable-base2] 11 commits: fixup krep fixes
by Rodrigo Mesquita (@alt-romes) 05 May '26
by Rodrigo Mesquita (@alt-romes) 05 May '26
05 May '26
Rodrigo Mesquita pushed to branch wip/spj-reinstallable-base2 at Glasgow Haskell Compiler / GHC
Commits:
9c334c51 by Rodrigo Mesquita at 2026-05-05T16:09:19+01:00
fixup krep fixes
TODO GET BACK
- - - - -
5f335b6e by Rodrigo Mesquita at 2026-05-05T16:09:25+01:00
Revert "fixup krep fixes"
This reverts commit 0c3177e9ecfdd9444df3439744996d599cb64c9b.
TODO GET BACK
- - - - -
9462a047 by Rodrigo Mesquita at 2026-05-05T16:09:28+01:00
Revert "krepStar, krepStarArrStar, etc..."
This reverts commit a47d441c70e2650cd7c6a4d466ec57c311ebe329.
TODO TODO TODO.
Thinking a bit more about this. get back later.
- - - - -
bf30dcb3 by Rodrigo Mesquita at 2026-05-05T16:27:07+01:00
emptyCallStack
- - - - -
f6e3662f by Rodrigo Mesquita at 2026-05-05T16:31:30+01:00
misc fixes to build
- - - - -
7f109c42 by Rodrigo Mesquita at 2026-05-05T16:55:20+01:00
callStackTyConKey, exceptionContextTyConKey, emptyExceptionContextName
- - - - -
d26b5b42 by Rodrigo Mesquita at 2026-05-05T17:10:49+01:00
errorMessageTypeErrorFamName, typeErrorTextDataConName, typeErrorAppendDataConName, typeErrorVAppendDataConName, typeErrorShowTypeDataConName
- - - - -
b7ce4338 by Rodrigo Mesquita at 2026-05-05T17:31:44+01:00
staticPtrTyConName, staticPtrDataConName, staticPtrInfoDataConName
- - - - -
7adf8b47 by Rodrigo Mesquita at 2026-05-05T17:31:44+01:00
-jsvalTyConName
- - - - -
e354bdae by Rodrigo Mesquita at 2026-05-05T17:31:44+01:00
knownNatClassName, knownSymbolClassName, knownCharClassName
- - - - -
a207cbcf by Rodrigo Mesquita at 2026-05-05T17:33:22+01:00
unsafeUnpackJSStringUtf8##
- - - - -
20 changed files:
- compiler/GHC/Builtin/KnownKeys.hs
- compiler/GHC/Builtin/KnownOccs.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Driver/Config/Tidy.hs
- compiler/GHC/Stg/BcPrep.hs
- compiler/GHC/StgToJS/Apply.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/Instance/Class.hs
- compiler/GHC/Tc/Instance/Typeable.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/Dict.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/Types/Constraint.hs
- ghc/GHCi/UI.hs
- libraries/base/src/GHC/Essentials.hs
- libraries/ghc-internal/src/GHC/Internal/Exception/Context.hs
- libraries/ghc-internal/src/GHC/Internal/Exception/Context.hs-boot
- libraries/ghc-internal/src/GHC/Internal/JS/Prim.hs
- libraries/ghc-internal/src/GHC/Internal/Stack/Types.hs
- libraries/ghc-internal/src/GHC/Internal/Types.hs
Changes:
=====================================
compiler/GHC/Builtin/KnownKeys.hs
=====================================
@@ -253,10 +253,26 @@ knownKeyTable
-- Implicit Params
, (mkTcOcc "IP", ipClassKey)
+ -- Callstacks
+ , (mkVarOcc "CallStack", callStackTyConKey)
+
+ -- Exception context
+ , (mkVarOcc "ExceptionContext", exceptionContextTyConKey)
+
+ -- Custom type errors
+ , (mkTcOcc "TypeError", errorMessageTypeErrorFamKey)
+ , (mkDataOcc "Text", typeErrorTextDataConKey)
+ , (mkDataOcc ":<>:", typeErrorAppendDataConKey)
+ , (mkDataOcc ":$$:", typeErrorVAppendDataConKey)
+ , (mkDataOcc "ShowType", typeErrorShowTypeDataConKey)
+
-- Base strings Strings
, (mkVarOcc "unpackCString#", unpackCStringIdKey)
, (mkVarOcc "unpackCStringUtf8#", unpackCStringUtf8IdKey)
+ -- JS primitives
+ , (mkVarOcc "unsafeUnpackJSStringUtf8##", unsafeUnpackJSStringUtf8ShShKey)
+
-- Known-key names that have BuiltinRules in ConstantFold
, (mkVarOcc "unpackFoldrCString#", unpackCStringFoldrIdKey)
, (mkVarOcc "unpackFoldrCStringUtf8#", unpackCStringFoldrUtf8IdKey)
@@ -343,42 +359,22 @@ knownKeyTable
basicKnownKeyNames :: [Name] -- See Note [Known-key names]
basicKnownKeyNames
= [
+ -- KindReps for common cases
+ starKindRepName,
+ starArrStarKindRepName,
+ starArrStarArrStarKindRepName,
+ constraintKindRepName,
-- FFI primitive types that are not wired-in.
ptrTyConName, funPtrTyConName, constPtrConName,
int8TyConName, int16TyConName, int32TyConName, int64TyConName,
word8TyConName, word16TyConName, word32TyConName, word64TyConName,
- jsvalTyConName,
-
- -- Type-level naturals
- knownNatClassName, knownSymbolClassName, knownCharClassName,
-
- -- ExceptionContext
- exceptionContextTyConName,
- emptyExceptionContextName,
-
- -- Call Stacks
- callStackTyConName,
- emptyCallStackName,
-- Plugins
pluginTyConName
, frontendPluginTyConName
- -- StaticPtr
- , staticPtrTyConName
- , staticPtrDataConName, staticPtrInfoDataConName
-
- -- Custom type errors
- , errorMessageTypeErrorFamName
- , typeErrorTextDataConName
- , typeErrorAppendDataConName
- , typeErrorVAppendDataConName
- , typeErrorShowTypeDataConName
-
-- Unsafe coercion proofs
, unsafeCoercePrimName
-
- , unsafeUnpackJSStringUtf8ShShName
]
@@ -425,33 +421,21 @@ bniVarQual str key = varQual gHC_INTERNAL_NUM_INTEGER (fsLit str) key
-- End of ghc-bignum
---------------------------------
+
+-- Class Typeable, and functions for constructing `Typeable` dictionaries
+starKindRepName, starArrStarKindRepName,
+ starArrStarArrStarKindRepName, constraintKindRepName :: Name
+-- This is the Typeable 'Module' for GHC.Prim (which has no code, so we place in GHC.Types)
+-- See Note [Grand plan for Typeable] in GHC.Tc.Instance.Typeable.
+starKindRepName = varQual gHC_TYPES (fsLit "krep$*") starKindRepKey
+starArrStarKindRepName = varQual gHC_TYPES (fsLit "krep$*Arr*") starArrStarKindRepKey
+starArrStarArrStarKindRepName = varQual gHC_TYPES (fsLit "krep$*->*->*") starArrStarArrStarKindRepKey
+constraintKindRepName = varQual gHC_TYPES (fsLit "krep$Constraint") constraintKindRepKey
+
-- WithDict
withDictClassName :: Name
withDictClassName = clsQual gHC_MAGIC_DICT (fsLit "WithDict") withDictClassKey
--- Custom type errors
-errorMessageTypeErrorFamName
- , typeErrorTextDataConName
- , typeErrorAppendDataConName
- , typeErrorVAppendDataConName
- , typeErrorShowTypeDataConName
- :: Name
-
-errorMessageTypeErrorFamName =
- tcQual gHC_INTERNAL_TYPEERROR (fsLit "TypeError") errorMessageTypeErrorFamKey
-
-typeErrorTextDataConName =
- dcQual gHC_INTERNAL_TYPEERROR (fsLit "Text") typeErrorTextDataConKey
-
-typeErrorAppendDataConName =
- dcQual gHC_INTERNAL_TYPEERROR (fsLit ":<>:") typeErrorAppendDataConKey
-
-typeErrorVAppendDataConName =
- dcQual gHC_INTERNAL_TYPEERROR (fsLit ":$$:") typeErrorVAppendDataConKey
-
-typeErrorShowTypeDataConName =
- dcQual gHC_INTERNAL_TYPEERROR (fsLit "ShowType") typeErrorShowTypeDataConKey
-
-- Unsafe coercion proofs
unsafeCoercePrimName:: Name
unsafeCoercePrimName = varQual gHC_INTERNAL_UNSAFE_COERCE (fsLit "unsafeCoerce#") unsafeCoercePrimIdKey
@@ -478,28 +462,6 @@ ptrTyConName, funPtrTyConName :: Name
ptrTyConName = tcQual gHC_INTERNAL_PTR (fsLit "Ptr") ptrTyConKey
funPtrTyConName = tcQual gHC_INTERNAL_PTR (fsLit "FunPtr") funPtrTyConKey
--- Type-level naturals
-knownNatClassName :: Name
-knownNatClassName = clsQual gHC_INTERNAL_TYPENATS (fsLit "KnownNat") knownNatClassKey
-knownSymbolClassName :: Name
-knownSymbolClassName = clsQual gHC_INTERNAL_TYPELITS (fsLit "KnownSymbol") knownSymbolClassKey
-knownCharClassName :: Name
-knownCharClassName = clsQual gHC_INTERNAL_TYPELITS (fsLit "KnownChar") knownCharClassKey
-
--- ExceptionContext
-exceptionContextTyConName, emptyExceptionContextName :: Name
-exceptionContextTyConName =
- tcQual gHC_INTERNAL_EXCEPTION_CONTEXT (fsLit "ExceptionContext") exceptionContextTyConKey
-emptyExceptionContextName
- = varQual gHC_INTERNAL_EXCEPTION_CONTEXT (fsLit "emptyExceptionContext") emptyExceptionContextKey
-
--- Source Locations
-callStackTyConName, emptyCallStackName :: Name
-callStackTyConName
- = tcQual gHC_INTERNAL_STACK_TYPES (fsLit "CallStack") callStackTyConKey
-emptyCallStackName
- = varQual gHC_INTERNAL_STACK_TYPES (fsLit "emptyCallStack") emptyCallStackKey
-
-- plugins
pLUGINS :: Module
pLUGINS = mkThisGhcModule (fsLit "GHC.Driver.Plugins")
@@ -508,31 +470,10 @@ pluginTyConName = tcQual pLUGINS (fsLit "Plugin") pluginTyConKey
frontendPluginTyConName :: Name
frontendPluginTyConName = tcQual pLUGINS (fsLit "FrontendPlugin") frontendPluginTyConKey
-staticPtrInfoTyConName :: Name
-staticPtrInfoTyConName =
- tcQual gHC_INTERNAL_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoTyConKey
-
-staticPtrInfoDataConName :: Name
-staticPtrInfoDataConName =
- dcQual gHC_INTERNAL_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoDataConKey
-
-staticPtrTyConName :: Name
-staticPtrTyConName =
- tcQual gHC_INTERNAL_STATICPTR (fsLit "StaticPtr") staticPtrTyConKey
-
-staticPtrDataConName :: Name
-staticPtrDataConName =
- dcQual gHC_INTERNAL_STATICPTR (fsLit "StaticPtr") staticPtrDataConKey
-
constPtrConName :: Name
constPtrConName =
tcQual gHC_INTERNAL_FOREIGN_C_CONSTPTR (fsLit "ConstPtr") constPtrTyConKey
-jsvalTyConName :: Name
-jsvalTyConName = tcQual gHC_INTERNAL_WASM_PRIM_TYPES (fsLit "JSVal") jsvalTyConKey
-
-unsafeUnpackJSStringUtf8ShShName :: Name
-unsafeUnpackJSStringUtf8ShShName = varQual gHC_INTERNAL_JS_PRIM (fsLit "unsafeUnpackJSStringUtf8##") unsafeUnpackJSStringUtf8ShShKey
{-
************************************************************************
@@ -871,12 +812,6 @@ specTyConKey = mkPreludeTyConUnique 185
smallArrayPrimTyConKey = mkPreludeTyConUnique 187
smallMutableArrayPrimTyConKey = mkPreludeTyConUnique 188
-staticPtrTyConKey :: KnownKey
-staticPtrTyConKey = mkPreludeTyConUnique 189
-
-staticPtrInfoTyConKey :: KnownKey
-staticPtrInfoTyConKey = mkPreludeTyConUnique 190
-
callStackTyConKey :: KnownKey
callStackTyConKey = mkPreludeTyConUnique 191
@@ -1344,6 +1279,13 @@ typeCharTypeRepKey = mkPreludeMiscIdUnique 509
typeRepIdKey = mkPreludeMiscIdUnique 510
mkTrFunKey = mkPreludeMiscIdUnique 511
+-- KindReps for common cases
+starKindRepKey, starArrStarKindRepKey, starArrStarArrStarKindRepKey, constraintKindRepKey :: KnownKey
+starKindRepKey = mkPreludeMiscIdUnique 520
+starArrStarKindRepKey = mkPreludeMiscIdUnique 521
+starArrStarArrStarKindRepKey = mkPreludeMiscIdUnique 522
+constraintKindRepKey = mkPreludeMiscIdUnique 523
+
-- Dynamic
toDynIdKey :: KnownKey
toDynIdKey = mkPreludeMiscIdUnique 530
@@ -1362,18 +1304,12 @@ memptyClassOpKey = mkPreludeMiscIdUnique 555
mappendClassOpKey = mkPreludeMiscIdUnique 556
mconcatClassOpKey = mkPreludeMiscIdUnique 557
-emptyCallStackKey :: KnownKey
-emptyCallStackKey = mkPreludeMiscIdUnique 558
-
fromStaticPtrClassOpKey :: KnownKey
fromStaticPtrClassOpKey = mkPreludeMiscIdUnique 560
makeStaticKey :: KnownKey
makeStaticKey = mkPreludeMiscIdUnique 561
-emptyExceptionContextKey :: KnownKey
-emptyExceptionContextKey = mkPreludeMiscIdUnique 562
-
-- Unsafe coercion proofs
unsafeEqualityProofIdKey, unsafeCoercePrimIdKey :: KnownKey
unsafeEqualityProofIdKey = mkPreludeMiscIdUnique 570
=====================================
compiler/GHC/Builtin/KnownOccs.hs
=====================================
@@ -204,6 +204,16 @@ fromStaticPtrClassOpOcc, newStablePtrIdOcc :: KnownOcc
fromStaticPtrClassOpOcc = mkVarOcc "fromStaticPtr"
newStablePtrIdOcc = mkVarOcc "newStablePtr"
+staticPtrTyConOcc, staticPtrDataConOcc, staticPtrInfoDataConOcc :: KnownOcc
+staticPtrTyConOcc = mkTcOcc "StaticPtr"
+staticPtrDataConOcc = mkDataOcc "StaticPtr"
+staticPtrInfoDataConOcc = mkDataOcc "StaticPtrInfo"
+
+knownNatClassOcc, knownSymbolClassOcc, knownCharClassOcc :: KnownOcc
+knownNatClassOcc = mkTcOcc "KnownNat"
+knownSymbolClassOcc = mkTcOcc "KnownSymbol"
+knownCharClassOcc = mkTcOcc "KnownChar"
+
returnIOIdOcc, bindIOIdOcc, thenIOIdOcc,
printIdOcc, ioTyConOcc, ioDataConOcc :: KnownOcc
returnIOIdOcc = mkVarOcc "returnIO"
@@ -321,15 +331,6 @@ traceIdOcc = mkVarOcc "trace"
assertErrorIdOcc :: KnownOcc
assertErrorIdOcc = mkVarOcc "assertError"
--- KindReps for common cases
--- See Note [Grand plan for Typeable] (GPT6) in GHC.Tc.Instance.Typeable.
-starKindRepIdOcc, starArrStarKindRepIdOcc,
- starArrStarArrStarKindRepIdOcc, constraintKindRepIdOcc :: KnownOcc
-starKindRepIdOcc = mkVarOcc "krepStar"
-starArrStarKindRepIdOcc = mkVarOcc "krepArrStar"
-starArrStarArrStarKindRepIdOcc = mkVarOcc "krepStarArrStarArrStarKind"
-constraintKindRepIdOcc = mkVarOcc "krepConstraint"
-
-- ghci
ghciIoClassOcc, ghciStepIoMOcc :: KnownOcc
ghciIoClassOcc = mkTcOcc "GHCiSandboxIO"
@@ -340,9 +341,14 @@ toAnnotationWrapperIdOcc :: KnownOcc
toAnnotationWrapperIdOcc = mkVarOcc "toAnnotationWrapper"
-- CallStacks/Source locations
-pushCallStackIdOcc, srcLocDataConOcc :: KnownOcc
-pushCallStackIdOcc = mkVarOcc "pushCallStack"
-srcLocDataConOcc = mkDataOcc "SrcLoc"
+emptyCallStackIdOcc, pushCallStackIdOcc, srcLocDataConOcc :: KnownOcc
+emptyCallStackIdOcc = mkVarOcc "emptyCallStack"
+pushCallStackIdOcc = mkVarOcc "pushCallStack"
+srcLocDataConOcc = mkDataOcc "SrcLoc"
+
+-- ExceptionContext
+emptyExceptionContextIdOcc :: KnownOcc
+emptyExceptionContextIdOcc = mkVarOcc "emptyExceptionContext"
{- *********************************************************************
* *
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -244,7 +244,7 @@ import {-# SOURCE #-} GHC.Builtin.WiredIn.Types
, manyDataConTy, oneDataConTy
, liftedRepTy, unliftedRepTy, zeroBitRepTy )
-import GHC.Types.Name( Name )
+import GHC.Types.Name( Name, hasKnownKey )
import GHC.Builtin.KnownKeys
import GHC.Core.Coercion.Axiom
@@ -1226,21 +1226,21 @@ pprUserTypeErrorTy ty =
-- Text "Something"
Just (tc,[txt])
- | tyConName tc == typeErrorTextDataConName
+ | tc `hasKnownKey` typeErrorTextDataConKey
, Just str <- isStrLitTy txt -> ftext str
-- ShowType t
Just (tc,[_k,t])
- | tyConName tc == typeErrorShowTypeDataConName -> ppr t
+ | tc `hasKnownKey` typeErrorShowTypeDataConKey -> ppr t
-- t1 :<>: t2
Just (tc,[t1,t2])
- | tyConName tc == typeErrorAppendDataConName ->
+ | tc `hasKnownKey` typeErrorAppendDataConKey ->
pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2
-- t1 :$$: t2
Just (tc,[t1,t2])
- | tyConName tc == typeErrorVAppendDataConName ->
+ | tc `hasKnownKey` typeErrorVAppendDataConKey ->
pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2
-- An unevaluated type function
=====================================
compiler/GHC/Driver/Config/Tidy.hs
=====================================
@@ -17,7 +17,7 @@ import GHC.Driver.Backend
import GHC.Core.Make (getMkStringIds)
import GHC.Builtin.KnownKeys
-import GHC.Tc.Utils.Env (lookupGlobal, lookupKnownKeyGlobal)
+import GHC.Tc.Utils.Env (lookupKnownKeyGlobal)
import GHC.Types.TyThing
import GHC.Platform.Ways
@@ -48,8 +48,8 @@ initStaticPtrOpts hsc_env = do
let dflags = hsc_dflags hsc_env
mk_string <- getMkStringIds (fmap tyThingId . lookupKnownKeyGlobal hsc_env)
- static_ptr_info_datacon <- tyThingDataCon <$> lookupGlobal hsc_env staticPtrInfoDataConName
- static_ptr_datacon <- tyThingDataCon <$> lookupGlobal hsc_env staticPtrDataConName
+ static_ptr_info_datacon <- tyThingDataCon <$> lookupKnownKeyGlobal hsc_env staticPtrInfoDataConKey
+ static_ptr_datacon <- tyThingDataCon <$> lookupKnownKeyGlobal hsc_env staticPtrDataConKey
pure $ StaticPtrOpts
{ opt_platform = targetPlatform dflags
=====================================
compiler/GHC/Stg/BcPrep.hs
=====================================
@@ -14,7 +14,6 @@ module GHC.Stg.BcPrep ( bcPrep ) where
import GHC.Prelude
-import GHC.Types.Id.Make
import GHC.Types.Id
import GHC.Core.Type
=====================================
compiler/GHC/StgToJS/Apply.hs
=====================================
@@ -111,7 +111,7 @@ genApp ctx i args
-- We detect if the Id is unsafeUnpackJSStringUtf8## applied to a string literal,
-- if so then we convert the unsafeUnpack to a call to h$decode.
| [StgVarArg v] <- args
- , idName i == unsafeUnpackJSStringUtf8ShShName
+ , i `hasKnownKey` unsafeUnpackJSStringUtf8ShShKey
-- See: https://gitlab.haskell.org/ghc/ghc/-/merge_requests/10588
-- Comment by Josh Meredith <josh.meredith(a)iohk.io>
-- `typex_expr` can throw an error for certain bindings so it's important
@@ -122,7 +122,7 @@ genApp ctx i args
-- Test case T23479
| [StgLitArg (LitString bs)] <- args
, Just d <- decodeModifiedUTF8 bs
- , idName i == unsafeUnpackJSStringUtf8ShShName
+ , i `hasKnownKey` unsafeUnpackJSStringUtf8ShShKey
, [top] <- concatMap typex_expr (ctxTarget ctx)
= return . (,ExprInline) $ top |= toJExpr d
=====================================
compiler/GHC/Tc/Gen/Expr.hs
=====================================
@@ -629,7 +629,7 @@ tcExpr (HsStatic _ expr) res_ty
-- StaticPtr a -> p a
; fromStaticPtr <- newKnownOccMethod StaticOrigin
fromStaticPtrClassOpOcc [p_ty]
- ; static_ptr_ty_con <- tcLookupTyCon staticPtrTyConName
+ ; static_ptr_ty_con <- tcLookupKnownOccTyCon staticPtrTyConOcc
; let wrap = mkWpEvVarApps [typeable_ev] <.> mkWpTyApps [expr_ty]
static_expr_ty = mkTyConApp static_ptr_ty_con [expr_ty]
; return $ mkHsWrapCo co $
=====================================
compiler/GHC/Tc/Instance/Class.hs
=====================================
@@ -27,12 +27,13 @@ import GHC.Rename.Env( addUsedGRE, addUsedDataCons, DeprecationWarnings (..) )
import GHC.Builtin.WiredIn.Types
import GHC.Builtin.WiredIn.Prim
import GHC.Builtin.KnownKeys
+import GHC.Builtin.KnownOccs
import GHC.Builtin.PrimOps ( PrimOp(..) )
import GHC.Builtin.PrimOps.Ids ( primOpId )
import GHC.Types.FieldLabel
import GHC.Types.SafeHaskell
-import GHC.Types.Name ( Name )
+import GHC.Types.Name ( Name, KnownOcc )
import GHC.Types.Name.Reader
import GHC.Types.Var.Env ( VarEnv )
import GHC.Types.Id
@@ -960,9 +961,9 @@ matchTypeable clas [k,t] -- clas = Typeable
-- see Note [No Typeable for polytypes or qualified types]
-- Now cases that do work
- | k `eqType` naturalTy = doTyLit knownNatClassName t
- | k `eqType` typeSymbolKind = doTyLit knownSymbolClassName t
- | k `eqType` charTy = doTyLit knownCharClassName t
+ | k `eqType` naturalTy = doTyLit knownNatClassOcc t
+ | k `eqType` typeSymbolKind = doTyLit knownSymbolClassOcc t
+ | k `eqType` charTy = doTyLit knownCharClassOcc t
| Just (tc, ks) <- splitTyConApp_maybe t -- See Note [Typeable (T a b c)]
, onlyNamedBndrsApplied tc ks = doTyConApp clas t tc ks
@@ -1038,8 +1039,8 @@ mk_typeable_pred clas ty = mkClassPred clas [ typeKind ty, ty ]
-- Typeable is implied by KnownNat/KnownSymbol. In the case of a type literal
-- we generate a sub-goal for the appropriate class.
-- See Note [Typeable for Nat and Symbol]
-doTyLit :: Name -> Type -> TcM ClsInstResult
-doTyLit kc t = do { kc_clas <- tcLookupClass kc
+doTyLit :: KnownOcc -> Type -> TcM ClsInstResult
+doTyLit kc t = do { kc_clas <- tcLookupKnownOccClass kc
; let kc_pred = mkClassPred kc_clas [ t ]
mk_ev [ev] = evTypeable t $ EvTypeableTyLit (EvExpr ev)
mk_ev _ = panic "doTyLit"
=====================================
compiler/GHC/Tc/Instance/Typeable.hs
=====================================
@@ -22,6 +22,7 @@ import GHC.Tc.Utils.TcType
import GHC.Iface.Env( newGlobalBinder )
import GHC.Builtin.Modules( gHC_TYPES, gHC_PRIM )
+import GHC.Builtin.KnownKeys
import GHC.Builtin.KnownOccs
import GHC.Builtin.WiredIn.Prim ( primTyCons )
import GHC.Builtin.WiredIn.Types
@@ -136,15 +137,6 @@ There are many wrinkles:
KindReps once in GHC.Types. These are referred to as "built-in"
KindReps below.
- * When compiling GHC.Internal.Types, generate some extra bindings for
- built-in kindreps (see `todoForExportedKindReps`):
-
- krepStar = MkTyCon app ...
-
- * Re-export `krepStar` from GHC.Essentials.
- * In `mkTypeableBinds`, use `krepStar` directly rather than using its
- long form. Must use lookupKnownOcc to find it.
-
(GPT7) Even though KindReps aren't inlined, this scheme still has more of an
effect on compilation time than I'd like. This is especially true in
the case of families of type constructors (e.g. tuples and unboxed
@@ -471,12 +463,11 @@ todoForTyCons mod mod_id tycons = do
mod_fpr = fingerprintString $ moduleNameString $ moduleName mod
pkg_fpr = fingerprintString $ unitString $ moduleUnit mod
-todoForExportedKindReps :: [(Kind, KnownOcc)] -> TcM TypeRepTodo
+todoForExportedKindReps :: [(Kind, Name)] -> TcM TypeRepTodo
todoForExportedKindReps kinds = do
trKindRepTy <- mkTyConTy <$> tcLookupKnownOccTyCon kindRepTyConOcc
- names <- mapM (fmap idName . tcLookupKnownOccId . snd) kinds -- ROMES:TODO: ugh... I don't see how this would work. These bindings are defined dynamically here when compiling this module, so how would knownOcc find them? they aren't defined!
- let mkId k name = (k, mkExportedVanillaId name trKindRepTy)
- return $ ExportedKindRepsTodo $ zipWith mkId (map fst kinds) names
+ let mkId (k, name) = (k, mkExportedVanillaId name trKindRepTy)
+ return $ ExportedKindRepsTodo $ map mkId kinds
-- | Generate TyCon bindings for a set of type constructors
mkTypeRepTodoBinds :: [TypeRepTodo] -> TcM TcGblEnv
@@ -671,13 +662,13 @@ liftTc = KindRepM . lift
-- | We generate `KindRep`s for a few common kinds, so that they
-- can be reused across modules.
--- These definitions are generated in `GHC.Internal.Types`.
-builtInKindReps :: [(Kind, KnownOcc)]
+-- These definitions are generated in `ghc-prim:GHC.Types`.
+builtInKindReps :: [(Kind, Name)]
builtInKindReps =
- [ (star, starKindRepIdOcc)
- , (constraintKind, constraintKindRepIdOcc)
- , (mkVisFunTyMany star star, starArrStarKindRepIdOcc)
- , (mkVisFunTysMany [star, star] star, starArrStarArrStarKindRepIdOcc)
+ [ (star, starKindRepName)
+ , (constraintKind, constraintKindRepName)
+ , (mkVisFunTyMany star star, starArrStarKindRepName)
+ , (mkVisFunTysMany [star, star] star, starArrStarArrStarKindRepName)
]
where
star = liftedTypeKind
@@ -686,7 +677,7 @@ initialKindRepEnv :: TcRn KindRepEnv
initialKindRepEnv = foldlM add_kind_rep emptyTypeMap builtInKindReps
where
add_kind_rep acc (k,n) = do
- id <- tcLookupKnownOccId n
+ id <- tcLookupId n
return $! extendTypeMap acc k (id, Nothing)
-- The TypeMap looks through type synonyms
=====================================
compiler/GHC/Tc/Solver/Default.hs
=====================================
@@ -40,9 +40,10 @@ import GHC.Types.Unique.Set
import GHC.Types.Id
import GHC.Builtin
+import GHC.Builtin.KnownOccs ( emptyExceptionContextIdOcc )
import GHC.Builtin.KnownKeys( unsatisfiableIdKey
, isStringClassKey
- , emptyExceptionContextName )
+ )
import GHC.Builtin.Modules ( gHC_INTERNAL_TYPEERROR )
import GHC.Builtin.WiredIn.Types
import GHC.Builtin.WiredIn.Ids ( unboxedUnitExpr )
@@ -449,7 +450,7 @@ defaultExceptionContext ct
| ClassPred cls tys <- classifyPredType (ctPred ct)
, isJust (isExceptionContextPred cls tys)
= do { warnTcS $ TcRnDefaultedExceptionContext (ctLoc ct)
- ; empty_ec_id <- wrapTcS (TcM.tcLookupId emptyExceptionContextName)
+ ; empty_ec_id <- wrapTcS (TcM.tcLookupKnownOccId emptyExceptionContextIdOcc)
; let ev = ctEvidence ct
ev_tm = EvExpr (evWrapIPE (ctEvPred ev) (Var empty_ec_id))
; setDictIfWanted ev EvCanonical ev_tm
=====================================
compiler/GHC/Tc/Solver/Dict.hs
=====================================
@@ -45,8 +45,7 @@ import GHC.Types.Var.Set
import GHC.Types.Var.Env
import GHC.Types.SrcLoc
-import GHC.Builtin.KnownOccs( pushCallStackIdOcc, srcLocDataConOcc )
-import GHC.Builtin.KnownKeys( emptyCallStackName )
+import GHC.Builtin.KnownOccs( emptyCallStackIdOcc, pushCallStackIdOcc, srcLocDataConOcc )
import GHC.Utils.Monad ( concatMapM )
import GHC.Utils.Outputable
@@ -187,7 +186,7 @@ solveCallStack ev ev_cs
evCallStack :: TcPredType -> EvCallStack -> TcS EvExpr
-- See Note [Overview of implicit CallStacks] in GHC.Tc.Types.Evidence
evCallStack _ EvCsEmpty
- = Var <$> wrapTcS (tcLookupId emptyCallStackName)
+ = Var <$> wrapTcS (tcLookupKnownOccId emptyCallStackIdOcc)
evCallStack pred (EvCsPushCall fs loc tm)
= do { df <- getDynFlags
; m <- getModule
=====================================
compiler/GHC/Tc/Solver/Monad.hs
=====================================
@@ -136,7 +136,7 @@ import qualified GHC.Tc.Utils.Monad as TcM
import qualified GHC.Tc.Utils.TcMType as TcM
import qualified GHC.Tc.Instance.Class as TcM( matchGlobalInst, ClsInstResult(..) )
import qualified GHC.Tc.Utils.Env as TcM
- ( tcGetDefaultTys, tcLookupKnownKeyId, tcLookupTyCon )
+ ( tcGetDefaultTys, tcLookupKnownKeyId, tcLookupKnownKeyTyCon )
import GHC.Tc.Zonk.Monad ( ZonkM )
import qualified GHC.Tc.Zonk.TcType as TcM
@@ -159,7 +159,7 @@ import GHC.Tc.Types.Origin
import GHC.Tc.Types.CtLoc
import GHC.Tc.Types.Constraint
-import GHC.Builtin.KnownKeys ( callStackTyConName, exceptionContextTyConName )
+import GHC.Builtin.KnownKeys ( callStackTyConKey, exceptionContextTyConKey )
import GHC.Core.Make
import GHC.Core.Type
@@ -569,8 +569,8 @@ updSolvedDicts :: InstanceWhat -> DictCt -> TcS ()
updSolvedDicts what dict_ct@(DictCt { di_cls = cls, di_tys = tys, di_ev = ev })
| isWanted ev
, instanceReturnsDictCon what
- = do { is_callstack <- is_tyConTy isCallStackTy callStackTyConName
- ; is_exceptionCtx <- is_tyConTy isExceptionContextTy exceptionContextTyConName
+ = do { is_callstack <- is_tyConTy isCallStackTy callStackTyConKey
+ ; is_exceptionCtx <- is_tyConTy isExceptionContextTy exceptionContextTyConKey
; let contains_callstack_or_exceptionCtx =
mightMentionIP
(const True)
@@ -593,9 +593,9 @@ updSolvedDicts what dict_ct@(DictCt { di_cls = cls, di_tys = tys, di_ev = ev })
-- per Note [Using typesAreApart when calling mightMentionIP].
--
-- See Note [Using isCallStackTy in mightMentionIP].
- is_tyConTy :: (Type -> Bool) -> Name -> TcS (Type -> Bool)
- is_tyConTy is_eq tc_name
- = do { (mb_tc, _) <- wrapTcS $ TcM.tryTc $ TcM.tcLookupTyCon tc_name
+ is_tyConTy :: (Type -> Bool) -> KnownKey -> TcS (Type -> Bool)
+ is_tyConTy is_eq tc_key
+ = do { (mb_tc, _) <- wrapTcS $ TcM.tryTc $ TcM.tcLookupKnownKeyTyCon tc_key
; case mb_tc of
Just tc ->
return $ \ ty -> not (typesAreApart ty (mkTyConTy tc))
=====================================
compiler/GHC/Tc/Types/Constraint.hs
=====================================
@@ -1426,7 +1426,7 @@ userTypeError_maybe look_everywhere = go
| Just ty' <- coreView ty
= go ty'
go (TyConApp tc tys)
- | tyConName tc == errorMessageTypeErrorFamName
+ | tc `hasKnownKey` errorMessageTypeErrorFamKey
, _kind : msg : _ <- tys
-- There may be more than 2 arguments, if the type error is
-- used as a type constructor (e.g. at kind `Type -> Type`).
=====================================
ghc/GHCi/UI.hs
=====================================
@@ -78,9 +78,8 @@ import GHC.Types.SourceError ( SourceError, initSourceErrorContext )
import GHC.Types.Name
import GHC.Types.Var ( varType )
import GHC.Iface.Syntax ( showToHeader )
-import GHC.Builtin.KnownKeys( ghciStepIoMName )
-import GHC.Builtin.KnownOccs( ioTyConOcc, stringTyCon_RDR, compose_RDR )
-import GHC.Types.Name.Reader as RdrName ( getGRE_NameQualifier_maybes, getRdrName, greName, globalRdrEnvElts)
+import GHC.Builtin.KnownOccs( ghciStepIoMOcc, ioTyConOcc, stringTyCon_RDR, compose_RDR )
+import GHC.Types.Name.Reader as RdrName
import GHC.Types.SrcLoc as SrcLoc
import qualified GHC.Parser.Lexer as Lexer
import GHC.Parser.Header ( toArgs )
@@ -2011,7 +2010,7 @@ defineMacro overwrite s
let stringTy :: LHsType GhcPs
stringTy = nlHsTyVar NotPromoted stringTyCon_RDR
ioM :: LHsType GhcPs -- AZ
- ioM = nlHsTyVar NotPromoted (ExactOcc ioTyConOcc) `nlHsAppTy` stringTy
+ ioM = nlHsTyVar NotPromoted (Exact (ExactOcc ioTyConOcc)) `nlHsAppTy` stringTy
body = nlHsVar compose_RDR `mkHsApp` (nlHsPar step)
`mkHsApp` (nlHsPar expr)
tySig = mkHsWildCardBndrs $ noLocA $ mkHsImplicitSigType $
@@ -2081,8 +2080,8 @@ getGhciStepIO = do
ghciTyConName <- GHC.getGHCiMonad
let stringTy = nlHsTyVar NotPromoted stringTyCon_RDR
ghciM = nlHsTyVar NotPromoted (Exact ghciTyConName) `nlHsAppTy` stringTy
- ioM = nlHsTyVar NotPromoted (ExactOcc ioTyConOcc) `nlHsAppTy` stringTy
- body = nlHsVar (getRdrName ghciStepIoMName)
+ ioM = nlHsTyVar NotPromoted (Exact (ExactOcc ioTyConOcc)) `nlHsAppTy` stringTy
+ body = nlHsVar (Exact (ExactOcc ghciStepIoMOcc))
tySig = mkHsWildCardBndrs $ noLocA $ mkHsImplicitSigType $
nlHsFunTy ghciM ioM
return $ noLocA $ ExprWithTySig noAnn body tySig
=====================================
libraries/base/src/GHC/Essentials.hs
=====================================
@@ -126,11 +126,19 @@ module GHC.Essentials
-- WithDict
, WithDict
+ -- Type-level naturals/symbols/chars
+ , KnownNat, KnownSymbol, KnownChar
+
+ -- Custom type errors
+ , TypeError
+ , ErrorMessage(..)
+
-- Unsatisfiable
, Unsatisfiable, unsatisfiable
-- Static pointers
, IsStatic( fromStaticPtr ), makeStatic
+ , StaticPtr( StaticPtr ), StaticPtrInfo( StaticPtrInfo )
-- Stable pointers
, StablePtr, newStablePtr
@@ -149,6 +157,9 @@ module GHC.Essentials
, CS.unpackAppendCStringUtf8#, CS.cstringLength#
, eqString, inline
+ -- JS primitives
+ , unsafeUnpackJSStringUtf8##
+
, UnsafeEquality( UnsafeRefl ), unsafeEqualityProof
-- Typeable and type representations
@@ -216,16 +227,16 @@ module GHC.Essentials
, Body, normalB, guardedB
, Guard, normalGE, patGE
- -- See Note [Grand plan for Typeable] point (GPT6)
- , krepStar, krepArrStar
- , krepStarArrStarArrStarKind
- , krepConstraint
-
-- GHCi
, GHCiSandboxIO(ghciStepIO)
-- Callstacks
- , pushCallStack, SrcLoc(..)
+ , CallStack, emptyCallStack, pushCallStack, SrcLoc(..)
+
+ -- Exception context
+ , ExceptionContext, emptyExceptionContext
+
+ , toAnnotationWrapper
) where
import GHC.Internal.Base hiding( foldr )
@@ -236,6 +247,8 @@ import GHC.Internal.Real
import Data.String( IsString )
import GHC.Internal.Ix
import GHC.Internal.Magic.Dict( WithDict )
+import GHC.Internal.TypeNats( KnownNat )
+import GHC.Internal.TypeLits( KnownSymbol, KnownChar )
import GHC.Internal.Enum
import GHC.Internal.Data.Dynamic( toDyn )
import GHC.Internal.Data.Data
@@ -253,7 +266,7 @@ import GHC.Internal.Desugar( (>>>) ) -- See Note [Tricky known-occ cases]
import GHC.Internal.OverloadedLabels( fromLabel )
import GHC.Internal.Records
import GHC.Internal.CString as CS
-import GHC.Internal.TypeError( Unsatisfiable, unsatisfiable )
+import GHC.Internal.TypeError( TypeError, ErrorMessage(..), Unsatisfiable, unsatisfiable )
import GHC.Internal.System.IO( print )
import qualified GHC.Internal.IsList as IL
import GHC.Internal.Err( error )
@@ -263,7 +276,7 @@ import GHC.Internal.Word( Word8(W8#), Word16(W16#), Word32(W32#), Word64(W64#) )
import GHC.Internal.Unsafe.Coerce( UnsafeEquality(..), unsafeEqualityProof )
-import GHC.Internal.StaticPtr( IsStatic(..) )
+import GHC.Internal.StaticPtr( IsStatic(..), StaticPtr(..), StaticPtrInfo(..) )
import GHC.Internal.StaticPtr.Internal( makeStatic )
import GHC.Internal.Stable( StablePtr, newStablePtr )
@@ -280,7 +293,8 @@ import GHC.Internal.TH.Lib
import GHC.Internal.TH.Lift
import GHC.Internal.TH.Monad
import GHC.Internal.TopHandler
-import GHC.Internal.Classes.IP (IP)
import GHC.Internal.GHCi
import GHC.Internal.Desugar (toAnnotationWrapper)
import GHC.Internal.Stack.Types
+import GHC.Internal.Exception.Context
+import GHC.Internal.JS.Prim (unsafeUnpackJSStringUtf8##)
=====================================
libraries/ghc-internal/src/GHC/Internal/Exception/Context.hs
=====================================
@@ -6,6 +6,7 @@
{-# LANGUAGE GADTs #-}
{-# OPTIONS_HADDOCK not-home #-}
+{-# OPTIONS_GHC -fdefines-known-key-names #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Internal.Exception.Context
=====================================
libraries/ghc-internal/src/GHC/Internal/Exception/Context.hs-boot
=====================================
@@ -1,4 +1,5 @@
{-# LANGUAGE NoImplicitPrelude #-}
+{-# OPTIONS_GHC -fdefines-known-key-names #-}
module GHC.Internal.Exception.Context where
=====================================
libraries/ghc-internal/src/GHC/Internal/JS/Prim.hs
=====================================
@@ -6,6 +6,8 @@
{-# LANGUAGE UnliftedFFITypes #-}
{-# LANGUAGE UnboxedTuples #-}
+{-# OPTIONS_GHC -fdefines-known-key-names #-}
+
module GHC.Internal.JS.Prim ( JSVal(..), JSVal#
, JSException(..)
, WouldBlockException(..)
=====================================
libraries/ghc-internal/src/GHC/Internal/Stack/Types.hs
=====================================
@@ -9,6 +9,7 @@
-- we hide this module from haddock to enforce GHC.Internal.Stack as the main
-- access point.
+{-# OPTIONS_GHC -fdefines-known-key-names #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Internal.Stack.Types
=====================================
libraries/ghc-internal/src/GHC/Internal/Types.hs
=====================================
@@ -8,7 +8,6 @@
-- NegativeLiterals: see Note [Fixity of (->)]
{-# OPTIONS_HADDOCK print-explicit-runtime-reps #-}
-{-# OPTIONS_GHC -frebindable-known-names #-} -- built-in type reps (e.g. krepStar) are defined in this module.
-----------------------------------------------------------------------------
-- |
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c8f3006f84841af96028cea4ee4cc9…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c8f3006f84841af96028cea4ee4cc9…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/dcoutts/windows-rts-dll] 5 commits: Add minimal dlltool support into ./configure
by David Eichmann (@DavidEichmann) 05 May '26
by David Eichmann (@DavidEichmann) 05 May '26
05 May '26
David Eichmann pushed to branch wip/dcoutts/windows-rts-dll at Glasgow Haskell Compiler / GHC
Commits:
68eff119 by Duncan Coutts at 2026-05-05T14:51:51+01:00
Add minimal dlltool support into ./configure
Find dlltool, and hopefully support finding it within the bundled llvm
toolchain on windows.
- - - - -
50192927 by Duncan Coutts at 2026-05-05T14:51:51+01:00
Update the default host and target files for dlltool support
- - - - -
0ef6450c by Duncan Coutts at 2026-05-05T14:51:51+01:00
Add dlltool as a hadrian builder
Optional except on windows.
- - - - -
95501811 by Duncan Coutts at 2026-05-05T14:51:51+01:00
Update and generate libHSghc-internal.def from .def.in file
The only symbol that the rts imports from the ghc-internal package now
is init_ghc_hs_iface. So the rts only needs an import lib that defines
that one symbol.
Also, remove the libHSghc-prim.def because it is redundant. The rts no
longer imports anything from ghc-prim.
Keep libHSffi.def for now. We may yet need it once it is clear how
libffi is going to be built/used for ghc.
- - - - -
fba86f1e by Duncan Coutts at 2026-05-05T14:51:51+01:00
Add rule to build libHSghc-internal.dll.a and link into the rts
On windows only, with dynamic linking.
This is needed because on windows, all symbols in dlls must be resolved.
No dangling symbols allowed. References to external symbols must be
explicit. We resolve this with an import library. We create an import
library for ghc-internal, a .dll.a file. This is a static archive
containing .o files that define the symbols we need, and crucially have
".idata" sections that specifies the symbols the dll imports and from
where.
Note that we do not install this libHSghc-internal.dll.a, and it does
not need to list all the symbols exported by that package. We create a
special purpose import lib and only use it when linking the rts dll, so
it only has to list the symbols that the rts uses from ghc-internal
(which is exactly one symbol: init_ghc_hs_iface).
- - - - -
15 changed files:
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/jobs.yaml
- configure.ac
- distrib/configure.ac.in
- hadrian/cfg/default.host.target.in
- hadrian/cfg/default.target.in
- hadrian/src/Builder.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Rules/Library.hs
- hadrian/src/Rules/Rts.hs
- m4/fp_setup_windows_toolchain.m4
- m4/ghc_toolchain.m4
- m4/prep_target_file.m4
- rts/.gitignore
- + rts/win32/libHSghc-internal.def.in
Changes:
=====================================
.gitlab/generate-ci/gen_ci.hs
=====================================
@@ -1305,6 +1305,7 @@ cross_jobs = [
. setVariable "STRINGS" (llvm_prefix ++ "strings")
. setVariable "STRIP" (llvm_prefix ++ "strip")
. setVariable "WindresCmd" (llvm_prefix ++ "windres")
+ . setVariable "DlltoolCmd" (llvm_prefix ++ "llvm-dlltool")
. setVariable "LLVMAS" (llvm_prefix ++ "clang")
. setVariable "LD" (llvm_prefix ++ "ld")
-- Windows target require to make linker merge feature check disabled.
=====================================
.gitlab/jobs.yaml
=====================================
@@ -317,6 +317,7 @@
"CROSS_EMULATOR": "/opt/wine-arm64ec-msys2-deb12/bin/wine",
"CROSS_TARGET": "aarch64-unknown-mingw32",
"CXX": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-clang++",
+ "DlltoolCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-llvm-dlltool",
"HADRIAN_ARGS": "--docs=none",
"INSTALL_CONFIGURE_ARGS": "--enable-strict-ghc-toolchain-check",
"LD": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld",
@@ -399,6 +400,7 @@
"CROSS_EMULATOR": "/opt/wine-arm64ec-msys2-deb12/bin/wine",
"CROSS_TARGET": "aarch64-unknown-mingw32",
"CXX": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-clang++",
+ "DlltoolCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-llvm-dlltool",
"HADRIAN_ARGS": "--docs=none",
"INSTALL_CONFIGURE_ARGS": "--enable-strict-ghc-toolchain-check",
"LD": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld",
@@ -1111,6 +1113,7 @@
"CROSS_EMULATOR": "/opt/wine-arm64ec-msys2-deb12/bin/wine",
"CROSS_TARGET": "aarch64-unknown-mingw32",
"CXX": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-clang++",
+ "DlltoolCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-llvm-dlltool",
"HADRIAN_ARGS": "--docs=none",
"INSTALL_CONFIGURE_ARGS": "--enable-strict-ghc-toolchain-check",
"LD": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld",
@@ -1194,6 +1197,7 @@
"CROSS_EMULATOR": "/opt/wine-arm64ec-msys2-deb12/bin/wine",
"CROSS_TARGET": "aarch64-unknown-mingw32",
"CXX": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-clang++",
+ "DlltoolCmd": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-llvm-dlltool",
"HADRIAN_ARGS": "--docs=none",
"INSTALL_CONFIGURE_ARGS": "--enable-strict-ghc-toolchain-check",
"LD": "/opt/llvm-mingw-linux/bin/aarch64-w64-mingw32-ld",
=====================================
configure.ac
=====================================
@@ -314,13 +314,16 @@ else
AC_CHECK_TOOL([RANLIB],[ranlib])
AC_CHECK_TOOL([OBJDUMP],[objdump])
AC_CHECK_TOOL([WindresCmd],[windres])
+ AC_CHECK_TOOL([DlltoolCmd],[llvm-dlltool])
AC_CHECK_TOOL([Genlib],[genlib])
if test "$HostOS" = "mingw32"; then
AC_CHECK_TARGET_TOOL([WindresCmd],[windres])
+ AC_CHECK_TARGET_TOOL([DlltoolCmd],[llvm-dlltool])
AC_CHECK_TARGET_TOOL([OBJDUMP],[objdump])
WindresCmd="$(cygpath -m $WindresCmd)"
+ DlltoolCmd="$(cygpath -m $DlltoolCmd)"
if test "$Genlib" != ""; then
GenlibCmd="$(cygpath -m $Genlib)"
@@ -1080,9 +1083,10 @@ echo "\
libdw : $UseLibdw
Using LLVM tools
- llc : $LlcCmd
- opt : $OptCmd
- llvm-as : $LlvmAsCmd"
+ llc : $LlcCmd
+ opt : $OptCmd
+ llvm-as : $LlvmAsCmd
+ llvm-dlltool : $DlltoolCmd"
if test "$HSCOLOUR" = ""; then
echo "
=====================================
distrib/configure.ac.in
=====================================
@@ -229,6 +229,12 @@ FIND_LLVM_PROG([LLVMAS], [clang], [$LlvmMinVersion], [$LlvmMaxVersion])
LlvmAsCmd="$LLVMAS"
AC_SUBST([LlvmAsCmd])
+dnl ** Which LLVM llvm-dlltool to use?
+dnl --------------------------------------------------------------
+AC_ARG_VAR(DlltoolCmd,[Use as the path to LLVM's llvm-dlltool [default=autodetect]])
+FIND_LLVM_PROG([DlltoolCmd], [llvm-dlltool], [$LlvmMinVersion], [$LlvmMaxVersion])
+AC_SUBST([DlltoolCmd])
+
dnl We know that `clang` supports `--target` and it is necessary to pass it
dnl lest we see #25793.
if test -z "$LlvmAsFlags" && ! test -z "$LlvmTarget"; then
=====================================
hadrian/cfg/default.host.target.in
=====================================
@@ -45,6 +45,7 @@ Target
, tgtOpt = Nothing
, tgtLlvmAs = Nothing
, tgtWindres = Nothing
+, tgtDlltool = Nothing
, tgtOtool = Nothing
, tgtInstallNameTool = Nothing
}
=====================================
hadrian/cfg/default.target.in
=====================================
@@ -45,6 +45,7 @@ Target
, tgtOpt = @OptCmdMaybeProg@
, tgtLlvmAs = @LlvmAsCmdMaybeProg@
, tgtWindres = @WindresCmdMaybeProg@
+, tgtDlltool = @DlltoolCmdMaybeProg@
, tgtOtool = @OtoolCmdMaybeProg@
, tgtInstallNameTool = @InstallNameToolCmdMaybeProg@
}
=====================================
hadrian/src/Builder.hs
=====================================
@@ -17,7 +17,7 @@ import Development.Shake.Classes
import Development.Shake.Command
import Development.Shake.FilePath
import GHC.Generics
-import GHC.Platform.ArchOS (ArchOS(..), Arch(..))
+import GHC.Platform.ArchOS (ArchOS(..), Arch(..), OS(..))
import qualified Hadrian.Builder as H
import Hadrian.Builder hiding (Builder)
import Hadrian.Builder.Ar
@@ -180,6 +180,7 @@ data Builder = Alex
| Objdump
| Python
| Ranlib
+ | Dlltool
| Testsuite TestMode
| Sphinx SphinxMode
| Tar TarMode
@@ -418,6 +419,7 @@ isOptional target = \case
Alex -> True
-- Most ar implemententions no longer need ranlib, but some still do
Ranlib -> not $ Toolchain.arNeedsRanlib (tgtAr target)
+ Dlltool -> archOS_OS (tgtArchOs target) /= OSMinGW32
JsCpp -> not $ (archOS_arch . tgtArchOs) target == ArchJavaScript -- ArchWasm32 too?
_ -> False
@@ -442,6 +444,7 @@ systemBuilderPath builder = case builder of
Objdump -> fromKey "objdump"
Python -> fromKey "python"
Ranlib -> fromTargetTC "ranlib" (maybeProg Toolchain.ranlibProgram . tgtRanlib)
+ Dlltool -> fromTargetTC "dlltool" (maybeProg id . tgtDlltool)
Testsuite _ -> fromKey "python"
Sphinx _ -> fromKey "sphinx-build"
Tar _ -> fromKey "tar"
=====================================
hadrian/src/Rules/Generate.hs
=====================================
@@ -377,6 +377,7 @@ templateRules = do
, interpolateSetting "ProjectPatchLevel1" ProjectPatchLevel1
, interpolateSetting "ProjectPatchLevel2" ProjectPatchLevel2
]
+ templateRule "rts/win32/libHSghc-internal.def" projectVersion
templateRule "docs/index.html" $ packageUnitIds Stage1
templateRule "docs/users_guide/ghc_config.py" $ mconcat
[ projectVersion
=====================================
hadrian/src/Rules/Library.hs
=====================================
@@ -4,6 +4,8 @@ import Hadrian.BuildPath
import Hadrian.Haskell.Cabal
import Hadrian.Haskell.Cabal.Type
import qualified Text.Parsec as Parsec
+import GHC.Platform.ArchOS (ArchOS(archOS_OS), OS(..))
+import GHC.Toolchain.Target (Target(tgtArchOs))
import Base
import Context
@@ -185,9 +187,13 @@ jsObjects context = do
srcs <- interpretInContext context (getContextData jsSrcs)
mapM (objectPath context) srcs
--- | Return extra object files needed to build the given library context. The
--- resulting list is currently non-empty only when the package from the
--- 'Context' is @ghc-internal@ built with in-tree GMP backend.
+-- | Return extra object files needed to build the given library context.
+--
+-- This is non-empty for:
+--
+-- * @ghc-internal@ when built with in-tree GMP backend
+-- * @rts@ on Windows when linking dynamically
+--
extraObjects :: Context -> Action [FilePath]
extraObjects context
| package context == ghcInternal = do
@@ -195,6 +201,13 @@ extraObjects context
"gmp" -> gmpObjects (stage context)
_ -> return []
+ | package context == rts = do
+ target <- interpretInContext context getStagedTarget
+ builddir <- buildPath context
+ return [ builddir -/- "libHSghc-internal.dll.a"
+ | archOS_OS (tgtArchOs target) == OSMinGW32
+ , Dynamic `wayUnit` way context ]
+
| otherwise = return []
-- | Return all the object files to be put into the library we're building for
=====================================
hadrian/src/Rules/Rts.hs
=====================================
@@ -24,6 +24,20 @@ rtsRules = priority 3 $ do
(addRtsDummyVersion $ takeFileName rtsLibFilePath')
rtsLibFilePath'
+ -- Solve the recursive dependency between the rts and ghc-internal
+ -- on Windows by creating an import lib for the ghc-internal dll,
+ -- to be linked into the rts dll.
+ forM_ [Stage1, Stage2, Stage3 ] $ \ stage -> do
+ let buildPath = root -/- buildDir (rtsContext stage)
+ buildPath -/- "libHSghc-internal.dll.a" %> buildGhcInternalImportLib
+
+buildGhcInternalImportLib :: FilePath -> Action ()
+buildGhcInternalImportLib target = do
+ let input = "rts/win32/libHSghc-internal.def"
+ output = target -- the .dll.a import lib
+ need [input]
+ runBuilder Dlltool ["-d", input, "-l", output] [input] [output]
+
-- Need symlinks generated by rtsRules.
needRtsSymLinks :: Stage -> Set.Set Way -> Action ()
needRtsSymLinks stage rtsWays
=====================================
m4/fp_setup_windows_toolchain.m4
=====================================
@@ -131,8 +131,8 @@ AC_DEFUN([FP_SETUP_WINDOWS_TOOLCHAIN],[
AR="${mingwbin}llvm-ar.exe"
RANLIB="${mingwbin}llvm-ranlib.exe"
OBJDUMP="${mingwbin}llvm-objdump.exe"
- DLLTOOL="${mingwbin}llvm-dlltool.exe"
WindresCmd="${mingwbin}llvm-windres.exe"
+ DlltoolCmd="${mingwbin}llvm-dlltool.exe"
LLC="${mingwbin}llc.exe"
OPT="${mingwbin}opt.exe"
LLVMAS="${mingwbin}clang.exe"
=====================================
m4/ghc_toolchain.m4
=====================================
@@ -95,6 +95,7 @@ AC_DEFUN([FIND_GHC_TOOLCHAIN],
echo "--merge-objs=$MergeObjsCmd" >> acargs
echo "--readelf=$READELF" >> acargs
echo "--windres=$WindresCmd" >> acargs
+ echo "--dlltool=$DlltoolCmd" >> acargs
echo "--llc=$LlcCmd" >> acargs
echo "--opt=$OptCmd" >> acargs
echo "--llvm-as=$LlvmAsCmd" >> acargs
=====================================
m4/prep_target_file.m4
=====================================
@@ -191,6 +191,7 @@ AC_DEFUN([PREP_TARGET_FILE],[
PREP_MAYBE_SIMPLE_PROGRAM([OptCmd])
PREP_MAYBE_PROGRAM([LlvmAsCmd], [LlvmAsFlags])
PREP_MAYBE_SIMPLE_PROGRAM([WindresCmd])
+ PREP_MAYBE_SIMPLE_PROGRAM([DlltoolCmd])
PREP_MAYBE_SIMPLE_PROGRAM([OtoolCmd])
PREP_MAYBE_SIMPLE_PROGRAM([InstallNameToolCmd])
PREP_MAYBE_STRING([TargetVendor_CPP])
=====================================
rts/.gitignore
=====================================
@@ -20,3 +20,4 @@
/ghcautoconf.h.autoconf.in
/ghcautoconf.h.autoconf
/include/ghcautoconf.h
+/win32/libHSghc-internal.def
=====================================
rts/win32/libHSghc-internal.def.in
=====================================
@@ -0,0 +1,4 @@
+LIBRARY libHSghc-internal-@ProjectVersionForLib@.0-ghc@ProjectVersion@.dll
+
+EXPORTS
+ init_ghc_hs_iface
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c3ece8f6c63c0b881cd18b4abc3ae8…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c3ece8f6c63c0b881cd18b4abc3ae8…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/marge_bot_batch_merge_job] 8 commits: testsuite: fix flaky foundation Divisible / mulIntMayOflo# tests (#27222)
by Marge Bot (@marge-bot) 05 May '26
by Marge Bot (@marge-bot) 05 May '26
05 May '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
5c4c3bf4 by Sylvain Henry at 2026-05-02T03:39:28-04:00
testsuite: fix flaky foundation Divisible / mulIntMayOflo# tests (#27222)
Since the LCG was widened to 64 bits and the seed randomised per CI run
(commit 2d30f7d3400 "Vendor mini-QuickCheck for testsuite"), two latent
bugs in the foundation test surface stochastically:
* The Divisible property `(x `div` y) * y + (x `mod` y) == x` raises
ArithException(Overflow) when (a, b) = (minBound, -1) for fixed-width
signed Integral types. Split testNumber/testDivisible into Bounded and
unbounded variants and skip just that one pair, gated by
`(minBound :: a) < 0` so unsigned types lose no coverage.
* The `mulIntMayOflo#` test compared raw Int# bit-for-bit, but the primop
is only specified to return 0/non-zero -- the exact non-zero indicator
legitimately differs between backends and inlining choices. Add a
dedicated `testPrimopMayOflo` helper that only compares zero / non-zero.
Also fix the long-standing typo "Dividible" -> "Divisible" in identifiers.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
- - - - -
e242ce4f by Sylvain Henry at 2026-05-02T03:39:28-04:00
testsuite: catch and display exceptions in MiniQuickCheck
Exceptions raised while evaluating a property are now caught and reported
as a normal failure (with arguments and seed), instead of aborting the
test.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
- - - - -
3b75cccd by fendor at 2026-05-02T03:40:14-04:00
Fix name of Note [Structure of dep_boot_mods]
- - - - -
a179e30b by Duncan Coutts at 2026-05-05T09:34:15-04:00
Use __attribute__((dllimport)) for external RTS symbol declarations
This is needed to be hygenic about DLL symbol imports and exports.
The attribute is ignored on platforms other than Windows.
Use of the attribute however means that external data symbols do not
have a compile-time constant address (they are loaded using an
indirection). This means we have to adjust the rtsSyms initial linker
table so that it is a local constant in a function, rather than a global
constant. We now define it within a function that pre-populates the
symbol table with the RTS symbols.
- - - - -
fdd26b00 by Duncan Coutts at 2026-05-05T09:34:15-04:00
Fix the rts linker declarations for a few data symbols
and ensure that the (windows only) rts_IOManagerIsWin32Native data
symbol is marked as externally visible.
- - - - -
1036f2ac by David Eichmann at 2026-05-05T09:34:15-04:00
Hadrian: Disable runtime pseudo relocations for RTS on windows hosts
- - - - -
6414bc49 by Teo Camarasu at 2026-05-05T09:34:16-04:00
ghci/TH: refactor to use IORef QState
This is a pure refactor and shouldn't modify semantics at all
- - - - -
bce22879 by Teo Camarasu at 2026-05-05T09:34:16-04:00
iserv: recover/getQ/putQ should behave same as internal interpreter
The internal and external interpreter should behave the same when
handling `recover`, the exeception recovery method of Q.
In practice, they diverge. In case of failure, the internal interpreter
only restores error message state to before the computation, wheras the
external interperter restores error message state *and* the state of putQ/getQ.
As far as I can tell this is a simple mistake in the implementation.
Note [TH recover with -fexternal-interpreter] describes the correct
behaviour but the implementation doesn't mirror this.
This change restores the correct behaviour by keeping the effects of
putQ in the erroring computation.
This is a breaking change since it modifies the behaviour of programs
that rely on recover ignoring putQ from failling computations when used
with the external interpreter. Although I highly doubt anyone relies on
this behaviour.
This divergence was first introduced in d00c308633fe7d216d31a1087e00e63532d87d6d.
As far as I can tell this was unintentional and tha commit was trying to solve a different bug.
Resolves #27022
- - - - -
16 changed files:
- + changelog.d/T27022
- compiler/GHC/Unit/Module/Deps.hs
- hadrian/src/Settings/Packages.hs
- libraries/ghci/GHCi/TH.hs
- rts/IOManager.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/linker/Elf.c
- testsuite/tests/MiniQuickCheck.hs
- testsuite/tests/linters/notes.stdout
- testsuite/tests/numeric/should_run/foundation.hs
- + testsuite/tests/th/T27022.hs
- + testsuite/tests/th/T27022.stdout
- testsuite/tests/th/all.T
Changes:
=====================================
changelog.d/T27022
=====================================
@@ -0,0 +1,11 @@
+section: compiler
+synopsis: Fix a divergence in the interaction between ``recover`` and ``putQ`` between the internal and external interpreter
+description: The ``recover`` method in TemplateHaskell now behaves the same
+ with the internal and external interpreter.
+ In the past, when an error was encountered in a computation in a ``recover`` block,
+ the external interpreter would discard any state changes from ``putQ``,
+ whereas the internal interpreter would not.
+ This was a long-standing error in the implementation of the external interpreter.
+ Both now keep state changes from ``putQ`` in ``recover`` blocks.
+mrs: !15994
+issues: #27022
=====================================
compiler/GHC/Unit/Module/Deps.hs
=====================================
@@ -96,7 +96,7 @@ data Dependencies = Deps
, dep_boot_mods_ :: Set (UnitId, ModuleNameWithIsBoot)
-- ^ All modules which have boot files below this one, and whether we
-- should use the boot file or not.
- -- This information is only used to populate the eps_is_boot field.
+ -- This information is only used to populate the 'eps_is_boot' field.
-- See Note [Structure of dep_boot_mods]
, dep_orphs_ :: [Module]
@@ -605,7 +605,7 @@ hash of the module. The export hash is computed in `GHC.Iface.Recomp.addFingerpr
-}
{-
-Note [Structure of dep_boot_deps]
+Note [Structure of dep_boot_mods]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In `-c` mode we always need to know whether to load the normal or boot version of
=====================================
hadrian/src/Settings/Packages.hs
=====================================
@@ -322,6 +322,7 @@ rtsPackageArgs = package rts ? do
, Profiling `wayUnit` way ? arg "-DPROFILING"
, Threaded `wayUnit` way ? arg "-DTHREADED_RTS"
, notM targetSupportsSMP ? arg "-optc-DNOSMP"
+ , isWinHost ? arg "-optl-Wl,--disable-runtime-pseudo-reloc"
-- See Note [AutoApply.cmm for vectors] in genapply/Main.hs
--
=====================================
libraries/ghci/GHCi/TH.hs
=====================================
@@ -119,7 +119,7 @@ initQState :: Pipe -> QState
initQState p = QState M.empty Nothing p
-- | The monad in which we run TH computations on the server
-newtype GHCiQ a = GHCiQ { runGHCiQ :: QState -> IO (a, QState) }
+newtype GHCiQ a = GHCiQ { runGHCiQ :: IORef QState -> IO a }
-- | The exception thrown by "fail" in the GHCiQ monad
data GHCiQException = GHCiQException QState String
@@ -128,52 +128,54 @@ data GHCiQException = GHCiQException QState String
instance Exception GHCiQException
instance Functor GHCiQ where
- fmap f (GHCiQ s) = GHCiQ $ fmap (\(x,s') -> (f x,s')) . s
+ fmap f (GHCiQ m) = GHCiQ $ fmap f . m
instance Applicative GHCiQ where
f <*> a = GHCiQ $ \s ->
- do (f',s') <- runGHCiQ f s
- (a',s'') <- runGHCiQ a s'
- return (f' a', s'')
- pure x = GHCiQ (\s -> return (x,s))
+ do f' <- runGHCiQ f s
+ a' <- runGHCiQ a s
+ return $ f' a'
+ pure x = GHCiQ $ \_ -> return x
instance Monad GHCiQ where
m >>= f = GHCiQ $ \s ->
- do (m', s') <- runGHCiQ m s
- (a, s'') <- runGHCiQ (f m') s'
- return (a, s'')
+ do m' <- runGHCiQ m s
+ a <- runGHCiQ (f m') s
+ return a
instance MonadFail GHCiQ where
- fail err = GHCiQ $ \s -> throwIO (GHCiQException s err)
+ fail err = GHCiQ $ \sRef -> readIORef sRef >>= \s -> throwIO (GHCiQException s err)
getState :: GHCiQ QState
-getState = GHCiQ $ \s -> return (s,s)
+getState = GHCiQ $ \sRef -> readIORef sRef
noLoc :: TH.Loc
noLoc = TH.Loc "<no file>" "<no package>" "<no module>" (0,0) (0,0)
-- | Send a 'THMessage' to GHC and return the result.
ghcCmd :: Binary a => THMessage (THResult a) -> GHCiQ a
-ghcCmd m = GHCiQ $ \s -> do
+ghcCmd m = GHCiQ $ \sRef -> do
+ s <- readIORef sRef
r <- remoteTHCall (qsPipe s) m
case r of
THException str -> throwIO (GHCiQException s str)
- THComplete res -> return (res, s)
+ THComplete res -> return res
instance MonadIO GHCiQ where
- liftIO m = GHCiQ $ \s -> fmap (,s) m
+ liftIO m = GHCiQ $ \_ -> m
instance TH.Quasi GHCiQ where
qNewName str = ghcCmd (NewName str)
qReport isError msg = ghcCmd (Report isError msg)
-- See Note [TH recover with -fexternal-interpreter] in GHC.Tc.Gen.Splice
- qRecover (GHCiQ h) a = GHCiQ $ \s -> mask $ \unmask -> do
+ qRecover (GHCiQ h) a = GHCiQ $ \sRef -> mask $ \unmask -> do
+ s <- readIORef sRef
remoteTHCall (qsPipe s) StartRecover
- e <- try $ unmask $ runGHCiQ (a <* ghcCmd FailIfErrs) s
+ e <- try $ unmask $ runGHCiQ (a <* ghcCmd FailIfErrs) sRef
remoteTHCall (qsPipe s) (EndRecover (isLeft e))
case e of
- Left GHCiQException{} -> h s
+ Left GHCiQException{} -> h sRef
Right r -> return r
qLookupName isType occ = ghcCmd (LookupName isType occ)
qReify name = ghcCmd (Reify name)
@@ -200,15 +202,16 @@ instance TH.Quasi GHCiQ where
qAddTempFile suffix = ghcCmd (AddTempFile suffix)
qAddTopDecls decls = ghcCmd (AddTopDecls decls)
qAddForeignFilePath lang fp = ghcCmd (AddForeignFilePath lang fp)
- qAddModFinalizer fin = GHCiQ (\s -> mkRemoteRef fin >>= return . (, s)) >>=
+ qAddModFinalizer fin = GHCiQ (\_ -> mkRemoteRef fin) >>=
ghcCmd . AddModFinalizer
qAddCorePlugin str = ghcCmd (AddCorePlugin str)
- qGetQ = GHCiQ $ \s ->
+ qGetQ = do
+ s <- getState
let lookup :: forall a. Typeable a => Map TypeRep Dynamic -> Maybe a
lookup m = fromDynamic =<< M.lookup (typeOf (undefined::a)) m
- in return (lookup (qsMap s), s)
- qPutQ k = GHCiQ $ \s ->
- return ((), s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
+ return $ lookup (qsMap s)
+ qPutQ k = GHCiQ $ \sRef ->
+ modifyIORef' sRef (\s -> s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) })
qIsExtEnabled x = ghcCmd (IsExtEnabled x)
qExtsEnabled = ghcCmd ExtsEnabled
qPutDoc l s = ghcCmd (PutDoc l s)
@@ -231,7 +234,8 @@ runModFinalizerRefs pipe rstate qrefs = do
qs <- mapM localRef qrefs
qstateref <- localRef rstate
qstate <- readIORef qstateref
- _ <- runGHCiQ (TH.runQ $ sequence_ qs) qstate { qsPipe = pipe }
+ qstate' <- newIORef $ qstate { qsPipe = pipe }
+ _ <- runGHCiQ (TH.runQ $ sequence_ qs) qstate'
return ()
-- | The implementation of the 'RunTH' message
@@ -267,8 +271,6 @@ runTHQ
-> IO ByteString
runTHQ pipe rstate mb_loc ghciq = do
qstateref <- localRef rstate
- qstate <- readIORef qstateref
- let st = qstate { qsLocation = mb_loc, qsPipe = pipe }
- (r,new_state) <- runGHCiQ (TH.runQ ghciq) st
- writeIORef qstateref new_state
+ modifyIORef' qstateref (\qstate -> qstate { qsLocation = mb_loc, qsPipe = pipe })
+ r <- runGHCiQ (TH.runQ ghciq) qstateref
return $! LB.toStrict (runPut (put r))
=====================================
rts/IOManager.h
=====================================
@@ -21,6 +21,15 @@
#include "sm/GC.h" // for evac_fn
+#if defined(mingw32_HOST_OS)
+/* Global var (only on Windows) that is exported (hence before BeginPrivate.h)
+ * to be shared with the I/O code in the base library to tell us which style
+ * of I/O manager we are using: one that uses the Windows native API HANDLEs,
+ * or one that uses Posix style fds.
+ */
+extern bool rts_IOManagerIsWin32Native;
+#endif
+
#include "BeginPrivate.h"
/* The ./configure gives us a set of CPP flags, one for each named I/O manager:
@@ -160,14 +169,6 @@ typedef enum {
/* Global var to tell us which I/O manager impl we are using */
extern IOManagerType iomgr_type;
-#if defined(mingw32_HOST_OS)
-/* Global var (only on Windows) that is exported to be shared with the I/O code
- * in the base library to tell us which style of I/O manager we are using: one
- * that uses the Windows native API HANDLEs, or one that uses Posix style fds.
- */
-extern bool rts_IOManagerIsWin32Native;
-#endif
-
/* The CapIOManager is the per-capability data structure belonging to the I/O
* manager. It is defined in full in IOManagerInternals.h. The opaque forward
=====================================
rts/Linker.c
=====================================
@@ -478,16 +478,7 @@ initLinker_ (int retain_cafs)
symhash = allocStrHashTable();
/* populate the symbol table with stuff from the RTS */
- IF_DEBUG(linker, debugBelch("populating linker symbol table with built-in RTS symbols\n"));
- for (const RtsSymbolVal *sym = rtsSyms; sym->lbl != NULL; sym++) {
- IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
- if (! ghciInsertSymbolTable(WSTR("(GHCi built-in symbols)"),
- symhash, sym->lbl, sym->addr,
- sym->strength, sym->type, 0, NULL)) {
- barf("ghciInsertSymbolTable failed");
- }
- }
- IF_DEBUG(linker, debugBelch("done with built-in RTS symbols\n"));
+ initLinkerRtsSyms(symhash);
/* Add extra symbols. rtsExtraSyms() is a weakly defined symbol in the rts,
* that can be overrided by linking in an object with a corresponding
=====================================
rts/LinkerInternals.h
=====================================
@@ -502,4 +502,6 @@ ObjectCode* mkOc( ObjectType type, pathchar *path, char *image, int imageSize,
void initSegment(Segment *s, void *start, size_t size, SegmentProt prot, int n_sections);
void freeSegments(ObjectCode *oc);
+void initLinkerRtsSyms(StrHashTable *symhash);
+
#include "EndPrivate.h"
=====================================
rts/RtsSymbols.c
=====================================
@@ -9,6 +9,8 @@
#include "ghcplatform.h"
#include "Rts.h"
#include "RtsSymbols.h"
+#include "LinkerInternals.h"
+#include "PathUtils.h"
#include "TopHandler.h"
#include "HsFFI.h"
@@ -51,6 +53,20 @@ extern char **environ;
/* -----------------------------------------------------------------------------
* Symbols to be inserted into the RTS symbol table.
+ *
+ * Note [Naming Scheme for Symbol Macros]
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ *
+ * SymI_*: symbol is internal to the RTS. It resides in an object
+ * file/library that is linked into the RTS library (as a static
+ * archive or dynamic shared library).
+ * SymE_*: symbol is external to the RTS library. It might be linked
+ * dynamically.
+ *
+ * Sym*_HasProto : the symbol prototype is imported in an include file
+ * or defined explicitly
+ * Sym*_NeedsProto: the symbol is undefined and we add a dummy
+ * default proto extern void sym(void);
*/
#define Maybe_Stable_Names SymI_HasProto(stg_mkWeakzh) \
@@ -162,7 +178,7 @@ extern char **environ;
SymI_HasProto(stg_asyncWritezh) \
SymI_HasProto(stg_asyncDoProczh) \
SymI_HasProto(rts_InstallConsoleEvent) \
- SymI_HasProto(rts_IOManagerIsWin32Native) \
+ SymI_HasDataProto(rts_IOManagerIsWin32Native) \
SymI_HasProto(rts_ConsoleHandlerDone) \
SymI_NeedsProto(__mingw_module_is_dll) \
RTS_WIN64_ONLY(SymI_NeedsProto(___chkstk_ms)) \
@@ -914,7 +930,7 @@ extern char **environ;
SymI_HasProto(freeExecPage) \
SymI_HasProto(getAllocations) \
SymI_HasProto(revertCAFs) \
- SymI_HasProto(RtsFlags) \
+ SymI_HasDataProto(RtsFlags) \
SymI_NeedsDataProto(rts_breakpoint_io_action) \
SymI_NeedsDataProto(rts_stop_next_breakpoint) \
SymI_NeedsDataProto(rts_stop_on_exception) \
@@ -925,9 +941,9 @@ extern char **environ;
SymI_NeedsProto(rts_enableStopAfterReturn) \
SymI_NeedsProto(rts_disableStopAfterReturn) \
SymI_HasProto(stopTimer) \
- SymI_HasProto(n_capabilities) \
- SymI_HasProto(max_n_capabilities) \
- SymI_HasProto(enabled_capabilities) \
+ SymI_HasDataProto(n_capabilities) \
+ SymI_HasDataProto(max_n_capabilities) \
+ SymI_HasDataProto(enabled_capabilities) \
SymI_HasDataProto(stg_traceEventzh) \
SymI_HasDataProto(stg_traceMarkerzh) \
SymI_HasDataProto(stg_traceBinaryEventzh) \
@@ -1145,12 +1161,27 @@ extern char **environ;
SymI_HasProto(hs_word2float64)
-/* entirely bogus claims about types of these symbols */
-#define SymI_NeedsProto(vvv) extern void vvv(void);
-#define SymI_NeedsDataProto(vvv) extern StgWord vvv[];
-#define SymE_NeedsProto(vvv) SymI_NeedsProto(vvv);
-#define SymE_NeedsDataProto(vvv) SymI_NeedsDataProto(vvv);
-#define SymE_HasProto(vvv) SymI_HasProto(vvv);
+/* Declare prototypes for the symbols that need it, so we can refer
+ * to them in the rtsSyms table below.
+ *
+ * In particular, for the external ones (SymE_*) we use the dllimport attribute
+ * to indicate that (on Windows) they come from external DLLs. This attribute
+ * is ignored on other platforms.
+ *
+ * The claims about the types of these symbols are entirely bogus.
+ */
+#if defined(mingw32_HOST_OS) && defined(DYNAMIC)
+#define DLLIMPORT __attribute__((dllimport))
+#else
+#define DLLIMPORT /**/
+#endif
+
+#define SymI_NeedsProto(vvv) extern void vvv(void);
+#define SymI_NeedsDataProto(vvv) extern StgWord vvv[];
+#define SymE_NeedsProto(vvv) extern DLLIMPORT void vvv(void);
+#define SymE_NeedsDataProto(vvv) extern DLLIMPORT StgWord vvv[];
+
+#define SymE_HasProto(vvv) /**/
#define SymI_HasProto(vvv) /**/
#define SymI_HasDataProto(vvv) /**/
#define SymI_HasProto_redirect(vvv,xxx,strength,ty) /**/
@@ -1179,6 +1210,8 @@ RTS_SYMBOLS_PRIM
#undef SymE_NeedsProto
#undef SymE_NeedsDataProto
+/* See Note [Naming Scheme for Symbol Macros] */
+
#define SymI_HasProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
(void*)(&(vvv)), STRENGTH_NORMAL, SYM_TYPE_CODE },
#define SymI_HasDataProto(vvv) { MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
@@ -1199,7 +1232,16 @@ RTS_SYMBOLS_PRIM
{ MAYBE_LEADING_UNDERSCORE_STR(#vvv), \
(void*)(&(xxx)), strength, ty },
-RtsSymbolVal rtsSyms[] = {
+
+
+/* Initialize (if not already initialized) and return an array of symbols with stuff from the RTS. */
+void initLinkerRtsSyms (StrHashTable *symhash) {
+ /* The address of data symbols with the dllimport attribute are not
+ * compile-time constants and so cannot be used in constant initialisers.
+ * For this reason, rtsSyms is a local variable within this function
+ * rather than a global constant (as it was historically).
+ */
+ const RtsSymbolVal rtsSyms[] = {
RTS_SYMBOLS
RTS_RET_SYMBOLS
RTS_POSIX_ONLY_SYMBOLS
@@ -1214,7 +1256,20 @@ RtsSymbolVal rtsSyms[] = {
RTS_SYMBOLS_PRIM
SymI_HasDataProto(nonmoving_write_barrier_enabled)
{ 0, 0, STRENGTH_NORMAL, SYM_TYPE_CODE } /* sentinel */
-};
+ };
+
+ IF_DEBUG(linker, debugBelch("populating linker symbol table with built-in RTS symbols\n"));
+ for (const RtsSymbolVal *sym = rtsSyms; sym->lbl != NULL; sym++) {
+ IF_DEBUG(linker, debugBelch("initLinker: inserting rts symbol %s, %p\n", sym->lbl, sym->addr));
+ if (! ghciInsertSymbolTable(WSTR("(GHCi built-in symbols)"),
+ symhash, sym->lbl, sym->addr,
+ sym->strength, sym->type, 0, NULL)) {
+ barf("ghciInsertSymbolTable failed");
+ }
+ }
+ IF_DEBUG(linker, debugBelch("done with built-in RTS symbols\n"));
+}
+
// Note [Extra RTS symbols]
=====================================
rts/RtsSymbols.h
=====================================
@@ -46,8 +46,6 @@ typedef struct _RtsSymbolVal {
SymType type;
} RtsSymbolVal;
-extern RtsSymbolVal rtsSyms[];
-
extern RtsSymbolVal* __attribute__((weak)) rtsExtraSyms(void);
/* See Note [_iob_func symbol]. */
=====================================
rts/linker/Elf.c
=====================================
@@ -76,18 +76,6 @@
*
* See bug #781
* See thread http://www.haskell.org/pipermail/cvs-ghc/2007-September/038458.html
- *
- * Naming Scheme for Symbol Macros
- *
- * SymI_*: symbol is internal to the RTS. It resides in an object
- * file/library that is statically.
- * SymE_*: symbol is external to the RTS library. It might be linked
- * dynamically.
- *
- * Sym*_HasProto : the symbol prototype is imported in an include file
- * or defined explicitly
- * Sym*_NeedsProto: the symbol is undefined and we add a dummy
- * default proto extern void sym(void);
*/
#define X86_64_ELF_NONPIC_HACK (!RtsFlags.MiscFlags.linkerAlwaysPic)
=====================================
testsuite/tests/MiniQuickCheck.hs
=====================================
@@ -2,6 +2,7 @@
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
-- | A minimal QuickCheck-like property testing framework for use in the GHC
@@ -52,6 +53,8 @@ module MiniQuickCheck
) where
-- base
+import Control.Exception
+ ( SomeException, displayException, evaluate, try )
import Control.Monad.IO.Class
( liftIO )
import Data.Bits
@@ -181,16 +184,39 @@ nest :: String -> ReaderT RunS IO a -> ReaderT RunS IO a
nest c = local (\s -> s { depth = depth s + 1, context = c : context s })
runPropertyCheck :: PropertyCheck -> ReaderT RunS IO Result
-runPropertyCheck (PropertyBinaryOp ok desc s1 s2) =
- if ok
- then return Success
- else do
- ctx <- context <$> ask
- let msg = "Failure: " ++ s1 ++ " " ++ desc ++ " " ++ s2
- putMsg msg
- return (Failure [msg : ctx])
-runPropertyCheck (PropertyAnd a b) =
- (<>) <$> runPropertyCheck a <*> runPropertyCheck b
+runPropertyCheck pcThunk = do
+ -- See Note [Catching exceptions in property evaluation].
+ pcRes <- liftIO $ try @SomeException (evaluate pcThunk)
+ case pcRes of
+ Left e -> reportFailure ("Failure: exception: " ++ displayException e)
+ Right (PropertyAnd a b) ->
+ (<>) <$> runPropertyCheck a <*> runPropertyCheck b
+ Right (PropertyBinaryOp ok desc s1 s2) -> do
+ okRes <- liftIO $ try @SomeException (evaluate ok)
+ case okRes of
+ Right True -> return Success
+ Right False -> reportFailure ("Failure: " ++ s1 ++ " " ++ desc ++ " " ++ s2)
+ Left e -> reportFailure ("Failure: exception: " ++ displayException e)
+
+reportFailure :: String -> ReaderT RunS IO Result
+reportFailure msg = do
+ ctx <- context <$> ask
+ putMsg msg
+ return (Failure [msg : ctx])
+
+-- Note [Catching exceptions in property evaluation]
+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+-- A property like `\a b -> let !r = a `div` 0 in r === b` builds a
+-- `PropertyCheck` thunk whose forcing raises an exception -- in this case
+-- already at the `PropertyBinaryOp` constructor, before its `ok` field is
+-- ever inspected. Other properties may force `ok = (s1 == s2)` instead and
+-- raise from there.
+--
+-- To handle both, we `evaluate` first the `PropertyCheck` thunk and then
+-- the `ok` field, each inside `try`, and report any exception through the
+-- normal `reportFailure` path. The surrounding loop then still prints
+-- "With arguments ... (Seed: ...)" and the test driver continues with
+-- subsequent properties instead of aborting.
runProperty :: Iterations -> Property -> ReaderT RunS IO Result
runProperty (Iterations iters) (Prop p) = do
=====================================
testsuite/tests/linters/notes.stdout
=====================================
@@ -27,7 +27,6 @@ ref compiler/GHC/Tc/Solver/Rewrite.hs:1020:7: Note [Stability of rewritin
ref compiler/GHC/Tc/TyCl.hs:1662:6: Note [Unification variables need fresh Names]
ref compiler/GHC/Tc/Types/Constraint.hs:209:9: Note [NonCanonical Semantics]
ref compiler/GHC/Types/Demand.hs:304:25: Note [Preserving Boxity of results is rarely a win]
-ref compiler/GHC/Unit/Module/Deps.hs:97:13: Note [Structure of dep_boot_mods]
ref compiler/GHC/Utils/Monad.hs:415:34: Note [multiShotIO]
ref compiler/Language/Haskell/Syntax/Binds.hs:206:31: Note [fun_id in Match]
ref configure.ac:205:10: Note [Linking ghc-bin against threaded stage0 RTS]
=====================================
testsuite/tests/numeric/should_run/foundation.hs
=====================================
@@ -77,13 +77,42 @@ testMultiplicative _ = Group "Multiplicative"
, Property "a * b == Integer(a) * Integer(b)" $ \(a :: a) (b :: a) -> a * b === fromInteger (toInteger a * toInteger b)
]
-testDividible :: forall a . (Show a, Eq a, Integral a, Num a, Arbitrary a, Typeable a)
+-- | Divisibility test for Bounded Integral types (Int, Int{8,16,32,64},
+-- Word, Word{8,16,32,64}).
+testDivisible :: forall a . (Show a, Eq a, Bounded a, Integral a, Num a, Arbitrary a, Typeable a)
=> Proxy a -> Test
-testDividible _ = Group "Divisible"
+testDivisible _ = Group "Divisible"
+ [ Property "(x `div` y) * y + (x `mod` y) == x" $ \(a :: a) (NonZero b) ->
+ -- See Note [Skipping minBound `div` (-1)].
+ if (minBound :: a) < 0 && a == minBound && b == (-1)
+ then True === True
+ else a === (a `div` b) * b + (a `mod` b)
+ ]
+
+-- | Divisibility test for unbounded Integral types (Integer). No overflow
+-- can occur here, so the property holds without exception for all NonZero b.
+testDivisibleUnbounded :: forall a . (Show a, Eq a, Integral a, Num a, Arbitrary a, Typeable a)
+ => Proxy a -> Test
+testDivisibleUnbounded _ = Group "Divisible"
[ Property "(x `div` y) * y + (x `mod` y) == x" $ \(a :: a) (NonZero b) ->
a === (a `div` b) * b + (a `mod` b)
]
+-- Note [Skipping minBound `div` (-1)]
+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+-- For a fixed-width *signed* Integral type, `minBound `div` (-1)` raises
+-- ArithException(Overflow) because `-minBound` is not representable in the
+-- type (e.g., for Int8, `-(-128)` would be 128, out of range). The div/mod
+-- identity property cannot hold there, so we skip exactly that one pair.
+--
+-- We detect "signed Bounded" with `(minBound :: a) < 0`: True for Int{N},
+-- False for Word{N}. This way unsigned Bounded types lose no coverage,
+-- and only the genuine overflow sample is skipped for signed types.
+--
+-- For the unbounded `Integer`, no overflow can occur and we use a separate
+-- 'testDivisibleUnbounded' (without the Bounded constraint or the skip).
+-- See #27222.
+
testOperatorPrecedence :: forall a . (Show a, Eq a, Prelude.Num a, Integral a, Num a, Arbitrary a, Typeable a)
=> Proxy a -> Test
testOperatorPrecedence _ = Group "Precedence"
@@ -101,14 +130,26 @@ testOperatorPrecedence _ = Group "Precedence"
]
-testNumber :: (Show a, Eq a, Prelude.Num a, Integral a, Num a, Arbitrary a, Typeable a)
+testNumber :: (Show a, Eq a, Prelude.Num a, Bounded a, Integral a, Num a, Arbitrary a, Typeable a)
=> String -> Proxy a -> Test
testNumber name proxy = Group name
[ testIntegral proxy
, testEqOrd proxy
, testAdditive proxy
, testMultiplicative proxy
- , testDividible proxy
+ , testDivisible proxy
+ , testOperatorPrecedence proxy
+ ]
+
+-- | Variant of 'testNumber' for unbounded Integral types (e.g., Integer).
+testNumberUnbounded :: (Show a, Eq a, Prelude.Num a, Integral a, Num a, Arbitrary a, Typeable a)
+ => String -> Proxy a -> Test
+testNumberUnbounded name proxy = Group name
+ [ testIntegral proxy
+ , testEqOrd proxy
+ , testAdditive proxy
+ , testMultiplicative proxy
+ , testDivisibleUnbounded proxy
, testOperatorPrecedence proxy
]
@@ -119,7 +160,7 @@ testNumberRefs = Group "ALL"
, testNumber "Int16" (Proxy :: Proxy Int16)
, testNumber "Int32" (Proxy :: Proxy Int32)
, testNumber "Int64" (Proxy :: Proxy Int64)
- , testNumber "Integer" (Proxy :: Proxy Integer)
+ , testNumberUnbounded "Integer" (Proxy :: Proxy Integer)
, testNumber "Word" (Proxy :: Proxy Word)
, testNumber "Word8" (Proxy :: Proxy Word8)
, testNumber "Word16" (Proxy :: Proxy Word16)
@@ -399,7 +440,7 @@ testPrimops = Group "primop"
, testPrimop "-#" (Primop.-#) (Wrapper.-#)
, testPrimop "*#" (Primop.*#) (Wrapper.*#)
, testPrimop "timesInt2#" Primop.timesInt2# Wrapper.timesInt2#
- , testPrimop "mulIntMayOflo#" Primop.mulIntMayOflo# Wrapper.mulIntMayOflo#
+ , testPrimopMayOflo "mulIntMayOflo#" Primop.mulIntMayOflo# Wrapper.mulIntMayOflo#
, testPrimopDivLike "quotInt#" Primop.quotInt# Wrapper.quotInt#
, testPrimopDivLike "remInt#" Primop.remInt# Wrapper.remInt#
, testPrimopDivLike "quotRemInt#" Primop.quotRemInt# Wrapper.quotRemInt#
@@ -497,6 +538,31 @@ instance TestPrimop (Int# -> Int# -> Int#) where
testPrimopDivLike s l r = Property s $ twoNonZero $ \ (uInt#-> x0) (uInt#-> x1) -> wInt# (l x0 x1) === wInt# (r x0 x1)
testPrimopShift s l r = Property s $ \ (uInt#-> x0) (BoundedShiftAmount @Int shift) -> wInt# (l x0 (uInt# shift)) === wInt# (r x0 (uInt# shift))
+-- | Compare two 'mulIntMayOflo#'-like primops only on whether their result
+-- is zero. See Note [Comparing mulIntMayOflo# results].
+testPrimopMayOflo :: String
+ -> (Int# -> Int# -> Int#)
+ -> (Int# -> Int# -> Int#)
+ -> Test
+testPrimopMayOflo s l r =
+ Property s $ \ (uInt# -> x0) (uInt# -> x1) ->
+ (wInt# (l x0 x1) == 0) === (wInt# (r x0 x1) == 0)
+
+-- Note [Comparing mulIntMayOflo# results]
+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+-- The 'mulIntMayOflo#' primop is only specified to return 0 if the signed
+-- multiplication does not overflow, and a non-zero value if it /may/
+-- overflow (see Note [MO_S_MulMayOflo significant width] in
+-- GHC.Cmm.MachOp). The exact non-zero value is unspecified and legitimately
+-- differs between backends and between inlined vs. non-inlined call sites
+-- (e.g., the LLVM backend's `isSMulOK` returns `sext_signbit(low) - high`,
+-- which is some arbitrary non-zero word on overflow).
+--
+-- Comparing the raw Int# results bit-for-bit is therefore too strict and
+-- causes spurious test failures whenever the random arguments happen to
+-- overflow. We compare zero/non-zero instead, which matches the spec.
+-- See #27222.
+
instance TestPrimop (Int# -> Int# -> (# Int#,Int# #)) where
testPrimop s l r = Property s $ \ (uInt#-> x0) (uInt#-> x1) -> WTUP2(wInt#,wInt#, (l x0 x1)) === WTUP2(wInt#,wInt#, (r x0 x1))
testPrimopDivLike s l r = Property s $ twoNonZero $ \ (uInt#-> x0) (uInt#-> x1) -> WTUP2(wInt#,wInt#, (l x0 x1)) === WTUP2(wInt#,wInt#, (r x0 x1))
=====================================
testsuite/tests/th/T27022.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE TemplateHaskell #-}
+-- | This tests the behaviour of TH's recover method.
+-- It should behave the same in the internal and external interperter.
+-- In the past, they have diverged, and the external interpreter would roll back the state of putQ/getQ whereas the internal interpreter would not.
+module Main where
+
+import Language.Haskell.TH.Syntax
+main = print $(putQ "0" >> recover (pure ()) (putQ "42" >> fail "oops") >> getQ @String >>= lift )
=====================================
testsuite/tests/th/T27022.stdout
=====================================
@@ -0,0 +1 @@
+Just "42"
=====================================
testsuite/tests/th/all.T
=====================================
@@ -650,3 +650,4 @@ test('GadtConSigs_th_dump1', normal, compile, ['-v0 -ddump-splices -dsuppress-un
test('T26099', normal, compile_fail, [''])
test('T8306_th', only_ways(['ghci']), ghci_script, ['T8306_th.script'])
test('T26862_th', only_ways(['ghci']), ghci_script, ['T26862_th.script'])
+test('T27022', normal, compile_and_run, [''])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/4441dabbcfa6dda03992fb96d4773b…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/4441dabbcfa6dda03992fb96d4773b…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/no-ws-32-base-export] 5 commits: Add Bounded instances for Double, Float, CDouble and CFloat
by Teo Camarasu (@teo) 05 May '26
by Teo Camarasu (@teo) 05 May '26
05 May '26
Teo Camarasu pushed to branch wip/no-ws-32-base-export at Glasgow Haskell Compiler / GHC
Commits:
39141343 by Alice Rixte at 2026-05-01T14:09:32+02:00
Add Bounded instances for Double, Float, CDouble and CFloat
- - - - -
5c4c3bf4 by Sylvain Henry at 2026-05-02T03:39:28-04:00
testsuite: fix flaky foundation Divisible / mulIntMayOflo# tests (#27222)
Since the LCG was widened to 64 bits and the seed randomised per CI run
(commit 2d30f7d3400 "Vendor mini-QuickCheck for testsuite"), two latent
bugs in the foundation test surface stochastically:
* The Divisible property `(x `div` y) * y + (x `mod` y) == x` raises
ArithException(Overflow) when (a, b) = (minBound, -1) for fixed-width
signed Integral types. Split testNumber/testDivisible into Bounded and
unbounded variants and skip just that one pair, gated by
`(minBound :: a) < 0` so unsigned types lose no coverage.
* The `mulIntMayOflo#` test compared raw Int# bit-for-bit, but the primop
is only specified to return 0/non-zero -- the exact non-zero indicator
legitimately differs between backends and inlining choices. Add a
dedicated `testPrimopMayOflo` helper that only compares zero / non-zero.
Also fix the long-standing typo "Dividible" -> "Divisible" in identifiers.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
- - - - -
e242ce4f by Sylvain Henry at 2026-05-02T03:39:28-04:00
testsuite: catch and display exceptions in MiniQuickCheck
Exceptions raised while evaluating a property are now caught and reported
as a normal failure (with arguments and seed), instead of aborting the
test.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
- - - - -
3b75cccd by fendor at 2026-05-02T03:40:14-04:00
Fix name of Note [Structure of dep_boot_mods]
- - - - -
c1788778 by Teo Camarasu at 2026-05-04T21:26:58+01:00
interface-stability/base: don't distinguish ws-32
The interface of base is identical when the Word size is 32bits.
Therefore, there is no need to have another file for this case.
So, we delete it.
Step towards: #26752
- - - - -
11 changed files:
- compiler/GHC/Unit/Module/Deps.hs
- libraries/base/changelog.md
- libraries/ghc-internal/include/CTypes.h
- libraries/ghc-internal/src/GHC/Internal/Float.hs
- testsuite/tests/MiniQuickCheck.hs
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- − testsuite/tests/interface-stability/base-exports.stdout-ws-32
- testsuite/tests/linters/notes.stdout
- testsuite/tests/numeric/should_run/foundation.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/7ae755bae2a8a5836f704a0446a8ca…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/7ae755bae2a8a5836f704a0446a8ca…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
[Git][ghc/ghc][wip/jeltsch/text-read-implementation-into-base] 5 commits: Add Bounded instances for Double, Float, CDouble and CFloat
by Wolfgang Jeltsch (@jeltsch) 05 May '26
by Wolfgang Jeltsch (@jeltsch) 05 May '26
05 May '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/text-read-implementation-into-base at Glasgow Haskell Compiler / GHC
Commits:
39141343 by Alice Rixte at 2026-05-01T14:09:32+02:00
Add Bounded instances for Double, Float, CDouble and CFloat
- - - - -
5c4c3bf4 by Sylvain Henry at 2026-05-02T03:39:28-04:00
testsuite: fix flaky foundation Divisible / mulIntMayOflo# tests (#27222)
Since the LCG was widened to 64 bits and the seed randomised per CI run
(commit 2d30f7d3400 "Vendor mini-QuickCheck for testsuite"), two latent
bugs in the foundation test surface stochastically:
* The Divisible property `(x `div` y) * y + (x `mod` y) == x` raises
ArithException(Overflow) when (a, b) = (minBound, -1) for fixed-width
signed Integral types. Split testNumber/testDivisible into Bounded and
unbounded variants and skip just that one pair, gated by
`(minBound :: a) < 0` so unsigned types lose no coverage.
* The `mulIntMayOflo#` test compared raw Int# bit-for-bit, but the primop
is only specified to return 0/non-zero -- the exact non-zero indicator
legitimately differs between backends and inlining choices. Add a
dedicated `testPrimopMayOflo` helper that only compares zero / non-zero.
Also fix the long-standing typo "Dividible" -> "Divisible" in identifiers.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
- - - - -
e242ce4f by Sylvain Henry at 2026-05-02T03:39:28-04:00
testsuite: catch and display exceptions in MiniQuickCheck
Exceptions raised while evaluating a property are now caught and reported
as a normal failure (with arguments and seed), instead of aborting the
test.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
- - - - -
3b75cccd by fendor at 2026-05-02T03:40:14-04:00
Fix name of Note [Structure of dep_boot_mods]
- - - - -
73c1672e by Wolfgang Jeltsch at 2026-05-05T15:58:07+03:00
Move the `Text.Read` implementation into `base`
- - - - -
21 changed files:
- compiler/GHC/Unit/Module/Deps.hs
- libraries/base/changelog.md
- libraries/base/src/Data/Functor/Classes.hs
- libraries/base/src/Data/Functor/Compose.hs
- libraries/base/src/Prelude.hs
- libraries/base/src/Text/Read.hs
- libraries/ghc-internal/ghc-internal.cabal.in
- libraries/ghc-internal/include/CTypes.h
- libraries/ghc-internal/src/GHC/Internal/Float.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Encoding.hs
- − libraries/ghc-internal/src/GHC/Internal/Text/Read.hs
- testsuite/tests/MiniQuickCheck.hs
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/interface-stability/base-exports.stdout-ws-32
- testsuite/tests/linters/notes.stdout
- testsuite/tests/numeric/should_run/foundation.hs
- testsuite/tests/th/T24111.stdout
- testsuite/tests/typecheck/should_compile/subsumption_sort_hole_fits.stderr
- testsuite/tests/typecheck/should_fail/T21130.stderr
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/6b9447fe427f458fa04c76c1eabb76…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/6b9447fe427f458fa04c76c1eabb76…
You're receiving this email because of your account on gitlab.haskell.org.
1
0