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

Ben Gamari (@bgamari) gitlab at gitlab.haskell.org
Tue Jan 17 21:39:19 UTC 2023



Ben Gamari pushed to branch wip/T22756 at Glasgow Haskell Compiler / GHC


Commits:
0bc1cb4f by Ben Gamari at 2023-01-17T16:39:13-05: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
=====================================
@@ -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,16 @@ hs_exit_(bool wait_foreign)
 {
     uint32_t g, i;
 
-    if (hs_init_count <= 0) {
-        errorBelch("warning: too many hs_exit()s");
-        return;
-    }
-    hs_init_count--;
-    if (hs_init_count > 0) {
+    // N.B. atomic_dec returns the new value.
+    StgWord init_count = atomic_dec(&hs_init_count);
+    if (init_count > 0) {
         // ignore until it's the last one
         return;
+    } else 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/0bc1cb4f5d8fabda32dd3ecde0ca646ed9e9e193

-- 
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0bc1cb4f5d8fabda32dd3ecde0ca646ed9e9e193
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/20230117/270443dc/attachment-0001.html>


More information about the ghc-commits mailing list