[Git][ghc/ghc][master] rts: Fix data-race in hs_init_ghc

Marge Bot (@marge-bot) gitlab at gitlab.haskell.org
Tue May 9 01:41:30 UTC 2023



Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC


Commits:
3e3a6be4 by Ben Gamari at 2023-05-08T12:15:19+00:00
rts: Fix data-race in hs_init_ghc

As noticed by @Terrorjack, `hs_init_ghc` previously used non-atomic
increment/decrement on the RTS's initialization count. This may go wrong
in a multithreaded program which initializes the runtime multiple times.

Closes #22756.

- - - - -


1 changed file:

- rts/RtsStartup.c


Changes:

=====================================
rts/RtsStartup.c
=====================================
@@ -68,7 +68,7 @@
 #endif
 
 // Count of how many outstanding hs_init()s there have been.
-static int hs_init_count = 0;
+static StgWord hs_init_count = 0;
 static bool rts_shutdown = false;
 
 #if defined(mingw32_HOST_OS)
@@ -242,8 +242,9 @@ hs_init_with_rtsopts(int *argc, char **argv[])
 void
 hs_init_ghc(int *argc, char **argv[], RtsConfig rts_config)
 {
-    hs_init_count++;
-    if (hs_init_count > 1) {
+    // N.B. atomic_inc returns the new value.
+    StgWord init_count = atomic_inc(&hs_init_count, 1);
+    if (init_count > 1) {
         // second and subsequent inits are ignored
         return;
     }
@@ -452,15 +453,17 @@ hs_exit_(bool wait_foreign)
 {
     uint32_t g, i;
 
-    if (hs_init_count <= 0) {
-        errorBelch("warning: too many hs_exit()s");
+    // N.B. atomic_dec returns the new value.
+    StgInt init_count = (StgInt)atomic_dec(&hs_init_count);
+    if (init_count > 0) {
+        // ignore until it's the last one
         return;
     }
-    hs_init_count--;
-    if (hs_init_count > 0) {
-        // ignore until it's the last one
+    if (init_count < 0) {
+        errorBelch("warning: too many hs_exit()s");
         return;
     }
+
     rts_shutdown = true;
 
     /* start timing the shutdown */



View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/3e3a6be4023189b2d637beda240e23fa9e856810

-- 
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/3e3a6be4023189b2d637beda240e23fa9e856810
You're receiving this email because of your account on gitlab.haskell.org.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/ghc-commits/attachments/20230508/707b83d5/attachment-0001.html>


More information about the ghc-commits mailing list