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