Skip to content

Commit 4095af5

Browse files
committed
[compiler-rt] Fix race condition when allocating object
For following program compiled with `-femulated-tls`, there is chance the first allocated object is different from other allocation. ``` thread_local int id = 0; std::mutex print_mutex; int main() { // std::cout << "thread " << 0 << ": " << &id << std::endl; std::vector<std::thread> group; for (int i = 1; i < 8; ++i) { group.emplace_back([i] { std::unique_lock<std::mutex> _(print_mutex); std::cout << "thread " << i << ": " << &id << std::endl; }); } for (auto &t : group) t.join(); return 0; } Output: thread 1: 0x7f57040010a8 thread 2: 0x7f56fc000c98 thread 3: 0x7f56fc000c98 thread 5: 0x7f56fc000c98 thread 4: 0x7f56fc000c98 thread 6: 0x7f56fc000c98 thread 7: 0x7f56fc000c98 ```
1 parent 49331ab commit 4095af5

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

compiler-rt/lib/builtins/emutls.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,8 +392,12 @@ __attribute__((visibility("default"), weak))
392392
void *__emutls_get_address(__emutls_control *control) {
393393
uintptr_t index = emutls_get_index(control);
394394
emutls_address_array *array = emutls_get_address_array(index--);
395-
if (array->data[index] == NULL)
396-
array->data[index] = emutls_allocate_object(control);
395+
if (array->data[index] == NULL) {
396+
emutls_lock();
397+
if (array->data[index] == NULL)
398+
array->data[index] = emutls_allocate_object(control);
399+
emutls_unlock();
400+
}
397401
return array->data[index];
398402
}
399403

0 commit comments

Comments
 (0)