[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
Wed Apr 13 12:48:40 PDT 2022


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

rebase


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.422610.patch
Type: text/x-patch
Size: 869 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20220413/d0b61c2e/attachment.bin>


More information about the libcxx-commits mailing list