asan_thread.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. //===-- asan_thread.cpp ---------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is a part of AddressSanitizer, an address sanity checker.
  10. //
  11. // Thread-related code.
  12. //===----------------------------------------------------------------------===//
  13. #include "asan_allocator.h"
  14. #include "asan_interceptors.h"
  15. #include "asan_poisoning.h"
  16. #include "asan_stack.h"
  17. #include "asan_thread.h"
  18. #include "asan_mapping.h"
  19. #include "sanitizer_common/sanitizer_common.h"
  20. #include "sanitizer_common/sanitizer_placement_new.h"
  21. #include "sanitizer_common/sanitizer_stackdepot.h"
  22. #include "sanitizer_common/sanitizer_tls_get_addr.h"
  23. #include "lsan/lsan_common.h"
  24. namespace __asan {
  25. // AsanThreadContext implementation.
  26. void AsanThreadContext::OnCreated(void *arg) {
  27. CreateThreadContextArgs *args = static_cast<CreateThreadContextArgs*>(arg);
  28. if (args->stack)
  29. stack_id = StackDepotPut(*args->stack);
  30. thread = args->thread;
  31. thread->set_context(this);
  32. }
  33. void AsanThreadContext::OnFinished() {
  34. // Drop the link to the AsanThread object.
  35. thread = nullptr;
  36. }
  37. // MIPS requires aligned address
  38. static ALIGNED(16) char thread_registry_placeholder[sizeof(ThreadRegistry)];
  39. static ThreadRegistry *asan_thread_registry;
  40. static Mutex mu_for_thread_context;
  41. static LowLevelAllocator allocator_for_thread_context;
  42. static ThreadContextBase *GetAsanThreadContext(u32 tid) {
  43. Lock lock(&mu_for_thread_context);
  44. return new(allocator_for_thread_context) AsanThreadContext(tid);
  45. }
  46. ThreadRegistry &asanThreadRegistry() {
  47. static bool initialized;
  48. // Don't worry about thread_safety - this should be called when there is
  49. // a single thread.
  50. if (!initialized) {
  51. // Never reuse ASan threads: we store pointer to AsanThreadContext
  52. // in TSD and can't reliably tell when no more TSD destructors will
  53. // be called. It would be wrong to reuse AsanThreadContext for another
  54. // thread before all TSD destructors will be called for it.
  55. asan_thread_registry =
  56. new (thread_registry_placeholder) ThreadRegistry(GetAsanThreadContext);
  57. initialized = true;
  58. }
  59. return *asan_thread_registry;
  60. }
  61. AsanThreadContext *GetThreadContextByTidLocked(u32 tid) {
  62. return static_cast<AsanThreadContext *>(
  63. asanThreadRegistry().GetThreadLocked(tid));
  64. }
  65. // AsanThread implementation.
  66. AsanThread *AsanThread::Create(thread_callback_t start_routine, void *arg,
  67. u32 parent_tid, StackTrace *stack,
  68. bool detached) {
  69. uptr PageSize = GetPageSizeCached();
  70. uptr size = RoundUpTo(sizeof(AsanThread), PageSize);
  71. AsanThread *thread = (AsanThread*)MmapOrDie(size, __func__);
  72. thread->start_routine_ = start_routine;
  73. thread->arg_ = arg;
  74. AsanThreadContext::CreateThreadContextArgs args = {thread, stack};
  75. asanThreadRegistry().CreateThread(0, detached, parent_tid, &args);
  76. return thread;
  77. }
  78. void AsanThread::TSDDtor(void *tsd) {
  79. AsanThreadContext *context = (AsanThreadContext*)tsd;
  80. VReport(1, "T%d TSDDtor\n", context->tid);
  81. if (context->thread)
  82. context->thread->Destroy();
  83. }
  84. void AsanThread::Destroy() {
  85. int tid = this->tid();
  86. VReport(1, "T%d exited\n", tid);
  87. bool was_running =
  88. (asanThreadRegistry().FinishThread(tid) == ThreadStatusRunning);
  89. if (was_running) {
  90. if (AsanThread *thread = GetCurrentThread())
  91. CHECK_EQ(this, thread);
  92. malloc_storage().CommitBack();
  93. if (common_flags()->use_sigaltstack)
  94. UnsetAlternateSignalStack();
  95. FlushToDeadThreadStats(&stats_);
  96. // We also clear the shadow on thread destruction because
  97. // some code may still be executing in later TSD destructors
  98. // and we don't want it to have any poisoned stack.
  99. ClearShadowForThreadStackAndTLS();
  100. DeleteFakeStack(tid);
  101. } else {
  102. CHECK_NE(this, GetCurrentThread());
  103. }
  104. uptr size = RoundUpTo(sizeof(AsanThread), GetPageSizeCached());
  105. UnmapOrDie(this, size);
  106. if (was_running)
  107. DTLS_Destroy();
  108. }
  109. void AsanThread::StartSwitchFiber(FakeStack **fake_stack_save, uptr bottom,
  110. uptr size) {
  111. if (atomic_load(&stack_switching_, memory_order_relaxed)) {
  112. Report("ERROR: starting fiber switch while in fiber switch\n");
  113. Die();
  114. }
  115. next_stack_bottom_ = bottom;
  116. next_stack_top_ = bottom + size;
  117. atomic_store(&stack_switching_, 1, memory_order_release);
  118. FakeStack *current_fake_stack = fake_stack_;
  119. if (fake_stack_save)
  120. *fake_stack_save = fake_stack_;
  121. fake_stack_ = nullptr;
  122. SetTLSFakeStack(nullptr);
  123. // if fake_stack_save is null, the fiber will die, delete the fakestack
  124. if (!fake_stack_save && current_fake_stack)
  125. current_fake_stack->Destroy(this->tid());
  126. }
  127. void AsanThread::FinishSwitchFiber(FakeStack *fake_stack_save,
  128. uptr *bottom_old,
  129. uptr *size_old) {
  130. if (!atomic_load(&stack_switching_, memory_order_relaxed)) {
  131. Report("ERROR: finishing a fiber switch that has not started\n");
  132. Die();
  133. }
  134. if (fake_stack_save) {
  135. SetTLSFakeStack(fake_stack_save);
  136. fake_stack_ = fake_stack_save;
  137. }
  138. if (bottom_old)
  139. *bottom_old = stack_bottom_;
  140. if (size_old)
  141. *size_old = stack_top_ - stack_bottom_;
  142. stack_bottom_ = next_stack_bottom_;
  143. stack_top_ = next_stack_top_;
  144. atomic_store(&stack_switching_, 0, memory_order_release);
  145. next_stack_top_ = 0;
  146. next_stack_bottom_ = 0;
  147. }
  148. inline AsanThread::StackBounds AsanThread::GetStackBounds() const {
  149. if (!atomic_load(&stack_switching_, memory_order_acquire)) {
  150. // Make sure the stack bounds are fully initialized.
  151. if (stack_bottom_ >= stack_top_) return {0, 0};
  152. return {stack_bottom_, stack_top_};
  153. }
  154. char local;
  155. const uptr cur_stack = (uptr)&local;
  156. // Note: need to check next stack first, because FinishSwitchFiber
  157. // may be in process of overwriting stack_top_/bottom_. But in such case
  158. // we are already on the next stack.
  159. if (cur_stack >= next_stack_bottom_ && cur_stack < next_stack_top_)
  160. return {next_stack_bottom_, next_stack_top_};
  161. return {stack_bottom_, stack_top_};
  162. }
  163. uptr AsanThread::stack_top() {
  164. return GetStackBounds().top;
  165. }
  166. uptr AsanThread::stack_bottom() {
  167. return GetStackBounds().bottom;
  168. }
  169. uptr AsanThread::stack_size() {
  170. const auto bounds = GetStackBounds();
  171. return bounds.top - bounds.bottom;
  172. }
  173. // We want to create the FakeStack lazily on the first use, but not earlier
  174. // than the stack size is known and the procedure has to be async-signal safe.
  175. FakeStack *AsanThread::AsyncSignalSafeLazyInitFakeStack() {
  176. uptr stack_size = this->stack_size();
  177. if (stack_size == 0) // stack_size is not yet available, don't use FakeStack.
  178. return nullptr;
  179. uptr old_val = 0;
  180. // fake_stack_ has 3 states:
  181. // 0 -- not initialized
  182. // 1 -- being initialized
  183. // ptr -- initialized
  184. // This CAS checks if the state was 0 and if so changes it to state 1,
  185. // if that was successful, it initializes the pointer.
  186. if (atomic_compare_exchange_strong(
  187. reinterpret_cast<atomic_uintptr_t *>(&fake_stack_), &old_val, 1UL,
  188. memory_order_relaxed)) {
  189. uptr stack_size_log = Log2(RoundUpToPowerOfTwo(stack_size));
  190. CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
  191. stack_size_log =
  192. Min(stack_size_log, static_cast<uptr>(flags()->max_uar_stack_size_log));
  193. stack_size_log =
  194. Max(stack_size_log, static_cast<uptr>(flags()->min_uar_stack_size_log));
  195. fake_stack_ = FakeStack::Create(stack_size_log);
  196. DCHECK_EQ(GetCurrentThread(), this);
  197. SetTLSFakeStack(fake_stack_);
  198. return fake_stack_;
  199. }
  200. return nullptr;
  201. }
  202. void AsanThread::Init(const InitOptions *options) {
  203. DCHECK_NE(tid(), kInvalidTid);
  204. next_stack_top_ = next_stack_bottom_ = 0;
  205. atomic_store(&stack_switching_, false, memory_order_release);
  206. CHECK_EQ(this->stack_size(), 0U);
  207. SetThreadStackAndTls(options);
  208. if (stack_top_ != stack_bottom_) {
  209. CHECK_GT(this->stack_size(), 0U);
  210. CHECK(AddrIsInMem(stack_bottom_));
  211. CHECK(AddrIsInMem(stack_top_ - 1));
  212. }
  213. ClearShadowForThreadStackAndTLS();
  214. fake_stack_ = nullptr;
  215. if (__asan_option_detect_stack_use_after_return &&
  216. tid() == GetCurrentTidOrInvalid()) {
  217. // AsyncSignalSafeLazyInitFakeStack makes use of threadlocals and must be
  218. // called from the context of the thread it is initializing, not its parent.
  219. // Most platforms call AsanThread::Init on the newly-spawned thread, but
  220. // Fuchsia calls this function from the parent thread. To support that
  221. // approach, we avoid calling AsyncSignalSafeLazyInitFakeStack here; it will
  222. // be called by the new thread when it first attempts to access the fake
  223. // stack.
  224. AsyncSignalSafeLazyInitFakeStack();
  225. }
  226. int local = 0;
  227. VReport(1, "T%d: stack [%p,%p) size 0x%zx; local=%p\n", tid(),
  228. (void *)stack_bottom_, (void *)stack_top_, stack_top_ - stack_bottom_,
  229. (void *)&local);
  230. }
  231. // Fuchsia doesn't use ThreadStart.
  232. // asan_fuchsia.c definies CreateMainThread and SetThreadStackAndTls.
  233. #if !SANITIZER_FUCHSIA
  234. thread_return_t AsanThread::ThreadStart(tid_t os_id) {
  235. Init();
  236. asanThreadRegistry().StartThread(tid(), os_id, ThreadType::Regular, nullptr);
  237. if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
  238. if (!start_routine_) {
  239. // start_routine_ == 0 if we're on the main thread or on one of the
  240. // OS X libdispatch worker threads. But nobody is supposed to call
  241. // ThreadStart() for the worker threads.
  242. CHECK_EQ(tid(), 0);
  243. return 0;
  244. }
  245. thread_return_t res = start_routine_(arg_);
  246. // On POSIX systems we defer this to the TSD destructor. LSan will consider
  247. // the thread's memory as non-live from the moment we call Destroy(), even
  248. // though that memory might contain pointers to heap objects which will be
  249. // cleaned up by a user-defined TSD destructor. Thus, calling Destroy() before
  250. // the TSD destructors have run might cause false positives in LSan.
  251. if (!SANITIZER_POSIX)
  252. this->Destroy();
  253. return res;
  254. }
  255. AsanThread *CreateMainThread() {
  256. AsanThread *main_thread = AsanThread::Create(
  257. /* start_routine */ nullptr, /* arg */ nullptr, /* parent_tid */ kMainTid,
  258. /* stack */ nullptr, /* detached */ true);
  259. SetCurrentThread(main_thread);
  260. main_thread->ThreadStart(internal_getpid());
  261. return main_thread;
  262. }
  263. // This implementation doesn't use the argument, which is just passed down
  264. // from the caller of Init (which see, above). It's only there to support
  265. // OS-specific implementations that need more information passed through.
  266. void AsanThread::SetThreadStackAndTls(const InitOptions *options) {
  267. DCHECK_EQ(options, nullptr);
  268. uptr tls_size = 0;
  269. uptr stack_size = 0;
  270. GetThreadStackAndTls(tid() == kMainTid, &stack_bottom_, &stack_size,
  271. &tls_begin_, &tls_size);
  272. stack_top_ = RoundDownTo(stack_bottom_ + stack_size, ASAN_SHADOW_GRANULARITY);
  273. tls_end_ = tls_begin_ + tls_size;
  274. dtls_ = DTLS_Get();
  275. if (stack_top_ != stack_bottom_) {
  276. int local;
  277. CHECK(AddrIsInStack((uptr)&local));
  278. }
  279. }
  280. #endif // !SANITIZER_FUCHSIA
  281. void AsanThread::ClearShadowForThreadStackAndTLS() {
  282. if (stack_top_ != stack_bottom_)
  283. PoisonShadow(stack_bottom_, stack_top_ - stack_bottom_, 0);
  284. if (tls_begin_ != tls_end_) {
  285. uptr tls_begin_aligned = RoundDownTo(tls_begin_, ASAN_SHADOW_GRANULARITY);
  286. uptr tls_end_aligned = RoundUpTo(tls_end_, ASAN_SHADOW_GRANULARITY);
  287. FastPoisonShadow(tls_begin_aligned, tls_end_aligned - tls_begin_aligned, 0);
  288. }
  289. }
  290. bool AsanThread::GetStackFrameAccessByAddr(uptr addr,
  291. StackFrameAccess *access) {
  292. if (stack_top_ == stack_bottom_)
  293. return false;
  294. uptr bottom = 0;
  295. if (AddrIsInStack(addr)) {
  296. bottom = stack_bottom();
  297. } else if (FakeStack *fake_stack = get_fake_stack()) {
  298. bottom = fake_stack->AddrIsInFakeStack(addr);
  299. CHECK(bottom);
  300. access->offset = addr - bottom;
  301. access->frame_pc = ((uptr*)bottom)[2];
  302. access->frame_descr = (const char *)((uptr*)bottom)[1];
  303. return true;
  304. }
  305. uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
  306. uptr mem_ptr = RoundDownTo(aligned_addr, ASAN_SHADOW_GRANULARITY);
  307. u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
  308. u8 *shadow_bottom = (u8*)MemToShadow(bottom);
  309. while (shadow_ptr >= shadow_bottom &&
  310. *shadow_ptr != kAsanStackLeftRedzoneMagic) {
  311. shadow_ptr--;
  312. mem_ptr -= ASAN_SHADOW_GRANULARITY;
  313. }
  314. while (shadow_ptr >= shadow_bottom &&
  315. *shadow_ptr == kAsanStackLeftRedzoneMagic) {
  316. shadow_ptr--;
  317. mem_ptr -= ASAN_SHADOW_GRANULARITY;
  318. }
  319. if (shadow_ptr < shadow_bottom) {
  320. return false;
  321. }
  322. uptr *ptr = (uptr *)(mem_ptr + ASAN_SHADOW_GRANULARITY);
  323. CHECK(ptr[0] == kCurrentStackFrameMagic);
  324. access->offset = addr - (uptr)ptr;
  325. access->frame_pc = ptr[2];
  326. access->frame_descr = (const char*)ptr[1];
  327. return true;
  328. }
  329. uptr AsanThread::GetStackVariableShadowStart(uptr addr) {
  330. uptr bottom = 0;
  331. if (AddrIsInStack(addr)) {
  332. bottom = stack_bottom();
  333. } else if (FakeStack *fake_stack = get_fake_stack()) {
  334. bottom = fake_stack->AddrIsInFakeStack(addr);
  335. if (bottom == 0) {
  336. return 0;
  337. }
  338. } else {
  339. return 0;
  340. }
  341. uptr aligned_addr = RoundDownTo(addr, SANITIZER_WORDSIZE / 8); // align addr.
  342. u8 *shadow_ptr = (u8*)MemToShadow(aligned_addr);
  343. u8 *shadow_bottom = (u8*)MemToShadow(bottom);
  344. while (shadow_ptr >= shadow_bottom &&
  345. (*shadow_ptr != kAsanStackLeftRedzoneMagic &&
  346. *shadow_ptr != kAsanStackMidRedzoneMagic &&
  347. *shadow_ptr != kAsanStackRightRedzoneMagic))
  348. shadow_ptr--;
  349. return (uptr)shadow_ptr + 1;
  350. }
  351. bool AsanThread::AddrIsInStack(uptr addr) {
  352. const auto bounds = GetStackBounds();
  353. return addr >= bounds.bottom && addr < bounds.top;
  354. }
  355. static bool ThreadStackContainsAddress(ThreadContextBase *tctx_base,
  356. void *addr) {
  357. AsanThreadContext *tctx = static_cast<AsanThreadContext *>(tctx_base);
  358. AsanThread *t = tctx->thread;
  359. if (!t)
  360. return false;
  361. if (t->AddrIsInStack((uptr)addr))
  362. return true;
  363. FakeStack *fake_stack = t->get_fake_stack();
  364. if (!fake_stack)
  365. return false;
  366. return fake_stack->AddrIsInFakeStack((uptr)addr);
  367. }
  368. AsanThread *GetCurrentThread() {
  369. AsanThreadContext *context =
  370. reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
  371. if (!context) {
  372. if (SANITIZER_ANDROID) {
  373. // On Android, libc constructor is called _after_ asan_init, and cleans up
  374. // TSD. Try to figure out if this is still the main thread by the stack
  375. // address. We are not entirely sure that we have correct main thread
  376. // limits, so only do this magic on Android, and only if the found thread
  377. // is the main thread.
  378. AsanThreadContext *tctx = GetThreadContextByTidLocked(kMainTid);
  379. if (tctx && ThreadStackContainsAddress(tctx, &context)) {
  380. SetCurrentThread(tctx->thread);
  381. return tctx->thread;
  382. }
  383. }
  384. return nullptr;
  385. }
  386. return context->thread;
  387. }
  388. void SetCurrentThread(AsanThread *t) {
  389. CHECK(t->context());
  390. VReport(2, "SetCurrentThread: %p for thread %p\n", (void *)t->context(),
  391. (void *)GetThreadSelf());
  392. // Make sure we do not reset the current AsanThread.
  393. CHECK_EQ(0, AsanTSDGet());
  394. AsanTSDSet(t->context());
  395. CHECK_EQ(t->context(), AsanTSDGet());
  396. }
  397. u32 GetCurrentTidOrInvalid() {
  398. AsanThread *t = GetCurrentThread();
  399. return t ? t->tid() : kInvalidTid;
  400. }
  401. AsanThread *FindThreadByStackAddress(uptr addr) {
  402. asanThreadRegistry().CheckLocked();
  403. AsanThreadContext *tctx = static_cast<AsanThreadContext *>(
  404. asanThreadRegistry().FindThreadContextLocked(ThreadStackContainsAddress,
  405. (void *)addr));
  406. return tctx ? tctx->thread : nullptr;
  407. }
  408. void EnsureMainThreadIDIsCorrect() {
  409. AsanThreadContext *context =
  410. reinterpret_cast<AsanThreadContext *>(AsanTSDGet());
  411. if (context && (context->tid == kMainTid))
  412. context->os_id = GetTid();
  413. }
  414. __asan::AsanThread *GetAsanThreadByOsIDLocked(tid_t os_id) {
  415. __asan::AsanThreadContext *context = static_cast<__asan::AsanThreadContext *>(
  416. __asan::asanThreadRegistry().FindThreadContextByOsIDLocked(os_id));
  417. if (!context) return nullptr;
  418. return context->thread;
  419. }
  420. } // namespace __asan
  421. // --- Implementation of LSan-specific functions --- {{{1
  422. namespace __lsan {
  423. void LockThreadRegistry() { __asan::asanThreadRegistry().Lock(); }
  424. void UnlockThreadRegistry() { __asan::asanThreadRegistry().Unlock(); }
  425. static ThreadRegistry *GetAsanThreadRegistryLocked() {
  426. __asan::asanThreadRegistry().CheckLocked();
  427. return &__asan::asanThreadRegistry();
  428. }
  429. void EnsureMainThreadIDIsCorrect() { __asan::EnsureMainThreadIDIsCorrect(); }
  430. bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
  431. uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
  432. uptr *cache_end, DTLS **dtls) {
  433. __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
  434. if (!t) return false;
  435. *stack_begin = t->stack_bottom();
  436. *stack_end = t->stack_top();
  437. *tls_begin = t->tls_begin();
  438. *tls_end = t->tls_end();
  439. // ASan doesn't keep allocator caches in TLS, so these are unused.
  440. *cache_begin = 0;
  441. *cache_end = 0;
  442. *dtls = t->dtls();
  443. return true;
  444. }
  445. void GetAllThreadAllocatorCachesLocked(InternalMmapVector<uptr> *caches) {}
  446. void GetThreadExtraStackRangesLocked(tid_t os_id,
  447. InternalMmapVector<Range> *ranges) {
  448. __asan::AsanThread *t = __asan::GetAsanThreadByOsIDLocked(os_id);
  449. if (!t)
  450. return;
  451. __asan::FakeStack *fake_stack = t->get_fake_stack();
  452. if (!fake_stack)
  453. return;
  454. fake_stack->ForEachFakeFrame(
  455. [](uptr begin, uptr end, void *arg) {
  456. reinterpret_cast<InternalMmapVector<Range> *>(arg)->push_back(
  457. {begin, end});
  458. },
  459. ranges);
  460. }
  461. void GetThreadExtraStackRangesLocked(InternalMmapVector<Range> *ranges) {
  462. GetAsanThreadRegistryLocked()->RunCallbackForEachThreadLocked(
  463. [](ThreadContextBase *tctx, void *arg) {
  464. GetThreadExtraStackRangesLocked(
  465. tctx->os_id, reinterpret_cast<InternalMmapVector<Range> *>(arg));
  466. },
  467. ranges);
  468. }
  469. void GetAdditionalThreadContextPtrsLocked(InternalMmapVector<uptr> *ptrs) {
  470. GetAsanThreadRegistryLocked()->RunCallbackForEachThreadLocked(
  471. [](ThreadContextBase *tctx, void *ptrs) {
  472. // Look for the arg pointer of threads that have been created or are
  473. // running. This is necessary to prevent false positive leaks due to the
  474. // AsanThread holding the only live reference to a heap object. This
  475. // can happen because the `pthread_create()` interceptor doesn't wait
  476. // for the child thread to start before returning and thus loosing the
  477. // the only live reference to the heap object on the stack.
  478. __asan::AsanThreadContext *atctx =
  479. static_cast<__asan::AsanThreadContext *>(tctx);
  480. // Note ThreadStatusRunning is required because there is a small window
  481. // where the thread status switches to `ThreadStatusRunning` but the
  482. // `arg` pointer still isn't on the stack yet.
  483. if (atctx->status != ThreadStatusCreated &&
  484. atctx->status != ThreadStatusRunning)
  485. return;
  486. uptr thread_arg = reinterpret_cast<uptr>(atctx->thread->get_arg());
  487. if (!thread_arg)
  488. return;
  489. auto ptrsVec = reinterpret_cast<InternalMmapVector<uptr> *>(ptrs);
  490. ptrsVec->push_back(thread_arg);
  491. },
  492. ptrs);
  493. }
  494. void GetRunningThreadsLocked(InternalMmapVector<tid_t> *threads) {
  495. GetAsanThreadRegistryLocked()->RunCallbackForEachThreadLocked(
  496. [](ThreadContextBase *tctx, void *threads) {
  497. if (tctx->status == ThreadStatusRunning)
  498. reinterpret_cast<InternalMmapVector<tid_t> *>(threads)->push_back(
  499. tctx->os_id);
  500. },
  501. threads);
  502. }
  503. void FinishThreadLocked(u32 tid) {
  504. GetAsanThreadRegistryLocked()->FinishThread(tid);
  505. }
  506. } // namespace __lsan
  507. // ---------------------- Interface ---------------- {{{1
  508. using namespace __asan;
  509. extern "C" {
  510. SANITIZER_INTERFACE_ATTRIBUTE
  511. void __sanitizer_start_switch_fiber(void **fakestacksave, const void *bottom,
  512. uptr size) {
  513. AsanThread *t = GetCurrentThread();
  514. if (!t) {
  515. VReport(1, "__asan_start_switch_fiber called from unknown thread\n");
  516. return;
  517. }
  518. t->StartSwitchFiber((FakeStack**)fakestacksave, (uptr)bottom, size);
  519. }
  520. SANITIZER_INTERFACE_ATTRIBUTE
  521. void __sanitizer_finish_switch_fiber(void* fakestack,
  522. const void **bottom_old,
  523. uptr *size_old) {
  524. AsanThread *t = GetCurrentThread();
  525. if (!t) {
  526. VReport(1, "__asan_finish_switch_fiber called from unknown thread\n");
  527. return;
  528. }
  529. t->FinishSwitchFiber((FakeStack*)fakestack,
  530. (uptr*)bottom_old,
  531. (uptr*)size_old);
  532. }
  533. }