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