78b9b3e
From 61d4c87c940fea028f08f27addc275b469320fda Mon Sep 17 00:00:00 2001
78b9b3e
From: David Mitchell <davem@iabyn.com>
78b9b3e
Date: Mon, 18 Feb 2019 09:19:38 +0000
78b9b3e
Subject: [PATCH] Perl_my_cxt_init: fix potential race condition
78b9b3e
MIME-Version: 1.0
78b9b3e
Content-Type: text/plain; charset=UTF-8
78b9b3e
Content-Transfer-Encoding: 8bit
78b9b3e
78b9b3e
(Found by code inspection - I can't reproduce a failure)
78b9b3e
78b9b3e
the MY_CXT subsystem, which allows per-thread pseudo-static variables,
78b9b3e
has a thread race condition.
78b9b3e
78b9b3e
When a module is first loaded, it is allocated  unique index (from
78b9b3e
PL_my_cxt_index++) which is assigned to the module's my_cxt_index static
78b9b3e
var.
78b9b3e
78b9b3e
If two threads both try to load an XS module at the same time, its
78b9b3e
possible for one thread to set my_cxtp, then a second thread to overwrite
78b9b3e
it with a higher value, causing the first thread to use the wrong index
78b9b3e
into its local storage.
78b9b3e
78b9b3e
Signed-off-by: Petr Písař <ppisar@redhat.com>
78b9b3e
---
78b9b3e
 util.c | 17 +++++++++++++----
78b9b3e
 1 file changed, 13 insertions(+), 4 deletions(-)
78b9b3e
78b9b3e
diff --git a/util.c b/util.c
78b9b3e
index 5b6f4bfd27..ae86a8c4a4 100644
78b9b3e
--- a/util.c
78b9b3e
+++ b/util.c
78b9b3e
@@ -5218,10 +5218,16 @@ Perl_my_cxt_init(pTHX_ int *index, size_t size)
78b9b3e
     dVAR;
78b9b3e
     void *p;
78b9b3e
     PERL_ARGS_ASSERT_MY_CXT_INIT;
78b9b3e
+    /* do initial check without locking.
78b9b3e
+     * -1:    not allocated or another thread currently allocating
78b9b3e
+     *  other: already allocated by another thread
78b9b3e
+     */
78b9b3e
     if (*index == -1) {
78b9b3e
-	/* this module hasn't been allocated an index yet */
78b9b3e
 	MUTEX_LOCK(&PL_my_ctx_mutex);
78b9b3e
-	*index = PL_my_cxt_index++;
78b9b3e
+        /*now a stricter check with locking */
78b9b3e
+        if (*index == -1)
78b9b3e
+            /* this module hasn't been allocated an index yet */
78b9b3e
+            *index = PL_my_cxt_index++;
78b9b3e
 	MUTEX_UNLOCK(&PL_my_ctx_mutex);
78b9b3e
     }
78b9b3e
     
78b9b3e
@@ -5278,9 +5284,12 @@ Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
78b9b3e
 
78b9b3e
     index = Perl_my_cxt_index(aTHX_ my_cxt_key);
78b9b3e
     if (index == -1) {
78b9b3e
-	/* this module hasn't been allocated an index yet */
78b9b3e
 	MUTEX_LOCK(&PL_my_ctx_mutex);
78b9b3e
-	index = PL_my_cxt_index++;
78b9b3e
+        /*now a stricter check with locking */
78b9b3e
+        index = Perl_my_cxt_index(aTHX_ my_cxt_key);
78b9b3e
+        if (index == -1)
78b9b3e
+            /* this module hasn't been allocated an index yet */
78b9b3e
+            index = PL_my_cxt_index++;
78b9b3e
 	MUTEX_UNLOCK(&PL_my_ctx_mutex);
78b9b3e
     }
78b9b3e
 
78b9b3e
-- 
78b9b3e
2.20.1
78b9b3e