sanitizer_linux_libcdep.cpp 35 KB

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