1 | //===-- sanitizer_linux_libcdep.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 shared between AddressSanitizer and ThreadSanitizer |
10 | // run-time libraries and implements linux-specific functions from |
11 | // sanitizer_libc.h. |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #include "sanitizer_platform.h" |
15 | |
16 | #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \ |
17 | SANITIZER_SOLARIS || SANITIZER_HAIKU |
18 | |
19 | # include "sanitizer_allocator_internal.h" |
20 | # include "sanitizer_atomic.h" |
21 | # include "sanitizer_common.h" |
22 | # include "sanitizer_file.h" |
23 | # include "sanitizer_flags.h" |
24 | # include "sanitizer_getauxval.h" |
25 | # include "sanitizer_glibc_version.h" |
26 | # include "sanitizer_linux.h" |
27 | # include "sanitizer_placement_new.h" |
28 | # include "sanitizer_procmaps.h" |
29 | # include "sanitizer_solaris.h" |
30 | |
31 | # if SANITIZER_HAIKU |
32 | # define _DEFAULT_SOURCE |
33 | # endif |
34 | |
35 | # if SANITIZER_NETBSD |
36 | # // for __lwp_gettcb_fast() / __lwp_getprivate_fast() |
37 | # define _RTLD_SOURCE |
38 | # include <machine/mcontext.h> |
39 | # undef _RTLD_SOURCE |
40 | # include <sys/param.h> |
41 | # if __NetBSD_Version__ >= 1099001200 |
42 | # include <machine/lwp_private.h> |
43 | # endif |
44 | # endif |
45 | |
46 | # include <dlfcn.h> // for dlsym() |
47 | # include <link.h> |
48 | # include <pthread.h> |
49 | # include <signal.h> |
50 | # include <sys/mman.h> |
51 | # include <sys/resource.h> |
52 | # include <syslog.h> |
53 | |
54 | # if SANITIZER_GLIBC |
55 | # include <gnu/libc-version.h> |
56 | # endif |
57 | |
58 | # if !defined(ElfW) |
59 | # define ElfW(type) Elf_##type |
60 | # endif |
61 | |
62 | # if SANITIZER_FREEBSD |
63 | # include <pthread_np.h> |
64 | # include <sys/auxv.h> |
65 | # include <sys/sysctl.h> |
66 | # define pthread_getattr_np pthread_attr_get_np |
67 | // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before |
68 | // that, it was never implemented. So just define it to zero. |
69 | # undef MAP_NORESERVE |
70 | # define MAP_NORESERVE 0 |
71 | extern const Elf_Auxinfo *__elf_aux_vector __attribute__((weak)); |
72 | extern "C" int __sys_sigaction(int signum, const struct sigaction *act, |
73 | struct sigaction *oldact); |
74 | # endif |
75 | |
76 | # if SANITIZER_NETBSD |
77 | # include <lwp.h> |
78 | # include <sys/sysctl.h> |
79 | # include <sys/tls.h> |
80 | # endif |
81 | |
82 | # if SANITIZER_SOLARIS |
83 | # include <stddef.h> |
84 | # include <stdlib.h> |
85 | # include <thread.h> |
86 | # endif |
87 | |
88 | # if SANITIZER_HAIKU |
89 | # include <kernel/OS.h> |
90 | # include <sys/link_elf.h> |
91 | # endif |
92 | |
93 | # if !SANITIZER_ANDROID |
94 | # include <elf.h> |
95 | # include <unistd.h> |
96 | # endif |
97 | |
98 | namespace __sanitizer { |
99 | |
100 | SANITIZER_WEAK_ATTRIBUTE int real_sigaction(int signum, const void *act, |
101 | void *oldact); |
102 | |
103 | int internal_sigaction(int signum, const void *act, void *oldact) { |
104 | # if SANITIZER_FREEBSD |
105 | // On FreeBSD, call the sigaction syscall directly (part of libsys in FreeBSD |
106 | // 15) since the libc version goes via a global interposing table. Due to |
107 | // library initialization order the table can be relocated after the call to |
108 | // InitializeDeadlySignals() which then crashes when dereferencing the |
109 | // uninitialized pointer in libc. |
110 | return __sys_sigaction(signum, (const struct sigaction *)act, |
111 | (struct sigaction *)oldact); |
112 | # else |
113 | # if !SANITIZER_GO |
114 | if (&real_sigaction) |
115 | return real_sigaction(signum, act, oldact); |
116 | # endif |
117 | return sigaction(sig: signum, act: (const struct sigaction *)act, |
118 | oact: (struct sigaction *)oldact); |
119 | # endif |
120 | } |
121 | |
122 | void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top, |
123 | uptr *stack_bottom) { |
124 | CHECK(stack_top); |
125 | CHECK(stack_bottom); |
126 | if (at_initialization) { |
127 | // This is the main thread. Libpthread may not be initialized yet. |
128 | struct rlimit rl; |
129 | CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0); |
130 | |
131 | // Find the mapping that contains a stack variable. |
132 | MemoryMappingLayout proc_maps(/*cache_enabled*/ true); |
133 | if (proc_maps.Error()) { |
134 | *stack_top = *stack_bottom = 0; |
135 | return; |
136 | } |
137 | MemoryMappedSegment segment; |
138 | uptr prev_end = 0; |
139 | while (proc_maps.Next(segment: &segment)) { |
140 | if ((uptr)&rl < segment.end) |
141 | break; |
142 | prev_end = segment.end; |
143 | } |
144 | CHECK((uptr)&rl >= segment.start && (uptr)&rl < segment.end); |
145 | |
146 | // Get stacksize from rlimit, but clip it so that it does not overlap |
147 | // with other mappings. |
148 | uptr stacksize = rl.rlim_cur; |
149 | if (stacksize > segment.end - prev_end) |
150 | stacksize = segment.end - prev_end; |
151 | // When running with unlimited stack size, we still want to set some limit. |
152 | // The unlimited stack size is caused by 'ulimit -s unlimited'. |
153 | // Also, for some reason, GNU make spawns subprocesses with unlimited stack. |
154 | if (stacksize > kMaxThreadStackSize) |
155 | stacksize = kMaxThreadStackSize; |
156 | *stack_top = segment.end; |
157 | *stack_bottom = segment.end - stacksize; |
158 | |
159 | uptr maxAddr = GetMaxUserVirtualAddress(); |
160 | // Edge case: the stack mapping on some systems may be off-by-one e.g., |
161 | // fffffffdf000-1000000000000 rw-p 00000000 00:00 0 [stack] |
162 | // instead of: |
163 | // fffffffdf000- ffffffffffff |
164 | // The out-of-range stack_top can result in an invalid shadow address |
165 | // calculation, since those usually assume the parameters are in range. |
166 | if (*stack_top == maxAddr + 1) |
167 | *stack_top = maxAddr; |
168 | else |
169 | CHECK_LE(*stack_top, maxAddr); |
170 | |
171 | return; |
172 | } |
173 | uptr stacksize = 0; |
174 | void *stackaddr = nullptr; |
175 | # if SANITIZER_SOLARIS |
176 | stack_t ss; |
177 | CHECK_EQ(thr_stksegment(&ss), 0); |
178 | stacksize = ss.ss_size; |
179 | stackaddr = (char *)ss.ss_sp - stacksize; |
180 | # else // !SANITIZER_SOLARIS |
181 | pthread_attr_t attr; |
182 | pthread_attr_init(attr: &attr); |
183 | CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0); |
184 | internal_pthread_attr_getstack(attr: &attr, addr: &stackaddr, size: &stacksize); |
185 | pthread_attr_destroy(attr: &attr); |
186 | # endif // SANITIZER_SOLARIS |
187 | |
188 | *stack_top = (uptr)stackaddr + stacksize; |
189 | *stack_bottom = (uptr)stackaddr; |
190 | } |
191 | |
192 | # if !SANITIZER_GO |
193 | bool SetEnv(const char *name, const char *value) { |
194 | void *f = dlsym(RTLD_NEXT, name: "setenv" ); |
195 | if (!f) |
196 | return false; |
197 | typedef int (*setenv_ft)(const char *name, const char *value, int overwrite); |
198 | setenv_ft setenv_f; |
199 | CHECK_EQ(sizeof(setenv_f), sizeof(f)); |
200 | internal_memcpy(dest: &setenv_f, src: &f, n: sizeof(f)); |
201 | return setenv_f(name, value, 1) == 0; |
202 | } |
203 | # endif |
204 | |
205 | // True if we can use dlpi_tls_data. glibc before 2.25 may leave NULL (BZ |
206 | // #19826) so dlpi_tls_data cannot be used. |
207 | // |
208 | // musl before 1.2.3 and FreeBSD as of 12.2 incorrectly set dlpi_tls_data to |
209 | // the TLS initialization image |
210 | // https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=254774 |
211 | __attribute__((unused)) static int g_use_dlpi_tls_data; |
212 | |
213 | # if SANITIZER_GLIBC && !SANITIZER_GO |
214 | static void GetGLibcVersion(int *major, int *minor, int *patch) { |
215 | const char *p = gnu_get_libc_version(); |
216 | *major = internal_simple_strtoll(nptr: p, endptr: &p, base: 10); |
217 | // Caller does not expect anything else. |
218 | CHECK_EQ(*major, 2); |
219 | *minor = (*p == '.') ? internal_simple_strtoll(nptr: p + 1, endptr: &p, base: 10) : 0; |
220 | *patch = (*p == '.') ? internal_simple_strtoll(nptr: p + 1, endptr: &p, base: 10) : 0; |
221 | } |
222 | |
223 | static uptr ThreadDescriptorSizeFallback() { |
224 | # if defined(__x86_64__) || defined(__i386__) || defined(__arm__) || \ |
225 | SANITIZER_RISCV64 |
226 | int major; |
227 | int minor; |
228 | int patch; |
229 | GetGLibcVersion(major: &major, minor: &minor, patch: &patch); |
230 | # endif |
231 | |
232 | # if defined(__x86_64__) || defined(__i386__) || defined(__arm__) |
233 | /* sizeof(struct pthread) values from various glibc versions. */ |
234 | if (SANITIZER_X32) |
235 | return 1728; // Assume only one particular version for x32. |
236 | // For ARM sizeof(struct pthread) changed in Glibc 2.23. |
237 | if (SANITIZER_ARM) |
238 | return minor <= 22 ? 1120 : 1216; |
239 | if (minor <= 3) |
240 | return FIRST_32_SECOND_64(1104, 1696); |
241 | if (minor == 4) |
242 | return FIRST_32_SECOND_64(1120, 1728); |
243 | if (minor == 5) |
244 | return FIRST_32_SECOND_64(1136, 1728); |
245 | if (minor <= 9) |
246 | return FIRST_32_SECOND_64(1136, 1712); |
247 | if (minor == 10) |
248 | return FIRST_32_SECOND_64(1168, 1776); |
249 | if (minor == 11 || (minor == 12 && patch == 1)) |
250 | return FIRST_32_SECOND_64(1168, 2288); |
251 | if (minor <= 14) |
252 | return FIRST_32_SECOND_64(1168, 2304); |
253 | if (minor < 32) // Unknown version |
254 | return FIRST_32_SECOND_64(1216, 2304); |
255 | // minor == 32 |
256 | return FIRST_32_SECOND_64(1344, 2496); |
257 | # endif |
258 | |
259 | # if SANITIZER_RISCV64 |
260 | // TODO: consider adding an optional runtime check for an unknown (untested) |
261 | // glibc version |
262 | if (minor <= 28) // WARNING: the highest tested version is 2.29 |
263 | return 1772; // no guarantees for this one |
264 | if (minor <= 31) |
265 | return 1772; // tested against glibc 2.29, 2.31 |
266 | return 1936; // tested against glibc 2.32 |
267 | # endif |
268 | |
269 | # if defined(__s390__) || defined(__sparc__) |
270 | // The size of a prefix of TCB including pthread::{specific_1stblock,specific} |
271 | // suffices. Just return offsetof(struct pthread, specific_used), which hasn't |
272 | // changed since 2007-05. Technically this applies to i386/x86_64 as well but |
273 | // we call _dl_get_tls_static_info and need the precise size of struct |
274 | // pthread. |
275 | return FIRST_32_SECOND_64(524, 1552); |
276 | # endif |
277 | |
278 | # if defined(__mips__) |
279 | // TODO(sagarthakur): add more values as per different glibc versions. |
280 | return FIRST_32_SECOND_64(1152, 1776); |
281 | # endif |
282 | |
283 | # if SANITIZER_LOONGARCH64 |
284 | return 1856; // from glibc 2.36 |
285 | # endif |
286 | |
287 | # if defined(__aarch64__) |
288 | // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22. |
289 | return 1776; |
290 | # endif |
291 | |
292 | # if defined(__powerpc64__) |
293 | return 1776; // from glibc.ppc64le 2.20-8.fc21 |
294 | # endif |
295 | } |
296 | # endif // SANITIZER_GLIBC && !SANITIZER_GO |
297 | |
298 | # if SANITIZER_FREEBSD && !SANITIZER_GO |
299 | // FIXME: Implementation is very GLIBC specific, but it's used by FreeBSD. |
300 | static uptr ThreadDescriptorSizeFallback() { |
301 | # if defined(__s390__) || defined(__sparc__) |
302 | // The size of a prefix of TCB including pthread::{specific_1stblock,specific} |
303 | // suffices. Just return offsetof(struct pthread, specific_used), which hasn't |
304 | // changed since 2007-05. Technically this applies to i386/x86_64 as well but |
305 | // we call _dl_get_tls_static_info and need the precise size of struct |
306 | // pthread. |
307 | return FIRST_32_SECOND_64(524, 1552); |
308 | # endif |
309 | |
310 | # if defined(__mips__) |
311 | // TODO(sagarthakur): add more values as per different glibc versions. |
312 | return FIRST_32_SECOND_64(1152, 1776); |
313 | # endif |
314 | |
315 | # if SANITIZER_LOONGARCH64 |
316 | return 1856; // from glibc 2.36 |
317 | # endif |
318 | |
319 | # if defined(__aarch64__) |
320 | // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22. |
321 | return 1776; |
322 | # endif |
323 | |
324 | # if defined(__powerpc64__) |
325 | return 1776; // from glibc.ppc64le 2.20-8.fc21 |
326 | # endif |
327 | |
328 | return 0; |
329 | } |
330 | # endif // SANITIZER_FREEBSD && !SANITIZER_GO |
331 | |
332 | # if (SANITIZER_FREEBSD || SANITIZER_GLIBC) && !SANITIZER_GO |
333 | // On glibc x86_64, ThreadDescriptorSize() needs to be precise due to the usage |
334 | // of g_tls_size. On other targets, ThreadDescriptorSize() is only used by lsan |
335 | // to get the pointer to thread-specific data keys in the thread control block. |
336 | // sizeof(struct pthread) from glibc. |
337 | static uptr thread_descriptor_size; |
338 | |
339 | uptr ThreadDescriptorSize() { return thread_descriptor_size; } |
340 | |
341 | # if SANITIZER_GLIBC |
342 | __attribute__((unused)) static size_t g_tls_size; |
343 | # endif |
344 | |
345 | void InitTlsSize() { |
346 | # if SANITIZER_GLIBC |
347 | int major, minor, patch; |
348 | GetGLibcVersion(major: &major, minor: &minor, patch: &patch); |
349 | g_use_dlpi_tls_data = major == 2 && minor >= 25; |
350 | |
351 | if (major == 2 && minor >= 34) { |
352 | // _thread_db_sizeof_pthread is a GLIBC_PRIVATE symbol that is exported in |
353 | // glibc 2.34 and later. |
354 | if (unsigned *psizeof = static_cast<unsigned *>( |
355 | dlsym(RTLD_DEFAULT, name: "_thread_db_sizeof_pthread" ))) { |
356 | thread_descriptor_size = *psizeof; |
357 | } |
358 | } |
359 | |
360 | # if defined(__aarch64__) || defined(__x86_64__) || \ |
361 | defined(__powerpc64__) || defined(__loongarch__) |
362 | auto *get_tls_static_info = (void (*)(size_t *, size_t *))dlsym( |
363 | RTLD_DEFAULT, name: "_dl_get_tls_static_info" ); |
364 | size_t tls_align; |
365 | // Can be null if static link. |
366 | if (get_tls_static_info) |
367 | get_tls_static_info(&g_tls_size, &tls_align); |
368 | # endif |
369 | |
370 | # endif // SANITIZER_GLIBC |
371 | |
372 | if (!thread_descriptor_size) |
373 | thread_descriptor_size = ThreadDescriptorSizeFallback(); |
374 | } |
375 | |
376 | # if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64 || \ |
377 | SANITIZER_LOONGARCH64 |
378 | // TlsPreTcbSize includes size of struct pthread_descr and size of tcb |
379 | // head structure. It lies before the static tls blocks. |
380 | static uptr TlsPreTcbSize() { |
381 | # if defined(__mips__) |
382 | const uptr kTcbHead = 16; // sizeof (tcbhead_t) |
383 | # elif defined(__powerpc64__) |
384 | const uptr kTcbHead = 88; // sizeof (tcbhead_t) |
385 | # elif SANITIZER_RISCV64 |
386 | const uptr kTcbHead = 16; // sizeof (tcbhead_t) |
387 | # elif SANITIZER_LOONGARCH64 |
388 | const uptr kTcbHead = 16; // sizeof (tcbhead_t) |
389 | # endif |
390 | const uptr kTlsAlign = 16; |
391 | const uptr kTlsPreTcbSize = |
392 | RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign); |
393 | return kTlsPreTcbSize; |
394 | } |
395 | # endif |
396 | # else // (SANITIZER_FREEBSD || SANITIZER_GLIBC) && !SANITIZER_GO |
397 | void InitTlsSize() {} |
398 | uptr ThreadDescriptorSize() { return 0; } |
399 | # endif // (SANITIZER_FREEBSD || SANITIZER_GLIBC) && !SANITIZER_GO |
400 | |
401 | # if (SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_SOLARIS) && \ |
402 | !SANITIZER_ANDROID && !SANITIZER_GO |
403 | namespace { |
404 | struct TlsBlock { |
405 | uptr begin, end, align; |
406 | size_t tls_modid; |
407 | bool operator<(const TlsBlock &rhs) const { return begin < rhs.begin; } |
408 | }; |
409 | } // namespace |
410 | |
411 | # ifdef __s390__ |
412 | extern "C" uptr __tls_get_offset(void *arg); |
413 | |
414 | static uptr TlsGetOffset(uptr ti_module, uptr ti_offset) { |
415 | // The __tls_get_offset ABI requires %r12 to point to GOT and %r2 to be an |
416 | // offset of a struct tls_index inside GOT. We don't possess either of the |
417 | // two, so violate the letter of the "ELF Handling For Thread-Local |
418 | // Storage" document and assume that the implementation just dereferences |
419 | // %r2 + %r12. |
420 | uptr tls_index[2] = {ti_module, ti_offset}; |
421 | register uptr r2 asm("2" ) = 0; |
422 | register void *r12 asm("12" ) = tls_index; |
423 | asm("basr %%r14, %[__tls_get_offset]" |
424 | : "+r" (r2) |
425 | : [__tls_get_offset] "r" (__tls_get_offset), "r" (r12) |
426 | : "memory" , "cc" , "0" , "1" , "3" , "4" , "5" , "14" ); |
427 | return r2; |
428 | } |
429 | # else |
430 | extern "C" void *__tls_get_addr(size_t *); |
431 | # endif |
432 | |
433 | static size_t main_tls_modid; |
434 | |
435 | static int CollectStaticTlsBlocks(struct dl_phdr_info *info, size_t size, |
436 | void *data) { |
437 | size_t tls_modid; |
438 | # if SANITIZER_SOLARIS |
439 | // dlpi_tls_modid is only available since Solaris 11.4 SRU 10. Use |
440 | // dlinfo(RTLD_DI_LINKMAP) instead which works on all of Solaris 11.3, |
441 | // 11.4, and Illumos. The tlsmodid of the executable was changed to 1 in |
442 | // 11.4 to match other implementations. |
443 | if (size >= offsetof(dl_phdr_info_test, dlpi_tls_modid)) |
444 | main_tls_modid = 1; |
445 | else |
446 | main_tls_modid = 0; |
447 | g_use_dlpi_tls_data = 0; |
448 | Rt_map *map; |
449 | dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &map); |
450 | tls_modid = map->rt_tlsmodid; |
451 | # else |
452 | main_tls_modid = 1; |
453 | tls_modid = info->dlpi_tls_modid; |
454 | # endif |
455 | |
456 | if (tls_modid < main_tls_modid) |
457 | return 0; |
458 | uptr begin; |
459 | # if !SANITIZER_SOLARIS |
460 | begin = (uptr)info->dlpi_tls_data; |
461 | # endif |
462 | if (!g_use_dlpi_tls_data) { |
463 | // Call __tls_get_addr as a fallback. This forces TLS allocation on glibc |
464 | // and FreeBSD. |
465 | # ifdef __s390__ |
466 | begin = (uptr)__builtin_thread_pointer() + TlsGetOffset(tls_modid, 0); |
467 | # else |
468 | size_t mod_and_off[2] = {tls_modid, 0}; |
469 | begin = (uptr)__tls_get_addr(mod_and_off); |
470 | # endif |
471 | } |
472 | for (unsigned i = 0; i != info->dlpi_phnum; ++i) |
473 | if (info->dlpi_phdr[i].p_type == PT_TLS) { |
474 | static_cast<InternalMmapVector<TlsBlock> *>(data)->push_back( |
475 | element: TlsBlock{.begin: begin, .end: begin + info->dlpi_phdr[i].p_memsz, |
476 | .align: info->dlpi_phdr[i].p_align, .tls_modid: tls_modid}); |
477 | break; |
478 | } |
479 | return 0; |
480 | } |
481 | |
482 | __attribute__((unused)) static void GetStaticTlsBoundary(uptr *addr, uptr *size, |
483 | uptr *align) { |
484 | InternalMmapVector<TlsBlock> ranges; |
485 | dl_iterate_phdr(callback: CollectStaticTlsBlocks, data: &ranges); |
486 | uptr len = ranges.size(); |
487 | Sort(v: ranges.begin(), size: len); |
488 | // Find the range with tls_modid == main_tls_modid. For glibc, because |
489 | // libc.so uses PT_TLS, this module is guaranteed to exist and is one of |
490 | // the initially loaded modules. |
491 | uptr one = 0; |
492 | while (one != len && ranges[one].tls_modid != main_tls_modid) ++one; |
493 | if (one == len) { |
494 | // This may happen with musl if no module uses PT_TLS. |
495 | *addr = 0; |
496 | *size = 0; |
497 | *align = 1; |
498 | return; |
499 | } |
500 | // Find the maximum consecutive ranges. We consider two modules consecutive if |
501 | // the gap is smaller than the alignment of the latter range. The dynamic |
502 | // loader places static TLS blocks this way not to waste space. |
503 | uptr l = one; |
504 | *align = ranges[l].align; |
505 | while (l != 0 && ranges[l].begin < ranges[l - 1].end + ranges[l].align) |
506 | *align = Max(a: *align, b: ranges[--l].align); |
507 | uptr r = one + 1; |
508 | while (r != len && ranges[r].begin < ranges[r - 1].end + ranges[r].align) |
509 | *align = Max(a: *align, b: ranges[r++].align); |
510 | *addr = ranges[l].begin; |
511 | *size = ranges[r - 1].end - ranges[l].begin; |
512 | } |
513 | # endif // (x86_64 || i386 || mips || ...) && (SANITIZER_FREEBSD || |
514 | // SANITIZER_LINUX) && !SANITIZER_ANDROID && !SANITIZER_GO |
515 | |
516 | # if SANITIZER_NETBSD |
517 | static struct tls_tcb *ThreadSelfTlsTcb() { |
518 | struct tls_tcb *tcb = nullptr; |
519 | # ifdef __HAVE___LWP_GETTCB_FAST |
520 | tcb = (struct tls_tcb *)__lwp_gettcb_fast(); |
521 | # elif defined(__HAVE___LWP_GETPRIVATE_FAST) |
522 | tcb = (struct tls_tcb *)__lwp_getprivate_fast(); |
523 | # endif |
524 | return tcb; |
525 | } |
526 | |
527 | uptr ThreadSelf() { return (uptr)ThreadSelfTlsTcb()->tcb_pthread; } |
528 | |
529 | int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) { |
530 | const Elf_Phdr *hdr = info->dlpi_phdr; |
531 | const Elf_Phdr *last_hdr = hdr + info->dlpi_phnum; |
532 | |
533 | for (; hdr != last_hdr; ++hdr) { |
534 | if (hdr->p_type == PT_TLS && info->dlpi_tls_modid == 1) { |
535 | *(uptr *)data = hdr->p_memsz; |
536 | break; |
537 | } |
538 | } |
539 | return 0; |
540 | } |
541 | # endif // SANITIZER_NETBSD |
542 | |
543 | # if SANITIZER_ANDROID |
544 | // Bionic provides this API since S. |
545 | extern "C" SANITIZER_WEAK_ATTRIBUTE void __libc_get_static_tls_bounds(void **, |
546 | void **); |
547 | # endif |
548 | |
549 | # if !SANITIZER_GO |
550 | static void GetTls(uptr *addr, uptr *size) { |
551 | # if SANITIZER_ANDROID |
552 | if (&__libc_get_static_tls_bounds) { |
553 | void *start_addr; |
554 | void *end_addr; |
555 | __libc_get_static_tls_bounds(&start_addr, &end_addr); |
556 | *addr = reinterpret_cast<uptr>(start_addr); |
557 | *size = |
558 | reinterpret_cast<uptr>(end_addr) - reinterpret_cast<uptr>(start_addr); |
559 | } else { |
560 | *addr = 0; |
561 | *size = 0; |
562 | } |
563 | # elif SANITIZER_GLIBC && defined(__x86_64__) |
564 | // For aarch64 and x86-64, use an O(1) approach which requires relatively |
565 | // precise ThreadDescriptorSize. g_tls_size was initialized in InitTlsSize. |
566 | # if SANITIZER_X32 |
567 | asm("mov %%fs:8,%0" : "=r" (*addr)); |
568 | # else |
569 | asm("mov %%fs:16,%0" : "=r" (*addr)); |
570 | # endif |
571 | *size = g_tls_size; |
572 | *addr -= *size; |
573 | *addr += ThreadDescriptorSize(); |
574 | # elif SANITIZER_GLIBC && defined(__aarch64__) |
575 | *addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) - |
576 | ThreadDescriptorSize(); |
577 | *size = g_tls_size + ThreadDescriptorSize(); |
578 | # elif SANITIZER_GLIBC && defined(__loongarch__) |
579 | # ifdef __clang__ |
580 | *addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) - |
581 | ThreadDescriptorSize(); |
582 | # else |
583 | asm("or %0,$tp,$zero" : "=r" (*addr)); |
584 | *addr -= ThreadDescriptorSize(); |
585 | # endif |
586 | *size = g_tls_size + ThreadDescriptorSize(); |
587 | # elif SANITIZER_GLIBC && defined(__powerpc64__) |
588 | // Workaround for glibc<2.25(?). 2.27 is known to not need this. |
589 | uptr tp; |
590 | asm("addi %0,13,-0x7000" : "=r" (tp)); |
591 | const uptr pre_tcb_size = TlsPreTcbSize(); |
592 | *addr = tp - pre_tcb_size; |
593 | *size = g_tls_size + pre_tcb_size; |
594 | # elif SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_SOLARIS |
595 | uptr align; |
596 | GetStaticTlsBoundary(addr, size, &align); |
597 | # if defined(__x86_64__) || defined(__i386__) || defined(__s390__) || \ |
598 | defined(__sparc__) |
599 | if (SANITIZER_GLIBC) { |
600 | # if defined(__x86_64__) || defined(__i386__) |
601 | align = Max<uptr>(align, 64); |
602 | # else |
603 | align = Max<uptr>(align, 16); |
604 | # endif |
605 | } |
606 | const uptr tp = RoundUpTo(*addr + *size, align); |
607 | |
608 | // lsan requires the range to additionally cover the static TLS surplus |
609 | // (elf/dl-tls.c defines 1664). Otherwise there may be false positives for |
610 | // allocations only referenced by tls in dynamically loaded modules. |
611 | if (SANITIZER_GLIBC) |
612 | *size += 1644; |
613 | else if (SANITIZER_FREEBSD) |
614 | *size += 128; // RTLD_STATIC_TLS_EXTRA |
615 | |
616 | // Extend the range to include the thread control block. On glibc, lsan needs |
617 | // the range to include pthread::{specific_1stblock,specific} so that |
618 | // allocations only referenced by pthread_setspecific can be scanned. This may |
619 | // underestimate by at most TLS_TCB_ALIGN-1 bytes but it should be fine |
620 | // because the number of bytes after pthread::specific is larger. |
621 | *addr = tp - RoundUpTo(*size, align); |
622 | *size = tp - *addr + ThreadDescriptorSize(); |
623 | # else |
624 | # if SANITIZER_GLIBC |
625 | *size += 1664; |
626 | # elif SANITIZER_FREEBSD |
627 | *size += 128; // RTLD_STATIC_TLS_EXTRA |
628 | # if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64 |
629 | const uptr pre_tcb_size = TlsPreTcbSize(); |
630 | *addr -= pre_tcb_size; |
631 | *size += pre_tcb_size; |
632 | # else |
633 | // arm and aarch64 reserve two words at TP, so this underestimates the range. |
634 | // However, this is sufficient for the purpose of finding the pointers to |
635 | // thread-specific data keys. |
636 | const uptr tcb_size = ThreadDescriptorSize(); |
637 | *addr -= tcb_size; |
638 | *size += tcb_size; |
639 | # endif |
640 | # endif |
641 | # endif |
642 | # elif SANITIZER_NETBSD |
643 | struct tls_tcb *const tcb = ThreadSelfTlsTcb(); |
644 | *addr = 0; |
645 | *size = 0; |
646 | if (tcb != 0) { |
647 | // Find size (p_memsz) of dlpi_tls_modid 1 (TLS block of the main program). |
648 | // ld.elf_so hardcodes the index 1. |
649 | dl_iterate_phdr(GetSizeFromHdr, size); |
650 | |
651 | if (*size != 0) { |
652 | // The block has been found and tcb_dtv[1] contains the base address |
653 | *addr = (uptr)tcb->tcb_dtv[1]; |
654 | } |
655 | } |
656 | # elif SANITIZER_HAIKU |
657 | # else |
658 | # error "Unknown OS" |
659 | # endif |
660 | } |
661 | # endif |
662 | |
663 | # if !SANITIZER_GO |
664 | uptr GetTlsSize() { |
665 | # if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \ |
666 | SANITIZER_SOLARIS |
667 | uptr addr, size; |
668 | GetTls(addr: &addr, size: &size); |
669 | return size; |
670 | # else |
671 | return 0; |
672 | # endif |
673 | } |
674 | # endif |
675 | |
676 | void GetThreadStackAndTls(bool main, uptr *stk_begin, uptr *stk_end, |
677 | uptr *tls_begin, uptr *tls_end) { |
678 | # if SANITIZER_GO |
679 | // Stub implementation for Go. |
680 | *stk_begin = 0; |
681 | *stk_end = 0; |
682 | *tls_begin = 0; |
683 | *tls_end = 0; |
684 | # else |
685 | uptr tls_addr = 0; |
686 | uptr tls_size = 0; |
687 | GetTls(addr: &tls_addr, size: &tls_size); |
688 | *tls_begin = tls_addr; |
689 | *tls_end = tls_addr + tls_size; |
690 | |
691 | uptr stack_top, stack_bottom; |
692 | GetThreadStackTopAndBottom(at_initialization: main, stack_top: &stack_top, stack_bottom: &stack_bottom); |
693 | *stk_begin = stack_bottom; |
694 | *stk_end = stack_top; |
695 | |
696 | if (!main) { |
697 | // If stack and tls intersect, make them non-intersecting. |
698 | if (*tls_begin > *stk_begin && *tls_begin < *stk_end) { |
699 | if (*stk_end < *tls_end) |
700 | *tls_end = *stk_end; |
701 | *stk_end = *tls_begin; |
702 | } |
703 | } |
704 | # endif |
705 | } |
706 | |
707 | # if !SANITIZER_FREEBSD |
708 | typedef ElfW(Phdr) Elf_Phdr; |
709 | # endif |
710 | |
711 | struct DlIteratePhdrData { |
712 | InternalMmapVectorNoCtor<LoadedModule> *modules; |
713 | bool first; |
714 | }; |
715 | |
716 | static int AddModuleSegments(const char *module_name, dl_phdr_info *info, |
717 | InternalMmapVectorNoCtor<LoadedModule> *modules) { |
718 | if (module_name[0] == '\0') |
719 | return 0; |
720 | LoadedModule cur_module; |
721 | cur_module.set(module_name, base_address: info->dlpi_addr); |
722 | for (int i = 0; i < (int)info->dlpi_phnum; i++) { |
723 | const Elf_Phdr *phdr = &info->dlpi_phdr[i]; |
724 | if (phdr->p_type == PT_LOAD) { |
725 | uptr cur_beg = info->dlpi_addr + phdr->p_vaddr; |
726 | uptr cur_end = cur_beg + phdr->p_memsz; |
727 | # if SANITIZER_HAIKU |
728 | bool executable = phdr->p_flags & PF_EXECUTE; |
729 | bool writable = phdr->p_flags & PF_WRITE; |
730 | # else |
731 | bool executable = phdr->p_flags & PF_X; |
732 | bool writable = phdr->p_flags & PF_W; |
733 | # endif |
734 | cur_module.addAddressRange(beg: cur_beg, end: cur_end, executable, writable); |
735 | } else if (phdr->p_type == PT_NOTE) { |
736 | # ifdef NT_GNU_BUILD_ID |
737 | uptr off = 0; |
738 | while (off + sizeof(ElfW(Nhdr)) < phdr->p_memsz) { |
739 | auto *nhdr = reinterpret_cast<const ElfW(Nhdr) *>(info->dlpi_addr + |
740 | phdr->p_vaddr + off); |
741 | constexpr auto kGnuNamesz = 4; // "GNU" with NUL-byte. |
742 | static_assert(kGnuNamesz % 4 == 0, "kGnuNameSize is aligned to 4." ); |
743 | if (nhdr->n_type == NT_GNU_BUILD_ID && nhdr->n_namesz == kGnuNamesz) { |
744 | if (off + sizeof(ElfW(Nhdr)) + nhdr->n_namesz + nhdr->n_descsz > |
745 | phdr->p_memsz) { |
746 | // Something is very wrong, bail out instead of reading potentially |
747 | // arbitrary memory. |
748 | break; |
749 | } |
750 | const char *name = |
751 | reinterpret_cast<const char *>(nhdr) + sizeof(*nhdr); |
752 | if (internal_memcmp(s1: name, s2: "GNU" , n: 3) == 0) { |
753 | const char *value = reinterpret_cast<const char *>(nhdr) + |
754 | sizeof(*nhdr) + kGnuNamesz; |
755 | cur_module.setUuid(uuid: value, size: nhdr->n_descsz); |
756 | break; |
757 | } |
758 | } |
759 | off += sizeof(*nhdr) + RoundUpTo(size: nhdr->n_namesz, boundary: 4) + |
760 | RoundUpTo(size: nhdr->n_descsz, boundary: 4); |
761 | } |
762 | # endif |
763 | } |
764 | } |
765 | modules->push_back(element: cur_module); |
766 | return 0; |
767 | } |
768 | |
769 | static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) { |
770 | DlIteratePhdrData *data = (DlIteratePhdrData *)arg; |
771 | if (data->first) { |
772 | InternalMmapVector<char> module_name(kMaxPathLength); |
773 | data->first = false; |
774 | // First module is the binary itself. |
775 | ReadBinaryNameCached(buf: module_name.data(), buf_len: module_name.size()); |
776 | return AddModuleSegments(module_name: module_name.data(), info, modules: data->modules); |
777 | } |
778 | |
779 | if (info->dlpi_name) |
780 | return AddModuleSegments(module_name: info->dlpi_name, info, modules: data->modules); |
781 | |
782 | return 0; |
783 | } |
784 | |
785 | static bool requiresProcmaps() { |
786 | # if SANITIZER_ANDROID && __ANDROID_API__ <= 22 |
787 | // Fall back to /proc/maps if dl_iterate_phdr is unavailable or broken. |
788 | // The runtime check allows the same library to work with |
789 | // both K and L (and future) Android releases. |
790 | return AndroidGetApiLevel() <= ANDROID_LOLLIPOP_MR1; |
791 | # else |
792 | return false; |
793 | # endif |
794 | } |
795 | |
796 | static void procmapsInit(InternalMmapVectorNoCtor<LoadedModule> *modules) { |
797 | MemoryMappingLayout memory_mapping(/*cache_enabled*/ true); |
798 | memory_mapping.DumpListOfModules(modules); |
799 | } |
800 | |
801 | void ListOfModules::init() { |
802 | clearOrInit(); |
803 | if (requiresProcmaps()) { |
804 | procmapsInit(modules: &modules_); |
805 | } else { |
806 | DlIteratePhdrData data = {.modules: &modules_, .first: true}; |
807 | dl_iterate_phdr(callback: dl_iterate_phdr_cb, data: &data); |
808 | } |
809 | } |
810 | |
811 | // When a custom loader is used, dl_iterate_phdr may not contain the full |
812 | // list of modules. Allow callers to fall back to using procmaps. |
813 | void ListOfModules::fallbackInit() { |
814 | if (!requiresProcmaps()) { |
815 | clearOrInit(); |
816 | procmapsInit(modules: &modules_); |
817 | } else { |
818 | clear(); |
819 | } |
820 | } |
821 | |
822 | // getrusage does not give us the current RSS, only the max RSS. |
823 | // Still, this is better than nothing if /proc/self/statm is not available |
824 | // for some reason, e.g. due to a sandbox. |
825 | static uptr () { |
826 | struct rusage usage; |
827 | if (getrusage(RUSAGE_SELF, usage: &usage)) // Failed, probably due to a sandbox. |
828 | return 0; |
829 | return usage.ru_maxrss << 10; // ru_maxrss is in Kb. |
830 | } |
831 | |
832 | uptr () { |
833 | if (!common_flags()->can_use_proc_maps_statm) |
834 | return GetRSSFromGetrusage(); |
835 | fd_t fd = OpenFile(filename: "/proc/self/statm" , mode: RdOnly); |
836 | if (fd == kInvalidFd) |
837 | return GetRSSFromGetrusage(); |
838 | char buf[64]; |
839 | uptr len = internal_read(fd, buf, count: sizeof(buf) - 1); |
840 | internal_close(fd); |
841 | if ((sptr)len <= 0) |
842 | return 0; |
843 | buf[len] = 0; |
844 | // The format of the file is: |
845 | // 1084 89 69 11 0 79 0 |
846 | // We need the second number which is RSS in pages. |
847 | char *pos = buf; |
848 | // Skip the first number. |
849 | while (*pos >= '0' && *pos <= '9') pos++; |
850 | // Skip whitespaces. |
851 | while (!(*pos >= '0' && *pos <= '9') && *pos != 0) pos++; |
852 | // Read the number. |
853 | uptr = 0; |
854 | while (*pos >= '0' && *pos <= '9') rss = rss * 10 + *pos++ - '0'; |
855 | return rss * GetPageSizeCached(); |
856 | } |
857 | |
858 | // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as |
859 | // they allocate memory. |
860 | u32 GetNumberOfCPUs() { |
861 | # if SANITIZER_FREEBSD || SANITIZER_NETBSD |
862 | u32 ncpu; |
863 | int req[2]; |
864 | uptr len = sizeof(ncpu); |
865 | req[0] = CTL_HW; |
866 | # ifdef HW_NCPUONLINE |
867 | req[1] = HW_NCPUONLINE; |
868 | # else |
869 | req[1] = HW_NCPU; |
870 | # endif |
871 | CHECK_EQ(internal_sysctl(req, 2, &ncpu, &len, NULL, 0), 0); |
872 | return ncpu; |
873 | # elif SANITIZER_HAIKU |
874 | system_info info; |
875 | get_system_info(&info); |
876 | return info.cpu_count; |
877 | # elif SANITIZER_SOLARIS |
878 | return sysconf(_SC_NPROCESSORS_ONLN); |
879 | # else |
880 | cpu_set_t CPUs; |
881 | CHECK_EQ(sched_getaffinity(0, sizeof(cpu_set_t), &CPUs), 0); |
882 | return CPU_COUNT(&CPUs); |
883 | # endif |
884 | } |
885 | |
886 | # if SANITIZER_LINUX |
887 | |
888 | # if SANITIZER_ANDROID |
889 | static atomic_uint8_t android_log_initialized; |
890 | |
891 | void AndroidLogInit() { |
892 | openlog(GetProcessName(), 0, LOG_USER); |
893 | atomic_store(&android_log_initialized, 1, memory_order_release); |
894 | } |
895 | |
896 | static bool ShouldLogAfterPrintf() { |
897 | return atomic_load(&android_log_initialized, memory_order_acquire); |
898 | } |
899 | |
900 | extern "C" SANITIZER_WEAK_ATTRIBUTE int async_safe_write_log(int pri, |
901 | const char *tag, |
902 | const char *msg); |
903 | extern "C" SANITIZER_WEAK_ATTRIBUTE int __android_log_write(int prio, |
904 | const char *tag, |
905 | const char *msg); |
906 | |
907 | // ANDROID_LOG_INFO is 4, but can't be resolved at runtime. |
908 | # define SANITIZER_ANDROID_LOG_INFO 4 |
909 | |
910 | // async_safe_write_log is a new public version of __libc_write_log that is |
911 | // used behind syslog. It is preferable to syslog as it will not do any dynamic |
912 | // memory allocation or formatting. |
913 | // If the function is not available, syslog is preferred for L+ (it was broken |
914 | // pre-L) as __android_log_write triggers a racey behavior with the strncpy |
915 | // interceptor. Fallback to __android_log_write pre-L. |
916 | void WriteOneLineToSyslog(const char *s) { |
917 | if (&async_safe_write_log) { |
918 | async_safe_write_log(SANITIZER_ANDROID_LOG_INFO, GetProcessName(), s); |
919 | } else { |
920 | syslog(LOG_INFO, "%s" , s); |
921 | } |
922 | } |
923 | |
924 | extern "C" SANITIZER_WEAK_ATTRIBUTE void android_set_abort_message( |
925 | const char *); |
926 | |
927 | void SetAbortMessage(const char *str) { |
928 | if (&android_set_abort_message) |
929 | android_set_abort_message(str); |
930 | } |
931 | # else |
932 | void AndroidLogInit() {} |
933 | |
934 | static bool ShouldLogAfterPrintf() { return true; } |
935 | |
936 | void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, fmt: "%s" , s); } |
937 | |
938 | void SetAbortMessage(const char *str) {} |
939 | # endif // SANITIZER_ANDROID |
940 | |
941 | void LogMessageOnPrintf(const char *str) { |
942 | if (common_flags()->log_to_syslog && ShouldLogAfterPrintf()) |
943 | WriteToSyslog(buffer: str); |
944 | } |
945 | |
946 | # endif // SANITIZER_LINUX |
947 | |
948 | # if SANITIZER_GLIBC && !SANITIZER_GO |
949 | // glibc crashes when using clock_gettime from a preinit_array function as the |
950 | // vDSO function pointers haven't been initialized yet. __progname is |
951 | // initialized after the vDSO function pointers, so if it exists, is not null |
952 | // and is not empty, we can use clock_gettime. |
953 | extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname; |
954 | inline bool CanUseVDSO() { return &__progname && __progname && *__progname; } |
955 | |
956 | // MonotonicNanoTime is a timing function that can leverage the vDSO by calling |
957 | // clock_gettime. real_clock_gettime only exists if clock_gettime is |
958 | // intercepted, so define it weakly and use it if available. |
959 | extern "C" SANITIZER_WEAK_ATTRIBUTE int real_clock_gettime(u32 clk_id, |
960 | void *tp); |
961 | u64 MonotonicNanoTime() { |
962 | timespec ts; |
963 | if (CanUseVDSO()) { |
964 | if (&real_clock_gettime) |
965 | real_clock_gettime(CLOCK_MONOTONIC, tp: &ts); |
966 | else |
967 | clock_gettime(CLOCK_MONOTONIC, tp: &ts); |
968 | } else { |
969 | internal_clock_gettime(CLOCK_MONOTONIC, tp: &ts); |
970 | } |
971 | return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec; |
972 | } |
973 | # else |
974 | // Non-glibc & Go always use the regular function. |
975 | u64 MonotonicNanoTime() { |
976 | timespec ts; |
977 | clock_gettime(CLOCK_MONOTONIC, &ts); |
978 | return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec; |
979 | } |
980 | # endif // SANITIZER_GLIBC && !SANITIZER_GO |
981 | |
982 | void ReExec() { |
983 | const char *pathname = "/proc/self/exe" ; |
984 | |
985 | # if SANITIZER_FREEBSD |
986 | for (const auto *aux = __elf_aux_vector; aux->a_type != AT_NULL; aux++) { |
987 | if (aux->a_type == AT_EXECPATH) { |
988 | pathname = static_cast<const char *>(aux->a_un.a_ptr); |
989 | break; |
990 | } |
991 | } |
992 | # elif SANITIZER_NETBSD |
993 | static const int name[] = { |
994 | CTL_KERN, |
995 | KERN_PROC_ARGS, |
996 | -1, |
997 | KERN_PROC_PATHNAME, |
998 | }; |
999 | char path[400]; |
1000 | uptr len; |
1001 | |
1002 | len = sizeof(path); |
1003 | if (internal_sysctl(name, ARRAY_SIZE(name), path, &len, NULL, 0) != -1) |
1004 | pathname = path; |
1005 | # elif SANITIZER_SOLARIS |
1006 | pathname = getexecname(); |
1007 | CHECK_NE(pathname, NULL); |
1008 | # elif SANITIZER_USE_GETAUXVAL |
1009 | // Calling execve with /proc/self/exe sets that as $EXEC_ORIGIN. Binaries that |
1010 | // rely on that will fail to load shared libraries. Query AT_EXECFN instead. |
1011 | pathname = reinterpret_cast<const char *>(getauxval(AT_EXECFN)); |
1012 | # endif |
1013 | |
1014 | uptr rv = internal_execve(filename: pathname, argv: GetArgv(), envp: GetEnviron()); |
1015 | int rverrno; |
1016 | CHECK_EQ(internal_iserror(rv, &rverrno), true); |
1017 | Printf(format: "execve failed, errno %d\n" , rverrno); |
1018 | Die(); |
1019 | } |
1020 | |
1021 | void UnmapFromTo(uptr from, uptr to) { |
1022 | if (to == from) |
1023 | return; |
1024 | CHECK(to >= from); |
1025 | uptr res = internal_munmap(addr: reinterpret_cast<void *>(from), length: to - from); |
1026 | if (UNLIKELY(internal_iserror(res))) { |
1027 | Report(format: "ERROR: %s failed to unmap 0x%zx (%zd) bytes at address %p\n" , |
1028 | SanitizerToolName, to - from, to - from, (void *)from); |
1029 | CHECK("unable to unmap" && 0); |
1030 | } |
1031 | } |
1032 | |
1033 | uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale, |
1034 | uptr min_shadow_base_alignment, UNUSED uptr &high_mem_end, |
1035 | uptr granularity) { |
1036 | const uptr alignment = |
1037 | Max<uptr>(a: granularity << shadow_scale, b: 1ULL << min_shadow_base_alignment); |
1038 | const uptr left_padding = |
1039 | Max<uptr>(a: granularity, b: 1ULL << min_shadow_base_alignment); |
1040 | |
1041 | const uptr shadow_size = RoundUpTo(size: shadow_size_bytes, boundary: granularity); |
1042 | const uptr map_size = shadow_size + left_padding + alignment; |
1043 | |
1044 | const uptr map_start = (uptr)MmapNoAccess(size: map_size); |
1045 | CHECK_NE(map_start, ~(uptr)0); |
1046 | |
1047 | const uptr shadow_start = RoundUpTo(size: map_start + left_padding, boundary: alignment); |
1048 | |
1049 | UnmapFromTo(from: map_start, to: shadow_start - left_padding); |
1050 | UnmapFromTo(from: shadow_start + shadow_size, to: map_start + map_size); |
1051 | |
1052 | return shadow_start; |
1053 | } |
1054 | |
1055 | static uptr MmapSharedNoReserve(uptr addr, uptr size) { |
1056 | return internal_mmap( |
1057 | addr: reinterpret_cast<void *>(addr), length: size, PROT_READ | PROT_WRITE, |
1058 | MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, fd: -1, offset: 0); |
1059 | } |
1060 | |
1061 | static uptr MremapCreateAlias(uptr base_addr, uptr alias_addr, |
1062 | uptr alias_size) { |
1063 | # if SANITIZER_LINUX |
1064 | return internal_mremap(old_address: reinterpret_cast<void *>(base_addr), old_size: 0, new_size: alias_size, |
1065 | MREMAP_MAYMOVE | MREMAP_FIXED, |
1066 | new_address: reinterpret_cast<void *>(alias_addr)); |
1067 | # else |
1068 | CHECK(false && "mremap is not supported outside of Linux" ); |
1069 | return 0; |
1070 | # endif |
1071 | } |
1072 | |
1073 | static void CreateAliases(uptr start_addr, uptr alias_size, uptr num_aliases) { |
1074 | uptr total_size = alias_size * num_aliases; |
1075 | uptr mapped = MmapSharedNoReserve(addr: start_addr, size: total_size); |
1076 | CHECK_EQ(mapped, start_addr); |
1077 | |
1078 | for (uptr i = 1; i < num_aliases; ++i) { |
1079 | uptr alias_addr = start_addr + i * alias_size; |
1080 | CHECK_EQ(MremapCreateAlias(start_addr, alias_addr, alias_size), alias_addr); |
1081 | } |
1082 | } |
1083 | |
1084 | uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size, |
1085 | uptr num_aliases, uptr ring_buffer_size) { |
1086 | CHECK_EQ(alias_size & (alias_size - 1), 0); |
1087 | CHECK_EQ(num_aliases & (num_aliases - 1), 0); |
1088 | CHECK_EQ(ring_buffer_size & (ring_buffer_size - 1), 0); |
1089 | |
1090 | const uptr granularity = GetMmapGranularity(); |
1091 | shadow_size = RoundUpTo(size: shadow_size, boundary: granularity); |
1092 | CHECK_EQ(shadow_size & (shadow_size - 1), 0); |
1093 | |
1094 | const uptr alias_region_size = alias_size * num_aliases; |
1095 | const uptr alignment = |
1096 | 2 * Max(a: Max(a: shadow_size, b: alias_region_size), b: ring_buffer_size); |
1097 | const uptr left_padding = ring_buffer_size; |
1098 | |
1099 | const uptr right_size = alignment; |
1100 | const uptr map_size = left_padding + 2 * alignment; |
1101 | |
1102 | const uptr map_start = reinterpret_cast<uptr>(MmapNoAccess(size: map_size)); |
1103 | CHECK_NE(map_start, static_cast<uptr>(-1)); |
1104 | const uptr right_start = RoundUpTo(size: map_start + left_padding, boundary: alignment); |
1105 | |
1106 | UnmapFromTo(from: map_start, to: right_start - left_padding); |
1107 | UnmapFromTo(from: right_start + right_size, to: map_start + map_size); |
1108 | |
1109 | CreateAliases(start_addr: right_start + right_size / 2, alias_size, num_aliases); |
1110 | |
1111 | return right_start; |
1112 | } |
1113 | |
1114 | void InitializePlatformCommonFlags(CommonFlags *cf) { |
1115 | # if SANITIZER_ANDROID |
1116 | if (&__libc_get_static_tls_bounds == nullptr) |
1117 | cf->detect_leaks = false; |
1118 | # endif |
1119 | } |
1120 | |
1121 | } // namespace __sanitizer |
1122 | |
1123 | #endif |
1124 | |