blob: 5a9cc998bccf39135a489407ce1b45ac4a8133fa [file] [log] [blame]
Kostya Kortchinsky36b34342017-04-27 20:21:16 +00001//===-- scudo_tls_linux.cpp -------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// Scudo thread local structure implementation for platforms supporting
11/// thread_local.
12///
13//===----------------------------------------------------------------------===//
14
15#include "sanitizer_common/sanitizer_platform.h"
16
Kostya Kortchinskyee0695762017-05-05 21:38:22 +000017#if SANITIZER_LINUX && !SANITIZER_ANDROID
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000018
19#include "scudo_tls.h"
20
21#include <limits.h>
22#include <pthread.h>
23
24namespace __scudo {
25
26static pthread_once_t GlobalInitialized = PTHREAD_ONCE_INIT;
27static pthread_key_t PThreadKey;
28
Kostya Kortchinskyee0695762017-05-05 21:38:22 +000029__attribute__((tls_model("initial-exec")))
30THREADLOCAL ThreadState ScudoThreadState = ThreadNotInitialized;
31__attribute__((tls_model("initial-exec")))
32THREADLOCAL ScudoThreadContext ThreadLocalContext;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000033
34static void teardownThread(void *Ptr) {
35 uptr Iteration = reinterpret_cast<uptr>(Ptr);
36 // The glibc POSIX thread-local-storage deallocation routine calls user
37 // provided destructors in a loop of PTHREAD_DESTRUCTOR_ITERATIONS.
38 // We want to be called last since other destructors might call free and the
39 // like, so we wait until PTHREAD_DESTRUCTOR_ITERATIONS before draining the
40 // quarantine and swallowing the cache.
41 if (Iteration < PTHREAD_DESTRUCTOR_ITERATIONS) {
42 pthread_setspecific(PThreadKey, reinterpret_cast<void *>(Iteration + 1));
43 return;
44 }
45 ThreadLocalContext.commitBack();
46 ScudoThreadState = ThreadTornDown;
47}
48
49
50static void initOnce() {
51 CHECK_EQ(pthread_key_create(&PThreadKey, teardownThread), 0);
52 initScudo();
53}
54
55void initThread() {
56 pthread_once(&GlobalInitialized, initOnce);
57 pthread_setspecific(PThreadKey, reinterpret_cast<void *>(1));
58 ThreadLocalContext.init();
59 ScudoThreadState = ThreadInitialized;
60}
61
62} // namespace __scudo
63
Kostya Kortchinskyee0695762017-05-05 21:38:22 +000064#endif // SANITIZER_LINUX && !SANITIZER_ANDROID