tsan_platform_linux.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //===-- tsan_platform_linux.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 ThreadSanitizer (TSan), a race detector.
  10. //
  11. // Linux- and BSD-specific code.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_common/sanitizer_platform.h"
  14. #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD
  15. #include "sanitizer_common/sanitizer_common.h"
  16. #include "sanitizer_common/sanitizer_libc.h"
  17. #include "sanitizer_common/sanitizer_linux.h"
  18. #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
  19. #include "sanitizer_common/sanitizer_platform_limits_posix.h"
  20. #include "sanitizer_common/sanitizer_posix.h"
  21. #include "sanitizer_common/sanitizer_procmaps.h"
  22. #include "sanitizer_common/sanitizer_stackdepot.h"
  23. #include "sanitizer_common/sanitizer_stoptheworld.h"
  24. #include "tsan_flags.h"
  25. #include "tsan_platform.h"
  26. #include "tsan_rtl.h"
  27. #include <fcntl.h>
  28. #include <pthread.h>
  29. #include <signal.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <stdarg.h>
  34. #include <sys/mman.h>
  35. #if SANITIZER_LINUX
  36. #include <sys/personality.h>
  37. #include <setjmp.h>
  38. #endif
  39. #include <sys/syscall.h>
  40. #include <sys/socket.h>
  41. #include <sys/time.h>
  42. #include <sys/types.h>
  43. #include <sys/resource.h>
  44. #include <sys/stat.h>
  45. #include <unistd.h>
  46. #include <sched.h>
  47. #include <dlfcn.h>
  48. #if SANITIZER_LINUX
  49. #define __need_res_state
  50. #include <resolv.h>
  51. #endif
  52. #ifdef sa_handler
  53. # undef sa_handler
  54. #endif
  55. #ifdef sa_sigaction
  56. # undef sa_sigaction
  57. #endif
  58. #if SANITIZER_FREEBSD
  59. extern "C" void *__libc_stack_end;
  60. void *__libc_stack_end = 0;
  61. #endif
  62. #if SANITIZER_LINUX && (defined(__aarch64__) || defined(__loongarch_lp64)) && \
  63. !SANITIZER_GO
  64. # define INIT_LONGJMP_XOR_KEY 1
  65. #else
  66. # define INIT_LONGJMP_XOR_KEY 0
  67. #endif
  68. #if INIT_LONGJMP_XOR_KEY
  69. #include "interception/interception.h"
  70. // Must be declared outside of other namespaces.
  71. DECLARE_REAL(int, _setjmp, void *env)
  72. #endif
  73. namespace __tsan {
  74. #if INIT_LONGJMP_XOR_KEY
  75. static void InitializeLongjmpXorKey();
  76. static uptr longjmp_xor_key;
  77. #endif
  78. // Runtime detected VMA size.
  79. uptr vmaSize;
  80. enum {
  81. MemTotal,
  82. MemShadow,
  83. MemMeta,
  84. MemFile,
  85. MemMmap,
  86. MemHeap,
  87. MemOther,
  88. MemCount,
  89. };
  90. void FillProfileCallback(uptr p, uptr rss, bool file, uptr *mem) {
  91. mem[MemTotal] += rss;
  92. if (p >= ShadowBeg() && p < ShadowEnd())
  93. mem[MemShadow] += rss;
  94. else if (p >= MetaShadowBeg() && p < MetaShadowEnd())
  95. mem[MemMeta] += rss;
  96. else if ((p >= LoAppMemBeg() && p < LoAppMemEnd()) ||
  97. (p >= MidAppMemBeg() && p < MidAppMemEnd()) ||
  98. (p >= HiAppMemBeg() && p < HiAppMemEnd()))
  99. mem[file ? MemFile : MemMmap] += rss;
  100. else if (p >= HeapMemBeg() && p < HeapMemEnd())
  101. mem[MemHeap] += rss;
  102. else
  103. mem[MemOther] += rss;
  104. }
  105. void WriteMemoryProfile(char *buf, uptr buf_size, u64 uptime_ns) {
  106. uptr mem[MemCount];
  107. internal_memset(mem, 0, sizeof(mem));
  108. GetMemoryProfile(FillProfileCallback, mem);
  109. auto meta = ctx->metamap.GetMemoryStats();
  110. StackDepotStats stacks = StackDepotGetStats();
  111. uptr nthread, nlive;
  112. ctx->thread_registry.GetNumberOfThreads(&nthread, &nlive);
  113. uptr trace_mem;
  114. {
  115. Lock l(&ctx->slot_mtx);
  116. trace_mem = ctx->trace_part_total_allocated * sizeof(TracePart);
  117. }
  118. uptr internal_stats[AllocatorStatCount];
  119. internal_allocator()->GetStats(internal_stats);
  120. // All these are allocated from the common mmap region.
  121. mem[MemMmap] -= meta.mem_block + meta.sync_obj + trace_mem +
  122. stacks.allocated + internal_stats[AllocatorStatMapped];
  123. if (s64(mem[MemMmap]) < 0)
  124. mem[MemMmap] = 0;
  125. internal_snprintf(
  126. buf, buf_size,
  127. "==%zu== %llus [%zu]: RSS %zd MB: shadow:%zd meta:%zd file:%zd"
  128. " mmap:%zd heap:%zd other:%zd intalloc:%zd memblocks:%zd syncobj:%zu"
  129. " trace:%zu stacks=%zd threads=%zu/%zu\n",
  130. internal_getpid(), uptime_ns / (1000 * 1000 * 1000), ctx->global_epoch,
  131. mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20,
  132. mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemHeap] >> 20,
  133. mem[MemOther] >> 20, internal_stats[AllocatorStatMapped] >> 20,
  134. meta.mem_block >> 20, meta.sync_obj >> 20, trace_mem >> 20,
  135. stacks.allocated >> 20, nlive, nthread);
  136. }
  137. #if !SANITIZER_GO
  138. // Mark shadow for .rodata sections with the special Shadow::kRodata marker.
  139. // Accesses to .rodata can't race, so this saves time, memory and trace space.
  140. static NOINLINE void MapRodata(char* buffer, uptr size) {
  141. // First create temp file.
  142. const char *tmpdir = GetEnv("TMPDIR");
  143. if (tmpdir == 0)
  144. tmpdir = GetEnv("TEST_TMPDIR");
  145. #ifdef P_tmpdir
  146. if (tmpdir == 0)
  147. tmpdir = P_tmpdir;
  148. #endif
  149. if (tmpdir == 0)
  150. return;
  151. internal_snprintf(buffer, size, "%s/tsan.rodata.%d",
  152. tmpdir, (int)internal_getpid());
  153. uptr openrv = internal_open(buffer, O_RDWR | O_CREAT | O_EXCL, 0600);
  154. if (internal_iserror(openrv))
  155. return;
  156. internal_unlink(buffer); // Unlink it now, so that we can reuse the buffer.
  157. fd_t fd = openrv;
  158. // Fill the file with Shadow::kRodata.
  159. const uptr kMarkerSize = 512 * 1024 / sizeof(RawShadow);
  160. InternalMmapVector<RawShadow> marker(kMarkerSize);
  161. // volatile to prevent insertion of memset
  162. for (volatile RawShadow *p = marker.data(); p < marker.data() + kMarkerSize;
  163. p++)
  164. *p = Shadow::kRodata;
  165. internal_write(fd, marker.data(), marker.size() * sizeof(RawShadow));
  166. // Map the file into memory.
  167. uptr page = internal_mmap(0, GetPageSizeCached(), PROT_READ | PROT_WRITE,
  168. MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
  169. if (internal_iserror(page)) {
  170. internal_close(fd);
  171. return;
  172. }
  173. // Map the file into shadow of .rodata sections.
  174. MemoryMappingLayout proc_maps(/*cache_enabled*/true);
  175. // Reusing the buffer 'buffer'.
  176. MemoryMappedSegment segment(buffer, size);
  177. while (proc_maps.Next(&segment)) {
  178. if (segment.filename[0] != 0 && segment.filename[0] != '[' &&
  179. segment.IsReadable() && segment.IsExecutable() &&
  180. !segment.IsWritable() && IsAppMem(segment.start)) {
  181. // Assume it's .rodata
  182. char *shadow_start = (char *)MemToShadow(segment.start);
  183. char *shadow_end = (char *)MemToShadow(segment.end);
  184. for (char *p = shadow_start; p < shadow_end;
  185. p += marker.size() * sizeof(RawShadow)) {
  186. internal_mmap(
  187. p, Min<uptr>(marker.size() * sizeof(RawShadow), shadow_end - p),
  188. PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0);
  189. }
  190. }
  191. }
  192. internal_close(fd);
  193. }
  194. void InitializeShadowMemoryPlatform() {
  195. char buffer[256]; // Keep in a different frame.
  196. MapRodata(buffer, sizeof(buffer));
  197. }
  198. #endif // #if !SANITIZER_GO
  199. # if !SANITIZER_GO
  200. static void ReExecIfNeeded() {
  201. // Go maps shadow memory lazily and works fine with limited address space.
  202. // Unlimited stack is not a problem as well, because the executable
  203. // is not compiled with -pie.
  204. bool reexec = false;
  205. // TSan doesn't play well with unlimited stack size (as stack
  206. // overlaps with shadow memory). If we detect unlimited stack size,
  207. // we re-exec the program with limited stack size as a best effort.
  208. if (StackSizeIsUnlimited()) {
  209. const uptr kMaxStackSize = 32 * 1024 * 1024;
  210. VReport(1,
  211. "Program is run with unlimited stack size, which wouldn't "
  212. "work with ThreadSanitizer.\n"
  213. "Re-execing with stack size limited to %zd bytes.\n",
  214. kMaxStackSize);
  215. SetStackSizeLimitInBytes(kMaxStackSize);
  216. reexec = true;
  217. }
  218. if (!AddressSpaceIsUnlimited()) {
  219. Report(
  220. "WARNING: Program is run with limited virtual address space,"
  221. " which wouldn't work with ThreadSanitizer.\n");
  222. Report("Re-execing with unlimited virtual address space.\n");
  223. SetAddressSpaceUnlimited();
  224. reexec = true;
  225. }
  226. # if SANITIZER_LINUX
  227. // ASLR personality check.
  228. int old_personality = personality(0xffffffff);
  229. bool aslr_on =
  230. (old_personality != -1) && ((old_personality & ADDR_NO_RANDOMIZE) == 0);
  231. # if SANITIZER_ANDROID && (defined(__aarch64__) || defined(__x86_64__))
  232. // After patch "arm64: mm: support ARCH_MMAP_RND_BITS." is introduced in
  233. // linux kernel, the random gap between stack and mapped area is increased
  234. // from 128M to 36G on 39-bit aarch64. As it is almost impossible to cover
  235. // this big range, we should disable randomized virtual space on aarch64.
  236. if (aslr_on) {
  237. VReport(1,
  238. "WARNING: Program is run with randomized virtual address "
  239. "space, which wouldn't work with ThreadSanitizer on Android.\n"
  240. "Re-execing with fixed virtual address space.\n");
  241. CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
  242. reexec = true;
  243. }
  244. # endif
  245. if (reexec) {
  246. // Don't check the address space since we're going to re-exec anyway.
  247. } else if (!CheckAndProtect(false, false, false)) {
  248. if (aslr_on) {
  249. // Disable ASLR if the memory layout was incompatible.
  250. // Alternatively, we could just keep re-execing until we get lucky
  251. // with a compatible randomized layout, but the risk is that if it's
  252. // not an ASLR-related issue, we will be stuck in an infinite loop of
  253. // re-execing (unless we change ReExec to pass a parameter of the
  254. // number of retries allowed.)
  255. VReport(1,
  256. "WARNING: ThreadSanitizer: memory layout is incompatible, "
  257. "possibly due to high-entropy ASLR.\n"
  258. "Re-execing with fixed virtual address space.\n"
  259. "N.B. reducing ASLR entropy is preferable.\n");
  260. CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
  261. reexec = true;
  262. } else {
  263. VReport(1,
  264. "FATAL: ThreadSanitizer: memory layout is incompatible, "
  265. "even though ASLR is disabled.\n"
  266. "Please file a bug.\n");
  267. Die();
  268. }
  269. }
  270. # endif // SANITIZER_LINUX
  271. if (reexec)
  272. ReExec();
  273. }
  274. # endif
  275. void InitializePlatformEarly() {
  276. vmaSize =
  277. (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1);
  278. #if defined(__aarch64__)
  279. # if !SANITIZER_GO
  280. if (vmaSize != 39 && vmaSize != 42 && vmaSize != 48) {
  281. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  282. Printf("FATAL: Found %zd - Supported 39, 42 and 48\n", vmaSize);
  283. Die();
  284. }
  285. #else
  286. if (vmaSize != 48) {
  287. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  288. Printf("FATAL: Found %zd - Supported 48\n", vmaSize);
  289. Die();
  290. }
  291. #endif
  292. #elif SANITIZER_LOONGARCH64
  293. # if !SANITIZER_GO
  294. if (vmaSize != 47) {
  295. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  296. Printf("FATAL: Found %zd - Supported 47\n", vmaSize);
  297. Die();
  298. }
  299. # else
  300. if (vmaSize != 47) {
  301. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  302. Printf("FATAL: Found %zd - Supported 47\n", vmaSize);
  303. Die();
  304. }
  305. # endif
  306. #elif defined(__powerpc64__)
  307. # if !SANITIZER_GO
  308. if (vmaSize != 44 && vmaSize != 46 && vmaSize != 47) {
  309. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  310. Printf("FATAL: Found %zd - Supported 44, 46, and 47\n", vmaSize);
  311. Die();
  312. }
  313. # else
  314. if (vmaSize != 46 && vmaSize != 47) {
  315. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  316. Printf("FATAL: Found %zd - Supported 46, and 47\n", vmaSize);
  317. Die();
  318. }
  319. # endif
  320. #elif defined(__mips64)
  321. # if !SANITIZER_GO
  322. if (vmaSize != 40) {
  323. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  324. Printf("FATAL: Found %zd - Supported 40\n", vmaSize);
  325. Die();
  326. }
  327. # else
  328. if (vmaSize != 47) {
  329. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  330. Printf("FATAL: Found %zd - Supported 47\n", vmaSize);
  331. Die();
  332. }
  333. # endif
  334. # elif SANITIZER_RISCV64
  335. // the bottom half of vma is allocated for userspace
  336. vmaSize = vmaSize + 1;
  337. # if !SANITIZER_GO
  338. if (vmaSize != 39 && vmaSize != 48) {
  339. Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
  340. Printf("FATAL: Found %zd - Supported 39 and 48\n", vmaSize);
  341. Die();
  342. }
  343. # endif
  344. # endif
  345. # if !SANITIZER_GO
  346. ReExecIfNeeded();
  347. # endif
  348. }
  349. void InitializePlatform() {
  350. DisableCoreDumperIfNecessary();
  351. // Go maps shadow memory lazily and works fine with limited address space.
  352. // Unlimited stack is not a problem as well, because the executable
  353. // is not compiled with -pie.
  354. #if !SANITIZER_GO
  355. {
  356. # if SANITIZER_LINUX && (defined(__aarch64__) || defined(__loongarch_lp64))
  357. // Initialize the xor key used in {sig}{set,long}jump.
  358. InitializeLongjmpXorKey();
  359. # endif
  360. }
  361. // Earlier initialization steps already re-exec'ed until we got a compatible
  362. // memory layout, so we don't expect any more issues here.
  363. if (!CheckAndProtect(true, true, true)) {
  364. Printf(
  365. "FATAL: ThreadSanitizer: unexpectedly found incompatible memory "
  366. "layout.\n");
  367. Printf("FATAL: Please file a bug.\n");
  368. Die();
  369. }
  370. InitTlsSize();
  371. #endif // !SANITIZER_GO
  372. }
  373. #if !SANITIZER_GO
  374. // Extract file descriptors passed to glibc internal __res_iclose function.
  375. // This is required to properly "close" the fds, because we do not see internal
  376. // closes within glibc. The code is a pure hack.
  377. int ExtractResolvFDs(void *state, int *fds, int nfd) {
  378. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  379. int cnt = 0;
  380. struct __res_state *statp = (struct __res_state*)state;
  381. for (int i = 0; i < MAXNS && cnt < nfd; i++) {
  382. if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
  383. fds[cnt++] = statp->_u._ext.nssocks[i];
  384. }
  385. return cnt;
  386. #else
  387. return 0;
  388. #endif
  389. }
  390. // Extract file descriptors passed via UNIX domain sockets.
  391. // This is required to properly handle "open" of these fds.
  392. // see 'man recvmsg' and 'man 3 cmsg'.
  393. int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) {
  394. int res = 0;
  395. msghdr *msg = (msghdr*)msgp;
  396. struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
  397. for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
  398. if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
  399. continue;
  400. int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]);
  401. for (int i = 0; i < n; i++) {
  402. fds[res++] = ((int*)CMSG_DATA(cmsg))[i];
  403. if (res == nfd)
  404. return res;
  405. }
  406. }
  407. return res;
  408. }
  409. // Reverse operation of libc stack pointer mangling
  410. static uptr UnmangleLongJmpSp(uptr mangled_sp) {
  411. #if defined(__x86_64__)
  412. # if SANITIZER_LINUX
  413. // Reverse of:
  414. // xor %fs:0x30, %rsi
  415. // rol $0x11, %rsi
  416. uptr sp;
  417. asm("ror $0x11, %0 \n"
  418. "xor %%fs:0x30, %0 \n"
  419. : "=r" (sp)
  420. : "0" (mangled_sp));
  421. return sp;
  422. # else
  423. return mangled_sp;
  424. # endif
  425. #elif defined(__aarch64__)
  426. # if SANITIZER_LINUX
  427. return mangled_sp ^ longjmp_xor_key;
  428. # else
  429. return mangled_sp;
  430. # endif
  431. #elif defined(__loongarch_lp64)
  432. return mangled_sp ^ longjmp_xor_key;
  433. #elif defined(__powerpc64__)
  434. // Reverse of:
  435. // ld r4, -28696(r13)
  436. // xor r4, r3, r4
  437. uptr xor_key;
  438. asm("ld %0, -28696(%%r13)" : "=r" (xor_key));
  439. return mangled_sp ^ xor_key;
  440. #elif defined(__mips__)
  441. return mangled_sp;
  442. # elif SANITIZER_RISCV64
  443. return mangled_sp;
  444. # elif defined(__s390x__)
  445. // tcbhead_t.stack_guard
  446. uptr xor_key = ((uptr *)__builtin_thread_pointer())[5];
  447. return mangled_sp ^ xor_key;
  448. # else
  449. # error "Unknown platform"
  450. # endif
  451. }
  452. #if SANITIZER_NETBSD
  453. # ifdef __x86_64__
  454. # define LONG_JMP_SP_ENV_SLOT 6
  455. # else
  456. # error unsupported
  457. # endif
  458. #elif defined(__powerpc__)
  459. # define LONG_JMP_SP_ENV_SLOT 0
  460. #elif SANITIZER_FREEBSD
  461. # ifdef __aarch64__
  462. # define LONG_JMP_SP_ENV_SLOT 1
  463. # else
  464. # define LONG_JMP_SP_ENV_SLOT 2
  465. # endif
  466. #elif SANITIZER_LINUX
  467. # ifdef __aarch64__
  468. # define LONG_JMP_SP_ENV_SLOT 13
  469. # elif defined(__loongarch__)
  470. # define LONG_JMP_SP_ENV_SLOT 1
  471. # elif defined(__mips64)
  472. # define LONG_JMP_SP_ENV_SLOT 1
  473. # elif SANITIZER_RISCV64
  474. # define LONG_JMP_SP_ENV_SLOT 13
  475. # elif defined(__s390x__)
  476. # define LONG_JMP_SP_ENV_SLOT 9
  477. # else
  478. # define LONG_JMP_SP_ENV_SLOT 6
  479. # endif
  480. #endif
  481. uptr ExtractLongJmpSp(uptr *env) {
  482. uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT];
  483. return UnmangleLongJmpSp(mangled_sp);
  484. }
  485. #if INIT_LONGJMP_XOR_KEY
  486. // GLIBC mangles the function pointers in jmp_buf (used in {set,long}*jmp
  487. // functions) by XORing them with a random key. For AArch64 it is a global
  488. // variable rather than a TCB one (as for x86_64/powerpc). We obtain the key by
  489. // issuing a setjmp and XORing the SP pointer values to derive the key.
  490. static void InitializeLongjmpXorKey() {
  491. // 1. Call REAL(setjmp), which stores the mangled SP in env.
  492. jmp_buf env;
  493. REAL(_setjmp)(env);
  494. // 2. Retrieve vanilla/mangled SP.
  495. uptr sp;
  496. #ifdef __loongarch__
  497. asm("move %0, $sp" : "=r" (sp));
  498. #else
  499. asm("mov %0, sp" : "=r" (sp));
  500. #endif
  501. uptr mangled_sp = ((uptr *)&env)[LONG_JMP_SP_ENV_SLOT];
  502. // 3. xor SPs to obtain key.
  503. longjmp_xor_key = mangled_sp ^ sp;
  504. }
  505. #endif
  506. extern "C" void __tsan_tls_initialization() {}
  507. void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
  508. // Check that the thr object is in tls;
  509. const uptr thr_beg = (uptr)thr;
  510. const uptr thr_end = (uptr)thr + sizeof(*thr);
  511. CHECK_GE(thr_beg, tls_addr);
  512. CHECK_LE(thr_beg, tls_addr + tls_size);
  513. CHECK_GE(thr_end, tls_addr);
  514. CHECK_LE(thr_end, tls_addr + tls_size);
  515. // Since the thr object is huge, skip it.
  516. const uptr pc = StackTrace::GetNextInstructionPc(
  517. reinterpret_cast<uptr>(__tsan_tls_initialization));
  518. MemoryRangeImitateWrite(thr, pc, tls_addr, thr_beg - tls_addr);
  519. MemoryRangeImitateWrite(thr, pc, thr_end, tls_addr + tls_size - thr_end);
  520. }
  521. // Note: this function runs with async signals enabled,
  522. // so it must not touch any tsan state.
  523. int call_pthread_cancel_with_cleanup(int (*fn)(void *arg),
  524. void (*cleanup)(void *arg), void *arg) {
  525. // pthread_cleanup_push/pop are hardcore macros mess.
  526. // We can't intercept nor call them w/o including pthread.h.
  527. int res;
  528. pthread_cleanup_push(cleanup, arg);
  529. res = fn(arg);
  530. pthread_cleanup_pop(0);
  531. return res;
  532. }
  533. #endif // !SANITIZER_GO
  534. #if !SANITIZER_GO
  535. void ReplaceSystemMalloc() { }
  536. #endif
  537. #if !SANITIZER_GO
  538. #if SANITIZER_ANDROID
  539. // On Android, one thread can call intercepted functions after
  540. // DestroyThreadState(), so add a fake thread state for "dead" threads.
  541. static ThreadState *dead_thread_state = nullptr;
  542. ThreadState *cur_thread() {
  543. ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
  544. if (thr == nullptr) {
  545. __sanitizer_sigset_t emptyset;
  546. internal_sigfillset(&emptyset);
  547. __sanitizer_sigset_t oldset;
  548. CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset));
  549. thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
  550. if (thr == nullptr) {
  551. thr = reinterpret_cast<ThreadState*>(MmapOrDie(sizeof(ThreadState),
  552. "ThreadState"));
  553. *get_android_tls_ptr() = reinterpret_cast<uptr>(thr);
  554. if (dead_thread_state == nullptr) {
  555. dead_thread_state = reinterpret_cast<ThreadState*>(
  556. MmapOrDie(sizeof(ThreadState), "ThreadState"));
  557. dead_thread_state->fast_state.SetIgnoreBit();
  558. dead_thread_state->ignore_interceptors = 1;
  559. dead_thread_state->is_dead = true;
  560. *const_cast<u32*>(&dead_thread_state->tid) = -1;
  561. CHECK_EQ(0, internal_mprotect(dead_thread_state, sizeof(ThreadState),
  562. PROT_READ));
  563. }
  564. }
  565. CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
  566. }
  567. return thr;
  568. }
  569. void set_cur_thread(ThreadState *thr) {
  570. *get_android_tls_ptr() = reinterpret_cast<uptr>(thr);
  571. }
  572. void cur_thread_finalize() {
  573. __sanitizer_sigset_t emptyset;
  574. internal_sigfillset(&emptyset);
  575. __sanitizer_sigset_t oldset;
  576. CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset));
  577. ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
  578. if (thr != dead_thread_state) {
  579. *get_android_tls_ptr() = reinterpret_cast<uptr>(dead_thread_state);
  580. UnmapOrDie(thr, sizeof(ThreadState));
  581. }
  582. CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
  583. }
  584. #endif // SANITIZER_ANDROID
  585. #endif // if !SANITIZER_GO
  586. } // namespace __tsan
  587. #endif // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD