[libcxx-commits] [PATCH] D122864: [libc++] Avoid lifetime UB in __thread_local_data()

Vitaly Buka via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Mon Apr 11 11:59:43 PDT 2022


vitalybuka updated this revision to Diff 421993.
vitalybuka added a comment.

comment


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122864/new/

https://reviews.llvm.org/D122864

Files:
  libcxx/src/thread.cpp


Index: libcxx/src/thread.cpp
===================================================================
--- libcxx/src/thread.cpp
+++ libcxx/src/thread.cpp
@@ -115,8 +115,13 @@
 __thread_specific_ptr<__thread_struct>&
 __thread_local_data()
 {
-    static __thread_specific_ptr<__thread_struct> __p;
-    return __p;
+  // Even though __thread_specific_ptr's destructor doesn't actually destroy
+  // anything (see comments there), we can't call it at all because threads may
+  // outlive the static variable and calling its destructor means accessing an
+  // object outside of its lifetime, which is UB.
+  alignas(__thread_specific_ptr<__thread_struct>) static char __b[sizeof(__thread_specific_ptr<__thread_struct>)];
+  static __thread_specific_ptr<__thread_struct>* __p = new (__b) __thread_specific_ptr<__thread_struct>();
+  return *__p;
 }
 
 // __thread_struct_imp


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D122864.421993.patch
Type: text/x-patch
Size: 869 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20220411/d5b0a54e/attachment.bin>


More information about the libcxx-commits mailing list