sanitizer_linux_libcdep.cpp 33 KB

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