blob: 3453367f8a5307947aeb460e74911c8540ce562b [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
17#if SANITIZER_LINUX
18
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
29thread_local ThreadState ScudoThreadState = ThreadNotInitialized;
30thread_local ScudoThreadContext ThreadLocalContext;
31
32static void teardownThread(void *Ptr) {
33 uptr Iteration = reinterpret_cast<uptr>(Ptr);
34 // The glibc POSIX thread-local-storage deallocation routine calls user
35 // provided destructors in a loop of PTHREAD_DESTRUCTOR_ITERATIONS.
36 // We want to be called last since other destructors might call free and the
37 // like, so we wait until PTHREAD_DESTRUCTOR_ITERATIONS before draining the
38 // quarantine and swallowing the cache.
39 if (Iteration < PTHREAD_DESTRUCTOR_ITERATIONS) {
40 pthread_setspecific(PThreadKey, reinterpret_cast<void *>(Iteration + 1));
41 return;
42 }
43 ThreadLocalContext.commitBack();
44 ScudoThreadState = ThreadTornDown;
45}
46
47
48static void initOnce() {
49 CHECK_EQ(pthread_key_create(&PThreadKey, teardownThread), 0);
50 initScudo();
51}
52
53void initThread() {
54 pthread_once(&GlobalInitialized, initOnce);
55 pthread_setspecific(PThreadKey, reinterpret_cast<void *>(1));
56 ThreadLocalContext.init();
57 ScudoThreadState = ThreadInitialized;
58}
59
60} // namespace __scudo
61
62#endif // SANITIZER_LINUX