sanitizer_mac.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. //===-- sanitizer_mac.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 various sanitizers' runtime libraries and
  10. // implements OSX-specific functions.
  11. //===----------------------------------------------------------------------===//
  12. #include "sanitizer_platform.h"
  13. #if SANITIZER_MAC
  14. #include "sanitizer_mac.h"
  15. #include "interception/interception.h"
  16. // Use 64-bit inodes in file operations. ASan does not support OS X 10.5, so
  17. // the clients will most certainly use 64-bit ones as well.
  18. #ifndef _DARWIN_USE_64_BIT_INODE
  19. #define _DARWIN_USE_64_BIT_INODE 1
  20. #endif
  21. #include <stdio.h>
  22. #include "sanitizer_common.h"
  23. #include "sanitizer_file.h"
  24. #include "sanitizer_flags.h"
  25. #include "sanitizer_internal_defs.h"
  26. #include "sanitizer_libc.h"
  27. #include "sanitizer_platform_limits_posix.h"
  28. #include "sanitizer_procmaps.h"
  29. #include "sanitizer_ptrauth.h"
  30. #if !SANITIZER_IOS
  31. #include <crt_externs.h> // for _NSGetEnviron
  32. #else
  33. extern char **environ;
  34. #endif
  35. #if defined(__has_include) && __has_include(<os/trace.h>)
  36. #define SANITIZER_OS_TRACE 1
  37. #include <os/trace.h>
  38. #else
  39. #define SANITIZER_OS_TRACE 0
  40. #endif
  41. // import new crash reporting api
  42. #if defined(__has_include) && __has_include(<CrashReporterClient.h>)
  43. #define HAVE_CRASHREPORTERCLIENT_H 1
  44. #include <CrashReporterClient.h>
  45. #else
  46. #define HAVE_CRASHREPORTERCLIENT_H 0
  47. #endif
  48. #if !SANITIZER_IOS
  49. #include <crt_externs.h> // for _NSGetArgv and _NSGetEnviron
  50. #else
  51. extern "C" {
  52. extern char ***_NSGetArgv(void);
  53. }
  54. #endif
  55. #include <asl.h>
  56. #include <dlfcn.h> // for dladdr()
  57. #include <errno.h>
  58. #include <fcntl.h>
  59. #include <libkern/OSAtomic.h>
  60. #include <mach-o/dyld.h>
  61. #include <mach/mach.h>
  62. #include <mach/mach_time.h>
  63. #include <mach/vm_statistics.h>
  64. #include <malloc/malloc.h>
  65. #include <os/log.h>
  66. #include <pthread.h>
  67. #include <sched.h>
  68. #include <signal.h>
  69. #include <spawn.h>
  70. #include <stdlib.h>
  71. #include <sys/ioctl.h>
  72. #include <sys/mman.h>
  73. #include <sys/resource.h>
  74. #include <sys/stat.h>
  75. #include <sys/sysctl.h>
  76. #include <sys/types.h>
  77. #include <sys/wait.h>
  78. #include <unistd.h>
  79. #include <util.h>
  80. // From <crt_externs.h>, but we don't have that file on iOS.
  81. extern "C" {
  82. extern char ***_NSGetArgv(void);
  83. extern char ***_NSGetEnviron(void);
  84. }
  85. // From <mach/mach_vm.h>, but we don't have that file on iOS.
  86. extern "C" {
  87. extern kern_return_t mach_vm_region_recurse(
  88. vm_map_t target_task,
  89. mach_vm_address_t *address,
  90. mach_vm_size_t *size,
  91. natural_t *nesting_depth,
  92. vm_region_recurse_info_t info,
  93. mach_msg_type_number_t *infoCnt);
  94. }
  95. namespace __sanitizer {
  96. #include "sanitizer_syscall_generic.inc"
  97. // Direct syscalls, don't call libmalloc hooks (but not available on 10.6).
  98. extern "C" void *__mmap(void *addr, size_t len, int prot, int flags, int fildes,
  99. off_t off) SANITIZER_WEAK_ATTRIBUTE;
  100. extern "C" int __munmap(void *, size_t) SANITIZER_WEAK_ATTRIBUTE;
  101. // ---------------------- sanitizer_libc.h
  102. // From <mach/vm_statistics.h>, but not on older OSs.
  103. #ifndef VM_MEMORY_SANITIZER
  104. #define VM_MEMORY_SANITIZER 99
  105. #endif
  106. // XNU on Darwin provides a mmap flag that optimizes allocation/deallocation of
  107. // giant memory regions (i.e. shadow memory regions).
  108. #define kXnuFastMmapFd 0x4
  109. static size_t kXnuFastMmapThreshold = 2 << 30; // 2 GB
  110. static bool use_xnu_fast_mmap = false;
  111. uptr internal_mmap(void *addr, size_t length, int prot, int flags,
  112. int fd, u64 offset) {
  113. if (fd == -1) {
  114. fd = VM_MAKE_TAG(VM_MEMORY_SANITIZER);
  115. if (length >= kXnuFastMmapThreshold) {
  116. if (use_xnu_fast_mmap) fd |= kXnuFastMmapFd;
  117. }
  118. }
  119. if (&__mmap) return (uptr)__mmap(addr, length, prot, flags, fd, offset);
  120. return (uptr)mmap(addr, length, prot, flags, fd, offset);
  121. }
  122. uptr internal_munmap(void *addr, uptr length) {
  123. if (&__munmap) return __munmap(addr, length);
  124. return munmap(addr, length);
  125. }
  126. uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
  127. void *new_address) {
  128. CHECK(false && "internal_mremap is unimplemented on Mac");
  129. return 0;
  130. }
  131. int internal_mprotect(void *addr, uptr length, int prot) {
  132. return mprotect(addr, length, prot);
  133. }
  134. int internal_madvise(uptr addr, uptr length, int advice) {
  135. return madvise((void *)addr, length, advice);
  136. }
  137. uptr internal_close(fd_t fd) {
  138. return close(fd);
  139. }
  140. uptr internal_open(const char *filename, int flags) {
  141. return open(filename, flags);
  142. }
  143. uptr internal_open(const char *filename, int flags, u32 mode) {
  144. return open(filename, flags, mode);
  145. }
  146. uptr internal_read(fd_t fd, void *buf, uptr count) {
  147. return read(fd, buf, count);
  148. }
  149. uptr internal_write(fd_t fd, const void *buf, uptr count) {
  150. return write(fd, buf, count);
  151. }
  152. uptr internal_stat(const char *path, void *buf) {
  153. return stat(path, (struct stat *)buf);
  154. }
  155. uptr internal_lstat(const char *path, void *buf) {
  156. return lstat(path, (struct stat *)buf);
  157. }
  158. uptr internal_fstat(fd_t fd, void *buf) {
  159. return fstat(fd, (struct stat *)buf);
  160. }
  161. uptr internal_filesize(fd_t fd) {
  162. struct stat st;
  163. if (internal_fstat(fd, &st))
  164. return -1;
  165. return (uptr)st.st_size;
  166. }
  167. uptr internal_dup(int oldfd) {
  168. return dup(oldfd);
  169. }
  170. uptr internal_dup2(int oldfd, int newfd) {
  171. return dup2(oldfd, newfd);
  172. }
  173. uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
  174. return readlink(path, buf, bufsize);
  175. }
  176. uptr internal_unlink(const char *path) {
  177. return unlink(path);
  178. }
  179. uptr internal_sched_yield() {
  180. return sched_yield();
  181. }
  182. void internal__exit(int exitcode) {
  183. _exit(exitcode);
  184. }
  185. void internal_usleep(u64 useconds) { usleep(useconds); }
  186. uptr internal_getpid() {
  187. return getpid();
  188. }
  189. int internal_dlinfo(void *handle, int request, void *p) {
  190. UNIMPLEMENTED();
  191. }
  192. int internal_sigaction(int signum, const void *act, void *oldact) {
  193. return sigaction(signum,
  194. (const struct sigaction *)act, (struct sigaction *)oldact);
  195. }
  196. void internal_sigfillset(__sanitizer_sigset_t *set) { sigfillset(set); }
  197. uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
  198. __sanitizer_sigset_t *oldset) {
  199. // Don't use sigprocmask here, because it affects all threads.
  200. return pthread_sigmask(how, set, oldset);
  201. }
  202. // Doesn't call pthread_atfork() handlers (but not available on 10.6).
  203. extern "C" pid_t __fork(void) SANITIZER_WEAK_ATTRIBUTE;
  204. int internal_fork() {
  205. if (&__fork)
  206. return __fork();
  207. return fork();
  208. }
  209. int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
  210. uptr *oldlenp, const void *newp, uptr newlen) {
  211. return sysctl(const_cast<int *>(name), namelen, oldp, (size_t *)oldlenp,
  212. const_cast<void *>(newp), (size_t)newlen);
  213. }
  214. int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
  215. const void *newp, uptr newlen) {
  216. return sysctlbyname(sname, oldp, (size_t *)oldlenp, const_cast<void *>(newp),
  217. (size_t)newlen);
  218. }
  219. static fd_t internal_spawn_impl(const char *argv[], const char *envp[],
  220. pid_t *pid) {
  221. fd_t primary_fd = kInvalidFd;
  222. fd_t secondary_fd = kInvalidFd;
  223. auto fd_closer = at_scope_exit([&] {
  224. internal_close(primary_fd);
  225. internal_close(secondary_fd);
  226. });
  227. // We need a new pseudoterminal to avoid buffering problems. The 'atos' tool
  228. // in particular detects when it's talking to a pipe and forgets to flush the
  229. // output stream after sending a response.
  230. primary_fd = posix_openpt(O_RDWR);
  231. if (primary_fd == kInvalidFd)
  232. return kInvalidFd;
  233. int res = grantpt(primary_fd) || unlockpt(primary_fd);
  234. if (res != 0) return kInvalidFd;
  235. // Use TIOCPTYGNAME instead of ptsname() to avoid threading problems.
  236. char secondary_pty_name[128];
  237. res = ioctl(primary_fd, TIOCPTYGNAME, secondary_pty_name);
  238. if (res == -1) return kInvalidFd;
  239. secondary_fd = internal_open(secondary_pty_name, O_RDWR);
  240. if (secondary_fd == kInvalidFd)
  241. return kInvalidFd;
  242. // File descriptor actions
  243. posix_spawn_file_actions_t acts;
  244. res = posix_spawn_file_actions_init(&acts);
  245. if (res != 0) return kInvalidFd;
  246. auto acts_cleanup = at_scope_exit([&] {
  247. posix_spawn_file_actions_destroy(&acts);
  248. });
  249. res = posix_spawn_file_actions_adddup2(&acts, secondary_fd, STDIN_FILENO) ||
  250. posix_spawn_file_actions_adddup2(&acts, secondary_fd, STDOUT_FILENO) ||
  251. posix_spawn_file_actions_addclose(&acts, secondary_fd);
  252. if (res != 0) return kInvalidFd;
  253. // Spawn attributes
  254. posix_spawnattr_t attrs;
  255. res = posix_spawnattr_init(&attrs);
  256. if (res != 0) return kInvalidFd;
  257. auto attrs_cleanup = at_scope_exit([&] {
  258. posix_spawnattr_destroy(&attrs);
  259. });
  260. // In the spawned process, close all file descriptors that are not explicitly
  261. // described by the file actions object. This is Darwin-specific extension.
  262. res = posix_spawnattr_setflags(&attrs, POSIX_SPAWN_CLOEXEC_DEFAULT);
  263. if (res != 0) return kInvalidFd;
  264. // posix_spawn
  265. char **argv_casted = const_cast<char **>(argv);
  266. char **envp_casted = const_cast<char **>(envp);
  267. res = posix_spawn(pid, argv[0], &acts, &attrs, argv_casted, envp_casted);
  268. if (res != 0) return kInvalidFd;
  269. // Disable echo in the new terminal, disable CR.
  270. struct termios termflags;
  271. tcgetattr(primary_fd, &termflags);
  272. termflags.c_oflag &= ~ONLCR;
  273. termflags.c_lflag &= ~ECHO;
  274. tcsetattr(primary_fd, TCSANOW, &termflags);
  275. // On success, do not close primary_fd on scope exit.
  276. fd_t fd = primary_fd;
  277. primary_fd = kInvalidFd;
  278. return fd;
  279. }
  280. fd_t internal_spawn(const char *argv[], const char *envp[], pid_t *pid) {
  281. // The client program may close its stdin and/or stdout and/or stderr thus
  282. // allowing open/posix_openpt to reuse file descriptors 0, 1 or 2. In this
  283. // case the communication is broken if either the parent or the child tries to
  284. // close or duplicate these descriptors. We temporarily reserve these
  285. // descriptors here to prevent this.
  286. fd_t low_fds[3];
  287. size_t count = 0;
  288. for (; count < 3; count++) {
  289. low_fds[count] = posix_openpt(O_RDWR);
  290. if (low_fds[count] >= STDERR_FILENO)
  291. break;
  292. }
  293. fd_t fd = internal_spawn_impl(argv, envp, pid);
  294. for (; count > 0; count--) {
  295. internal_close(low_fds[count]);
  296. }
  297. return fd;
  298. }
  299. uptr internal_rename(const char *oldpath, const char *newpath) {
  300. return rename(oldpath, newpath);
  301. }
  302. uptr internal_ftruncate(fd_t fd, uptr size) {
  303. return ftruncate(fd, size);
  304. }
  305. uptr internal_execve(const char *filename, char *const argv[],
  306. char *const envp[]) {
  307. return execve(filename, argv, envp);
  308. }
  309. uptr internal_waitpid(int pid, int *status, int options) {
  310. return waitpid(pid, status, options);
  311. }
  312. // ----------------- sanitizer_common.h
  313. bool FileExists(const char *filename) {
  314. if (ShouldMockFailureToOpen(filename))
  315. return false;
  316. struct stat st;
  317. if (stat(filename, &st))
  318. return false;
  319. // Sanity check: filename is a regular file.
  320. return S_ISREG(st.st_mode);
  321. }
  322. tid_t GetTid() {
  323. tid_t tid;
  324. pthread_threadid_np(nullptr, &tid);
  325. return tid;
  326. }
  327. void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
  328. uptr *stack_bottom) {
  329. CHECK(stack_top);
  330. CHECK(stack_bottom);
  331. uptr stacksize = pthread_get_stacksize_np(pthread_self());
  332. // pthread_get_stacksize_np() returns an incorrect stack size for the main
  333. // thread on Mavericks. See
  334. // https://github.com/google/sanitizers/issues/261
  335. if ((GetMacosAlignedVersion() >= MacosVersion(10, 9)) && at_initialization &&
  336. stacksize == (1 << 19)) {
  337. struct rlimit rl;
  338. CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
  339. // Most often rl.rlim_cur will be the desired 8M.
  340. if (rl.rlim_cur < kMaxThreadStackSize) {
  341. stacksize = rl.rlim_cur;
  342. } else {
  343. stacksize = kMaxThreadStackSize;
  344. }
  345. }
  346. void *stackaddr = pthread_get_stackaddr_np(pthread_self());
  347. *stack_top = (uptr)stackaddr;
  348. *stack_bottom = *stack_top - stacksize;
  349. }
  350. char **GetEnviron() {
  351. #if !SANITIZER_IOS
  352. char ***env_ptr = _NSGetEnviron();
  353. if (!env_ptr) {
  354. Report("_NSGetEnviron() returned NULL. Please make sure __asan_init() is "
  355. "called after libSystem_initializer().\n");
  356. CHECK(env_ptr);
  357. }
  358. char **environ = *env_ptr;
  359. #endif
  360. CHECK(environ);
  361. return environ;
  362. }
  363. const char *GetEnv(const char *name) {
  364. char **env = GetEnviron();
  365. uptr name_len = internal_strlen(name);
  366. while (*env != 0) {
  367. uptr len = internal_strlen(*env);
  368. if (len > name_len) {
  369. const char *p = *env;
  370. if (!internal_memcmp(p, name, name_len) &&
  371. p[name_len] == '=') { // Match.
  372. return *env + name_len + 1; // String starting after =.
  373. }
  374. }
  375. env++;
  376. }
  377. return 0;
  378. }
  379. uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
  380. CHECK_LE(kMaxPathLength, buf_len);
  381. // On OS X the executable path is saved to the stack by dyld. Reading it
  382. // from there is much faster than calling dladdr, especially for large
  383. // binaries with symbols.
  384. InternalMmapVector<char> exe_path(kMaxPathLength);
  385. uint32_t size = exe_path.size();
  386. if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
  387. realpath(exe_path.data(), buf) != 0) {
  388. return internal_strlen(buf);
  389. }
  390. return 0;
  391. }
  392. uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
  393. return ReadBinaryName(buf, buf_len);
  394. }
  395. void ReExec() {
  396. UNIMPLEMENTED();
  397. }
  398. void CheckASLR() {
  399. // Do nothing
  400. }
  401. void CheckMPROTECT() {
  402. // Do nothing
  403. }
  404. uptr GetPageSize() {
  405. return sysconf(_SC_PAGESIZE);
  406. }
  407. extern "C" unsigned malloc_num_zones;
  408. extern "C" malloc_zone_t **malloc_zones;
  409. malloc_zone_t sanitizer_zone;
  410. // We need to make sure that sanitizer_zone is registered as malloc_zones[0]. If
  411. // libmalloc tries to set up a different zone as malloc_zones[0], it will call
  412. // mprotect(malloc_zones, ..., PROT_READ). This interceptor will catch that and
  413. // make sure we are still the first (default) zone.
  414. void MprotectMallocZones(void *addr, int prot) {
  415. if (addr == malloc_zones && prot == PROT_READ) {
  416. if (malloc_num_zones > 1 && malloc_zones[0] != &sanitizer_zone) {
  417. for (unsigned i = 1; i < malloc_num_zones; i++) {
  418. if (malloc_zones[i] == &sanitizer_zone) {
  419. // Swap malloc_zones[0] and malloc_zones[i].
  420. malloc_zones[i] = malloc_zones[0];
  421. malloc_zones[0] = &sanitizer_zone;
  422. break;
  423. }
  424. }
  425. }
  426. }
  427. }
  428. void FutexWait(atomic_uint32_t *p, u32 cmp) {
  429. // FIXME: implement actual blocking.
  430. sched_yield();
  431. }
  432. void FutexWake(atomic_uint32_t *p, u32 count) {}
  433. u64 NanoTime() {
  434. timeval tv;
  435. internal_memset(&tv, 0, sizeof(tv));
  436. gettimeofday(&tv, 0);
  437. return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
  438. }
  439. // This needs to be called during initialization to avoid being racy.
  440. u64 MonotonicNanoTime() {
  441. static mach_timebase_info_data_t timebase_info;
  442. if (timebase_info.denom == 0) mach_timebase_info(&timebase_info);
  443. return (mach_absolute_time() * timebase_info.numer) / timebase_info.denom;
  444. }
  445. uptr GetTlsSize() {
  446. return 0;
  447. }
  448. void InitTlsSize() {
  449. }
  450. uptr TlsBaseAddr() {
  451. uptr segbase = 0;
  452. #if defined(__x86_64__)
  453. asm("movq %%gs:0,%0" : "=r"(segbase));
  454. #elif defined(__i386__)
  455. asm("movl %%gs:0,%0" : "=r"(segbase));
  456. #elif defined(__aarch64__)
  457. asm("mrs %x0, tpidrro_el0" : "=r"(segbase));
  458. segbase &= 0x07ul; // clearing lower bits, cpu id stored there
  459. #endif
  460. return segbase;
  461. }
  462. // The size of the tls on darwin does not appear to be well documented,
  463. // however the vm memory map suggests that it is 1024 uptrs in size,
  464. // with a size of 0x2000 bytes on x86_64 and 0x1000 bytes on i386.
  465. uptr TlsSize() {
  466. #if defined(__x86_64__) || defined(__i386__)
  467. return 1024 * sizeof(uptr);
  468. #else
  469. return 0;
  470. #endif
  471. }
  472. void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
  473. uptr *tls_addr, uptr *tls_size) {
  474. #if !SANITIZER_GO
  475. uptr stack_top, stack_bottom;
  476. GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
  477. *stk_addr = stack_bottom;
  478. *stk_size = stack_top - stack_bottom;
  479. *tls_addr = TlsBaseAddr();
  480. *tls_size = TlsSize();
  481. #else
  482. *stk_addr = 0;
  483. *stk_size = 0;
  484. *tls_addr = 0;
  485. *tls_size = 0;
  486. #endif
  487. }
  488. void ListOfModules::init() {
  489. clearOrInit();
  490. MemoryMappingLayout memory_mapping(false);
  491. memory_mapping.DumpListOfModules(&modules_);
  492. }
  493. void ListOfModules::fallbackInit() { clear(); }
  494. static HandleSignalMode GetHandleSignalModeImpl(int signum) {
  495. switch (signum) {
  496. case SIGABRT:
  497. return common_flags()->handle_abort;
  498. case SIGILL:
  499. return common_flags()->handle_sigill;
  500. case SIGTRAP:
  501. return common_flags()->handle_sigtrap;
  502. case SIGFPE:
  503. return common_flags()->handle_sigfpe;
  504. case SIGSEGV:
  505. return common_flags()->handle_segv;
  506. case SIGBUS:
  507. return common_flags()->handle_sigbus;
  508. }
  509. return kHandleSignalNo;
  510. }
  511. HandleSignalMode GetHandleSignalMode(int signum) {
  512. // Handling fatal signals on watchOS and tvOS devices is disallowed.
  513. if ((SANITIZER_WATCHOS || SANITIZER_TVOS) && !(SANITIZER_IOSSIM))
  514. return kHandleSignalNo;
  515. HandleSignalMode result = GetHandleSignalModeImpl(signum);
  516. if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
  517. return kHandleSignalExclusive;
  518. return result;
  519. }
  520. // Offset example:
  521. // XNU 17 -- macOS 10.13 -- iOS 11 -- tvOS 11 -- watchOS 4
  522. constexpr u16 GetOSMajorKernelOffset() {
  523. if (TARGET_OS_OSX) return 4;
  524. if (TARGET_OS_IOS || TARGET_OS_TV) return 6;
  525. if (TARGET_OS_WATCH) return 13;
  526. }
  527. using VersStr = char[64];
  528. static uptr ApproximateOSVersionViaKernelVersion(VersStr vers) {
  529. u16 kernel_major = GetDarwinKernelVersion().major;
  530. u16 offset = GetOSMajorKernelOffset();
  531. CHECK_GE(kernel_major, offset);
  532. u16 os_major = kernel_major - offset;
  533. const char *format = "%d.0";
  534. if (TARGET_OS_OSX) {
  535. if (os_major >= 16) { // macOS 11+
  536. os_major -= 5;
  537. } else { // macOS 10.15 and below
  538. format = "10.%d";
  539. }
  540. }
  541. return internal_snprintf(vers, sizeof(VersStr), format, os_major);
  542. }
  543. static void GetOSVersion(VersStr vers) {
  544. uptr len = sizeof(VersStr);
  545. if (SANITIZER_IOSSIM) {
  546. const char *vers_env = GetEnv("SIMULATOR_RUNTIME_VERSION");
  547. if (!vers_env) {
  548. Report("ERROR: Running in simulator but SIMULATOR_RUNTIME_VERSION env "
  549. "var is not set.\n");
  550. Die();
  551. }
  552. len = internal_strlcpy(vers, vers_env, len);
  553. } else {
  554. int res =
  555. internal_sysctlbyname("kern.osproductversion", vers, &len, nullptr, 0);
  556. // XNU 17 (macOS 10.13) and below do not provide the sysctl
  557. // `kern.osproductversion` entry (res != 0).
  558. bool no_os_version = res != 0;
  559. // For launchd, sanitizer initialization runs before sysctl is setup
  560. // (res == 0 && len != strlen(vers), vers is not a valid version). However,
  561. // the kernel version `kern.osrelease` is available.
  562. bool launchd = (res == 0 && internal_strlen(vers) < 3);
  563. if (launchd) CHECK_EQ(internal_getpid(), 1);
  564. if (no_os_version || launchd) {
  565. len = ApproximateOSVersionViaKernelVersion(vers);
  566. }
  567. }
  568. CHECK_LT(len, sizeof(VersStr));
  569. }
  570. void ParseVersion(const char *vers, u16 *major, u16 *minor) {
  571. // Format: <major>.<minor>[.<patch>]\0
  572. CHECK_GE(internal_strlen(vers), 3);
  573. const char *p = vers;
  574. *major = internal_simple_strtoll(p, &p, /*base=*/10);
  575. CHECK_EQ(*p, '.');
  576. p += 1;
  577. *minor = internal_simple_strtoll(p, &p, /*base=*/10);
  578. }
  579. // Aligned versions example:
  580. // macOS 10.15 -- iOS 13 -- tvOS 13 -- watchOS 6
  581. static void MapToMacos(u16 *major, u16 *minor) {
  582. if (TARGET_OS_OSX)
  583. return;
  584. if (TARGET_OS_IOS || TARGET_OS_TV)
  585. *major += 2;
  586. else if (TARGET_OS_WATCH)
  587. *major += 9;
  588. else
  589. UNREACHABLE("unsupported platform");
  590. if (*major >= 16) { // macOS 11+
  591. *major -= 5;
  592. } else { // macOS 10.15 and below
  593. *minor = *major;
  594. *major = 10;
  595. }
  596. }
  597. static MacosVersion GetMacosAlignedVersionInternal() {
  598. VersStr vers = {};
  599. GetOSVersion(vers);
  600. u16 major, minor;
  601. ParseVersion(vers, &major, &minor);
  602. MapToMacos(&major, &minor);
  603. return MacosVersion(major, minor);
  604. }
  605. static_assert(sizeof(MacosVersion) == sizeof(atomic_uint32_t::Type),
  606. "MacosVersion cache size");
  607. static atomic_uint32_t cached_macos_version;
  608. MacosVersion GetMacosAlignedVersion() {
  609. atomic_uint32_t::Type result =
  610. atomic_load(&cached_macos_version, memory_order_acquire);
  611. if (!result) {
  612. MacosVersion version = GetMacosAlignedVersionInternal();
  613. result = *reinterpret_cast<atomic_uint32_t::Type *>(&version);
  614. atomic_store(&cached_macos_version, result, memory_order_release);
  615. }
  616. return *reinterpret_cast<MacosVersion *>(&result);
  617. }
  618. DarwinKernelVersion GetDarwinKernelVersion() {
  619. VersStr vers = {};
  620. uptr len = sizeof(VersStr);
  621. int res = internal_sysctlbyname("kern.osrelease", vers, &len, nullptr, 0);
  622. CHECK_EQ(res, 0);
  623. CHECK_LT(len, sizeof(VersStr));
  624. u16 major, minor;
  625. ParseVersion(vers, &major, &minor);
  626. return DarwinKernelVersion(major, minor);
  627. }
  628. uptr GetRSS() {
  629. struct task_basic_info info;
  630. unsigned count = TASK_BASIC_INFO_COUNT;
  631. kern_return_t result =
  632. task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &count);
  633. if (UNLIKELY(result != KERN_SUCCESS)) {
  634. Report("Cannot get task info. Error: %d\n", result);
  635. Die();
  636. }
  637. return info.resident_size;
  638. }
  639. void *internal_start_thread(void *(*func)(void *arg), void *arg) {
  640. // Start the thread with signals blocked, otherwise it can steal user signals.
  641. __sanitizer_sigset_t set, old;
  642. internal_sigfillset(&set);
  643. internal_sigprocmask(SIG_SETMASK, &set, &old);
  644. pthread_t th;
  645. pthread_create(&th, 0, func, arg);
  646. internal_sigprocmask(SIG_SETMASK, &old, 0);
  647. return th;
  648. }
  649. void internal_join_thread(void *th) { pthread_join((pthread_t)th, 0); }
  650. #if !SANITIZER_GO
  651. static Mutex syslog_lock;
  652. # endif
  653. void WriteOneLineToSyslog(const char *s) {
  654. #if !SANITIZER_GO
  655. syslog_lock.CheckLocked();
  656. if (GetMacosAlignedVersion() >= MacosVersion(10, 12)) {
  657. os_log_error(OS_LOG_DEFAULT, "%{public}s", s);
  658. } else {
  659. asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
  660. }
  661. #endif
  662. }
  663. // buffer to store crash report application information
  664. static char crashreporter_info_buff[__sanitizer::kErrorMessageBufferSize] = {};
  665. static Mutex crashreporter_info_mutex;
  666. extern "C" {
  667. // Integrate with crash reporter libraries.
  668. #if HAVE_CRASHREPORTERCLIENT_H
  669. CRASH_REPORTER_CLIENT_HIDDEN
  670. struct crashreporter_annotations_t gCRAnnotations
  671. __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
  672. CRASHREPORTER_ANNOTATIONS_VERSION,
  673. 0,
  674. 0,
  675. 0,
  676. 0,
  677. 0,
  678. 0,
  679. #if CRASHREPORTER_ANNOTATIONS_VERSION > 4
  680. 0,
  681. #endif
  682. };
  683. #else
  684. // fall back to old crashreporter api
  685. static const char *__crashreporter_info__ __attribute__((__used__)) =
  686. &crashreporter_info_buff[0];
  687. asm(".desc ___crashreporter_info__, 0x10");
  688. #endif
  689. } // extern "C"
  690. static void CRAppendCrashLogMessage(const char *msg) {
  691. Lock l(&crashreporter_info_mutex);
  692. internal_strlcat(crashreporter_info_buff, msg,
  693. sizeof(crashreporter_info_buff));
  694. #if HAVE_CRASHREPORTERCLIENT_H
  695. (void)CRSetCrashLogMessage(crashreporter_info_buff);
  696. #endif
  697. }
  698. void LogMessageOnPrintf(const char *str) {
  699. // Log all printf output to CrashLog.
  700. if (common_flags()->abort_on_error)
  701. CRAppendCrashLogMessage(str);
  702. }
  703. void LogFullErrorReport(const char *buffer) {
  704. #if !SANITIZER_GO
  705. // Log with os_trace. This will make it into the crash log.
  706. #if SANITIZER_OS_TRACE
  707. if (GetMacosAlignedVersion() >= MacosVersion(10, 10)) {
  708. // os_trace requires the message (format parameter) to be a string literal.
  709. if (internal_strncmp(SanitizerToolName, "AddressSanitizer",
  710. sizeof("AddressSanitizer") - 1) == 0)
  711. os_trace("Address Sanitizer reported a failure.");
  712. else if (internal_strncmp(SanitizerToolName, "UndefinedBehaviorSanitizer",
  713. sizeof("UndefinedBehaviorSanitizer") - 1) == 0)
  714. os_trace("Undefined Behavior Sanitizer reported a failure.");
  715. else if (internal_strncmp(SanitizerToolName, "ThreadSanitizer",
  716. sizeof("ThreadSanitizer") - 1) == 0)
  717. os_trace("Thread Sanitizer reported a failure.");
  718. else
  719. os_trace("Sanitizer tool reported a failure.");
  720. if (common_flags()->log_to_syslog)
  721. os_trace("Consult syslog for more information.");
  722. }
  723. #endif
  724. // Log to syslog.
  725. // The logging on OS X may call pthread_create so we need the threading
  726. // environment to be fully initialized. Also, this should never be called when
  727. // holding the thread registry lock since that may result in a deadlock. If
  728. // the reporting thread holds the thread registry mutex, and asl_log waits
  729. // for GCD to dispatch a new thread, the process will deadlock, because the
  730. // pthread_create wrapper needs to acquire the lock as well.
  731. Lock l(&syslog_lock);
  732. if (common_flags()->log_to_syslog)
  733. WriteToSyslog(buffer);
  734. // The report is added to CrashLog as part of logging all of Printf output.
  735. #endif
  736. }
  737. SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
  738. #if defined(__x86_64__) || defined(__i386__)
  739. ucontext_t *ucontext = static_cast<ucontext_t*>(context);
  740. return ucontext->uc_mcontext->__es.__err & 2 /*T_PF_WRITE*/ ? Write : Read;
  741. #else
  742. return Unknown;
  743. #endif
  744. }
  745. bool SignalContext::IsTrueFaultingAddress() const {
  746. auto si = static_cast<const siginfo_t *>(siginfo);
  747. // "Real" SIGSEGV codes (e.g., SEGV_MAPERR, SEGV_MAPERR) are non-zero.
  748. return si->si_signo == SIGSEGV && si->si_code != 0;
  749. }
  750. #if defined(__aarch64__) && defined(arm_thread_state64_get_sp)
  751. #define AARCH64_GET_REG(r) \
  752. (uptr)ptrauth_strip( \
  753. (void *)arm_thread_state64_get_##r(ucontext->uc_mcontext->__ss), 0)
  754. #else
  755. #define AARCH64_GET_REG(r) (uptr)ucontext->uc_mcontext->__ss.__##r
  756. #endif
  757. static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
  758. ucontext_t *ucontext = (ucontext_t*)context;
  759. # if defined(__aarch64__)
  760. *pc = AARCH64_GET_REG(pc);
  761. # if defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
  762. *bp = AARCH64_GET_REG(fp);
  763. # else
  764. *bp = AARCH64_GET_REG(lr);
  765. # endif
  766. *sp = AARCH64_GET_REG(sp);
  767. # elif defined(__x86_64__)
  768. *pc = ucontext->uc_mcontext->__ss.__rip;
  769. *bp = ucontext->uc_mcontext->__ss.__rbp;
  770. *sp = ucontext->uc_mcontext->__ss.__rsp;
  771. # elif defined(__arm__)
  772. *pc = ucontext->uc_mcontext->__ss.__pc;
  773. *bp = ucontext->uc_mcontext->__ss.__r[7];
  774. *sp = ucontext->uc_mcontext->__ss.__sp;
  775. # elif defined(__i386__)
  776. *pc = ucontext->uc_mcontext->__ss.__eip;
  777. *bp = ucontext->uc_mcontext->__ss.__ebp;
  778. *sp = ucontext->uc_mcontext->__ss.__esp;
  779. # else
  780. # error "Unknown architecture"
  781. # endif
  782. }
  783. void SignalContext::InitPcSpBp() {
  784. addr = (uptr)ptrauth_strip((void *)addr, 0);
  785. GetPcSpBp(context, &pc, &sp, &bp);
  786. }
  787. // ASan/TSan use mmap in a way that creates “deallocation gaps” which triggers
  788. // EXC_GUARD exceptions on macOS 10.15+ (XNU 19.0+).
  789. static void DisableMmapExcGuardExceptions() {
  790. using task_exc_guard_behavior_t = uint32_t;
  791. using task_set_exc_guard_behavior_t =
  792. kern_return_t(task_t task, task_exc_guard_behavior_t behavior);
  793. auto *set_behavior = (task_set_exc_guard_behavior_t *)dlsym(
  794. RTLD_DEFAULT, "task_set_exc_guard_behavior");
  795. if (set_behavior == nullptr) return;
  796. const task_exc_guard_behavior_t task_exc_guard_none = 0;
  797. set_behavior(mach_task_self(), task_exc_guard_none);
  798. }
  799. void InitializePlatformEarly() {
  800. // Only use xnu_fast_mmap when on x86_64 and the kernel supports it.
  801. use_xnu_fast_mmap =
  802. #if defined(__x86_64__)
  803. GetDarwinKernelVersion() >= DarwinKernelVersion(17, 5);
  804. #else
  805. false;
  806. #endif
  807. if (GetDarwinKernelVersion() >= DarwinKernelVersion(19, 0))
  808. DisableMmapExcGuardExceptions();
  809. }
  810. #if !SANITIZER_GO
  811. static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES";
  812. LowLevelAllocator allocator_for_env;
  813. // Change the value of the env var |name|, leaking the original value.
  814. // If |name_value| is NULL, the variable is deleted from the environment,
  815. // otherwise the corresponding "NAME=value" string is replaced with
  816. // |name_value|.
  817. void LeakyResetEnv(const char *name, const char *name_value) {
  818. char **env = GetEnviron();
  819. uptr name_len = internal_strlen(name);
  820. while (*env != 0) {
  821. uptr len = internal_strlen(*env);
  822. if (len > name_len) {
  823. const char *p = *env;
  824. if (!internal_memcmp(p, name, name_len) && p[name_len] == '=') {
  825. // Match.
  826. if (name_value) {
  827. // Replace the old value with the new one.
  828. *env = const_cast<char*>(name_value);
  829. } else {
  830. // Shift the subsequent pointers back.
  831. char **del = env;
  832. do {
  833. del[0] = del[1];
  834. } while (*del++);
  835. }
  836. }
  837. }
  838. env++;
  839. }
  840. }
  841. SANITIZER_WEAK_CXX_DEFAULT_IMPL
  842. bool ReexecDisabled() {
  843. return false;
  844. }
  845. static bool DyldNeedsEnvVariable() {
  846. // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
  847. // DYLD_INSERT_LIBRARIES is not set.
  848. return GetMacosAlignedVersion() < MacosVersion(10, 11);
  849. }
  850. void MaybeReexec() {
  851. // FIXME: This should really live in some "InitializePlatform" method.
  852. MonotonicNanoTime();
  853. if (ReexecDisabled()) return;
  854. // Make sure the dynamic runtime library is preloaded so that the
  855. // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec
  856. // ourselves.
  857. Dl_info info;
  858. RAW_CHECK(dladdr((void*)((uptr)&__sanitizer_report_error_summary), &info));
  859. char *dyld_insert_libraries =
  860. const_cast<char*>(GetEnv(kDyldInsertLibraries));
  861. uptr old_env_len = dyld_insert_libraries ?
  862. internal_strlen(dyld_insert_libraries) : 0;
  863. uptr fname_len = internal_strlen(info.dli_fname);
  864. const char *dylib_name = StripModuleName(info.dli_fname);
  865. uptr dylib_name_len = internal_strlen(dylib_name);
  866. bool lib_is_in_env = dyld_insert_libraries &&
  867. internal_strstr(dyld_insert_libraries, dylib_name);
  868. if (DyldNeedsEnvVariable() && !lib_is_in_env) {
  869. // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
  870. // library.
  871. InternalMmapVector<char> program_name(1024);
  872. uint32_t buf_size = program_name.size();
  873. _NSGetExecutablePath(program_name.data(), &buf_size);
  874. char *new_env = const_cast<char*>(info.dli_fname);
  875. if (dyld_insert_libraries) {
  876. // Append the runtime dylib name to the existing value of
  877. // DYLD_INSERT_LIBRARIES.
  878. new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2);
  879. internal_strncpy(new_env, dyld_insert_libraries, old_env_len);
  880. new_env[old_env_len] = ':';
  881. // Copy fname_len and add a trailing zero.
  882. internal_strncpy(new_env + old_env_len + 1, info.dli_fname,
  883. fname_len + 1);
  884. // Ok to use setenv() since the wrappers don't depend on the value of
  885. // asan_inited.
  886. setenv(kDyldInsertLibraries, new_env, /*overwrite*/1);
  887. } else {
  888. // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name.
  889. setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0);
  890. }
  891. VReport(1, "exec()-ing the program with\n");
  892. VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env);
  893. VReport(1, "to enable wrappers.\n");
  894. execv(program_name.data(), *_NSGetArgv());
  895. // We get here only if execv() failed.
  896. Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, "
  897. "which is required for the sanitizer to work. We tried to set the "
  898. "environment variable and re-execute itself, but execv() failed, "
  899. "possibly because of sandbox restrictions. Make sure to launch the "
  900. "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env);
  901. RAW_CHECK("execv failed" && 0);
  902. }
  903. // Verify that interceptors really work. We'll use dlsym to locate
  904. // "pthread_create", if interceptors are working, it should really point to
  905. // "wrap_pthread_create" within our own dylib.
  906. Dl_info info_pthread_create;
  907. void *dlopen_addr = dlsym(RTLD_DEFAULT, "pthread_create");
  908. RAW_CHECK(dladdr(dlopen_addr, &info_pthread_create));
  909. if (internal_strcmp(info.dli_fname, info_pthread_create.dli_fname) != 0) {
  910. Report(
  911. "ERROR: Interceptors are not working. This may be because %s is "
  912. "loaded too late (e.g. via dlopen). Please launch the executable "
  913. "with:\n%s=%s\n",
  914. SanitizerToolName, kDyldInsertLibraries, info.dli_fname);
  915. RAW_CHECK("interceptors not installed" && 0);
  916. }
  917. if (!lib_is_in_env)
  918. return;
  919. if (!common_flags()->strip_env)
  920. return;
  921. // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove
  922. // the dylib from the environment variable, because interceptors are installed
  923. // and we don't want our children to inherit the variable.
  924. uptr env_name_len = internal_strlen(kDyldInsertLibraries);
  925. // Allocate memory to hold the previous env var name, its value, the '='
  926. // sign and the '\0' char.
  927. char *new_env = (char*)allocator_for_env.Allocate(
  928. old_env_len + 2 + env_name_len);
  929. RAW_CHECK(new_env);
  930. internal_memset(new_env, '\0', old_env_len + 2 + env_name_len);
  931. internal_strncpy(new_env, kDyldInsertLibraries, env_name_len);
  932. new_env[env_name_len] = '=';
  933. char *new_env_pos = new_env + env_name_len + 1;
  934. // Iterate over colon-separated pieces of |dyld_insert_libraries|.
  935. char *piece_start = dyld_insert_libraries;
  936. char *piece_end = NULL;
  937. char *old_env_end = dyld_insert_libraries + old_env_len;
  938. do {
  939. if (piece_start[0] == ':') piece_start++;
  940. piece_end = internal_strchr(piece_start, ':');
  941. if (!piece_end) piece_end = dyld_insert_libraries + old_env_len;
  942. if ((uptr)(piece_start - dyld_insert_libraries) > old_env_len) break;
  943. uptr piece_len = piece_end - piece_start;
  944. char *filename_start =
  945. (char *)internal_memrchr(piece_start, '/', piece_len);
  946. uptr filename_len = piece_len;
  947. if (filename_start) {
  948. filename_start += 1;
  949. filename_len = piece_len - (filename_start - piece_start);
  950. } else {
  951. filename_start = piece_start;
  952. }
  953. // If the current piece isn't the runtime library name,
  954. // append it to new_env.
  955. if ((dylib_name_len != filename_len) ||
  956. (internal_memcmp(filename_start, dylib_name, dylib_name_len) != 0)) {
  957. if (new_env_pos != new_env + env_name_len + 1) {
  958. new_env_pos[0] = ':';
  959. new_env_pos++;
  960. }
  961. internal_strncpy(new_env_pos, piece_start, piece_len);
  962. new_env_pos += piece_len;
  963. }
  964. // Move on to the next piece.
  965. piece_start = piece_end;
  966. } while (piece_start < old_env_end);
  967. // Can't use setenv() here, because it requires the allocator to be
  968. // initialized.
  969. // FIXME: instead of filtering DYLD_INSERT_LIBRARIES here, do it in
  970. // a separate function called after InitializeAllocator().
  971. if (new_env_pos == new_env + env_name_len + 1) new_env = NULL;
  972. LeakyResetEnv(kDyldInsertLibraries, new_env);
  973. }
  974. #endif // SANITIZER_GO
  975. char **GetArgv() {
  976. return *_NSGetArgv();
  977. }
  978. #if SANITIZER_IOS && !SANITIZER_IOSSIM
  979. // The task_vm_info struct is normally provided by the macOS SDK, but we need
  980. // fields only available in 10.12+. Declare the struct manually to be able to
  981. // build against older SDKs.
  982. struct __sanitizer_task_vm_info {
  983. mach_vm_size_t virtual_size;
  984. integer_t region_count;
  985. integer_t page_size;
  986. mach_vm_size_t resident_size;
  987. mach_vm_size_t resident_size_peak;
  988. mach_vm_size_t device;
  989. mach_vm_size_t device_peak;
  990. mach_vm_size_t internal;
  991. mach_vm_size_t internal_peak;
  992. mach_vm_size_t external;
  993. mach_vm_size_t external_peak;
  994. mach_vm_size_t reusable;
  995. mach_vm_size_t reusable_peak;
  996. mach_vm_size_t purgeable_volatile_pmap;
  997. mach_vm_size_t purgeable_volatile_resident;
  998. mach_vm_size_t purgeable_volatile_virtual;
  999. mach_vm_size_t compressed;
  1000. mach_vm_size_t compressed_peak;
  1001. mach_vm_size_t compressed_lifetime;
  1002. mach_vm_size_t phys_footprint;
  1003. mach_vm_address_t min_address;
  1004. mach_vm_address_t max_address;
  1005. };
  1006. #define __SANITIZER_TASK_VM_INFO_COUNT ((mach_msg_type_number_t) \
  1007. (sizeof(__sanitizer_task_vm_info) / sizeof(natural_t)))
  1008. static uptr GetTaskInfoMaxAddress() {
  1009. __sanitizer_task_vm_info vm_info = {} /* zero initialize */;
  1010. mach_msg_type_number_t count = __SANITIZER_TASK_VM_INFO_COUNT;
  1011. int err = task_info(mach_task_self(), TASK_VM_INFO, (int *)&vm_info, &count);
  1012. return err ? 0 : vm_info.max_address;
  1013. }
  1014. uptr GetMaxUserVirtualAddress() {
  1015. static uptr max_vm = GetTaskInfoMaxAddress();
  1016. if (max_vm != 0) {
  1017. const uptr ret_value = max_vm - 1;
  1018. CHECK_LE(ret_value, SANITIZER_MMAP_RANGE_SIZE);
  1019. return ret_value;
  1020. }
  1021. // xnu cannot provide vm address limit
  1022. # if SANITIZER_WORDSIZE == 32
  1023. constexpr uptr fallback_max_vm = 0xffe00000 - 1;
  1024. # else
  1025. constexpr uptr fallback_max_vm = 0x200000000 - 1;
  1026. # endif
  1027. static_assert(fallback_max_vm <= SANITIZER_MMAP_RANGE_SIZE,
  1028. "Max virtual address must be less than mmap range size.");
  1029. return fallback_max_vm;
  1030. }
  1031. #else // !SANITIZER_IOS
  1032. uptr GetMaxUserVirtualAddress() {
  1033. # if SANITIZER_WORDSIZE == 64
  1034. constexpr uptr max_vm = (1ULL << 47) - 1; // 0x00007fffffffffffUL;
  1035. # else // SANITIZER_WORDSIZE == 32
  1036. static_assert(SANITIZER_WORDSIZE == 32, "Wrong wordsize");
  1037. constexpr uptr max_vm = (1ULL << 32) - 1; // 0xffffffff;
  1038. # endif
  1039. static_assert(max_vm <= SANITIZER_MMAP_RANGE_SIZE,
  1040. "Max virtual address must be less than mmap range size.");
  1041. return max_vm;
  1042. }
  1043. #endif
  1044. uptr GetMaxVirtualAddress() {
  1045. return GetMaxUserVirtualAddress();
  1046. }
  1047. uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
  1048. uptr min_shadow_base_alignment, uptr &high_mem_end) {
  1049. const uptr granularity = GetMmapGranularity();
  1050. const uptr alignment =
  1051. Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
  1052. const uptr left_padding =
  1053. Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
  1054. uptr space_size = shadow_size_bytes + left_padding;
  1055. uptr largest_gap_found = 0;
  1056. uptr max_occupied_addr = 0;
  1057. VReport(2, "FindDynamicShadowStart, space_size = %p\n", (void *)space_size);
  1058. uptr shadow_start =
  1059. FindAvailableMemoryRange(space_size, alignment, granularity,
  1060. &largest_gap_found, &max_occupied_addr);
  1061. // If the shadow doesn't fit, restrict the address space to make it fit.
  1062. if (shadow_start == 0) {
  1063. VReport(
  1064. 2,
  1065. "Shadow doesn't fit, largest_gap_found = %p, max_occupied_addr = %p\n",
  1066. (void *)largest_gap_found, (void *)max_occupied_addr);
  1067. uptr new_max_vm = RoundDownTo(largest_gap_found << shadow_scale, alignment);
  1068. if (new_max_vm < max_occupied_addr) {
  1069. Report("Unable to find a memory range for dynamic shadow.\n");
  1070. Report(
  1071. "space_size = %p, largest_gap_found = %p, max_occupied_addr = %p, "
  1072. "new_max_vm = %p\n",
  1073. (void *)space_size, (void *)largest_gap_found,
  1074. (void *)max_occupied_addr, (void *)new_max_vm);
  1075. CHECK(0 && "cannot place shadow");
  1076. }
  1077. RestrictMemoryToMaxAddress(new_max_vm);
  1078. high_mem_end = new_max_vm - 1;
  1079. space_size = (high_mem_end >> shadow_scale) + left_padding;
  1080. VReport(2, "FindDynamicShadowStart, space_size = %p\n", (void *)space_size);
  1081. shadow_start = FindAvailableMemoryRange(space_size, alignment, granularity,
  1082. nullptr, nullptr);
  1083. if (shadow_start == 0) {
  1084. Report("Unable to find a memory range after restricting VM.\n");
  1085. CHECK(0 && "cannot place shadow after restricting vm");
  1086. }
  1087. }
  1088. CHECK_NE((uptr)0, shadow_start);
  1089. CHECK(IsAligned(shadow_start, alignment));
  1090. return shadow_start;
  1091. }
  1092. uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
  1093. uptr num_aliases, uptr ring_buffer_size) {
  1094. CHECK(false && "HWASan aliasing is unimplemented on Mac");
  1095. return 0;
  1096. }
  1097. uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
  1098. uptr *largest_gap_found,
  1099. uptr *max_occupied_addr) {
  1100. typedef vm_region_submap_short_info_data_64_t RegionInfo;
  1101. enum { kRegionInfoSize = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 };
  1102. // Start searching for available memory region past PAGEZERO, which is
  1103. // 4KB on 32-bit and 4GB on 64-bit.
  1104. mach_vm_address_t start_address =
  1105. (SANITIZER_WORDSIZE == 32) ? 0x000000001000 : 0x000100000000;
  1106. mach_vm_address_t address = start_address;
  1107. mach_vm_address_t free_begin = start_address;
  1108. kern_return_t kr = KERN_SUCCESS;
  1109. if (largest_gap_found) *largest_gap_found = 0;
  1110. if (max_occupied_addr) *max_occupied_addr = 0;
  1111. while (kr == KERN_SUCCESS) {
  1112. mach_vm_size_t vmsize = 0;
  1113. natural_t depth = 0;
  1114. RegionInfo vminfo;
  1115. mach_msg_type_number_t count = kRegionInfoSize;
  1116. kr = mach_vm_region_recurse(mach_task_self(), &address, &vmsize, &depth,
  1117. (vm_region_info_t)&vminfo, &count);
  1118. if (kr == KERN_INVALID_ADDRESS) {
  1119. // No more regions beyond "address", consider the gap at the end of VM.
  1120. address = GetMaxVirtualAddress() + 1;
  1121. vmsize = 0;
  1122. } else {
  1123. if (max_occupied_addr) *max_occupied_addr = address + vmsize;
  1124. }
  1125. if (free_begin != address) {
  1126. // We found a free region [free_begin..address-1].
  1127. uptr gap_start = RoundUpTo((uptr)free_begin + left_padding, alignment);
  1128. uptr gap_end = RoundDownTo((uptr)address, alignment);
  1129. uptr gap_size = gap_end > gap_start ? gap_end - gap_start : 0;
  1130. if (size < gap_size) {
  1131. return gap_start;
  1132. }
  1133. if (largest_gap_found && *largest_gap_found < gap_size) {
  1134. *largest_gap_found = gap_size;
  1135. }
  1136. }
  1137. // Move to the next region.
  1138. address += vmsize;
  1139. free_begin = address;
  1140. }
  1141. // We looked at all free regions and could not find one large enough.
  1142. return 0;
  1143. }
  1144. // FIXME implement on this platform.
  1145. void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
  1146. void SignalContext::DumpAllRegisters(void *context) {
  1147. Report("Register values:\n");
  1148. ucontext_t *ucontext = (ucontext_t*)context;
  1149. # define DUMPREG64(r) \
  1150. Printf("%s = 0x%016llx ", #r, ucontext->uc_mcontext->__ss.__ ## r);
  1151. # define DUMPREGA64(r) \
  1152. Printf(" %s = 0x%016lx ", #r, AARCH64_GET_REG(r));
  1153. # define DUMPREG32(r) \
  1154. Printf("%s = 0x%08x ", #r, ucontext->uc_mcontext->__ss.__ ## r);
  1155. # define DUMPREG_(r) Printf(" "); DUMPREG(r);
  1156. # define DUMPREG__(r) Printf(" "); DUMPREG(r);
  1157. # define DUMPREG___(r) Printf(" "); DUMPREG(r);
  1158. # if defined(__x86_64__)
  1159. # define DUMPREG(r) DUMPREG64(r)
  1160. DUMPREG(rax); DUMPREG(rbx); DUMPREG(rcx); DUMPREG(rdx); Printf("\n");
  1161. DUMPREG(rdi); DUMPREG(rsi); DUMPREG(rbp); DUMPREG(rsp); Printf("\n");
  1162. DUMPREG_(r8); DUMPREG_(r9); DUMPREG(r10); DUMPREG(r11); Printf("\n");
  1163. DUMPREG(r12); DUMPREG(r13); DUMPREG(r14); DUMPREG(r15); Printf("\n");
  1164. # elif defined(__i386__)
  1165. # define DUMPREG(r) DUMPREG32(r)
  1166. DUMPREG(eax); DUMPREG(ebx); DUMPREG(ecx); DUMPREG(edx); Printf("\n");
  1167. DUMPREG(edi); DUMPREG(esi); DUMPREG(ebp); DUMPREG(esp); Printf("\n");
  1168. # elif defined(__aarch64__)
  1169. # define DUMPREG(r) DUMPREG64(r)
  1170. DUMPREG_(x[0]); DUMPREG_(x[1]); DUMPREG_(x[2]); DUMPREG_(x[3]); Printf("\n");
  1171. DUMPREG_(x[4]); DUMPREG_(x[5]); DUMPREG_(x[6]); DUMPREG_(x[7]); Printf("\n");
  1172. DUMPREG_(x[8]); DUMPREG_(x[9]); DUMPREG(x[10]); DUMPREG(x[11]); Printf("\n");
  1173. DUMPREG(x[12]); DUMPREG(x[13]); DUMPREG(x[14]); DUMPREG(x[15]); Printf("\n");
  1174. DUMPREG(x[16]); DUMPREG(x[17]); DUMPREG(x[18]); DUMPREG(x[19]); Printf("\n");
  1175. DUMPREG(x[20]); DUMPREG(x[21]); DUMPREG(x[22]); DUMPREG(x[23]); Printf("\n");
  1176. DUMPREG(x[24]); DUMPREG(x[25]); DUMPREG(x[26]); DUMPREG(x[27]); Printf("\n");
  1177. DUMPREG(x[28]); DUMPREGA64(fp); DUMPREGA64(lr); DUMPREGA64(sp); Printf("\n");
  1178. # elif defined(__arm__)
  1179. # define DUMPREG(r) DUMPREG32(r)
  1180. DUMPREG_(r[0]); DUMPREG_(r[1]); DUMPREG_(r[2]); DUMPREG_(r[3]); Printf("\n");
  1181. DUMPREG_(r[4]); DUMPREG_(r[5]); DUMPREG_(r[6]); DUMPREG_(r[7]); Printf("\n");
  1182. DUMPREG_(r[8]); DUMPREG_(r[9]); DUMPREG(r[10]); DUMPREG(r[11]); Printf("\n");
  1183. DUMPREG(r[12]); DUMPREG___(sp); DUMPREG___(lr); DUMPREG___(pc); Printf("\n");
  1184. # else
  1185. # error "Unknown architecture"
  1186. # endif
  1187. # undef DUMPREG64
  1188. # undef DUMPREG32
  1189. # undef DUMPREG_
  1190. # undef DUMPREG__
  1191. # undef DUMPREG___
  1192. # undef DUMPREG
  1193. }
  1194. static inline bool CompareBaseAddress(const LoadedModule &a,
  1195. const LoadedModule &b) {
  1196. return a.base_address() < b.base_address();
  1197. }
  1198. void FormatUUID(char *out, uptr size, const u8 *uuid) {
  1199. internal_snprintf(out, size,
  1200. "<%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-"
  1201. "%02X%02X%02X%02X%02X%02X>",
  1202. uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5],
  1203. uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11],
  1204. uuid[12], uuid[13], uuid[14], uuid[15]);
  1205. }
  1206. void DumpProcessMap() {
  1207. Printf("Process module map:\n");
  1208. MemoryMappingLayout memory_mapping(false);
  1209. InternalMmapVector<LoadedModule> modules;
  1210. modules.reserve(128);
  1211. memory_mapping.DumpListOfModules(&modules);
  1212. Sort(modules.data(), modules.size(), CompareBaseAddress);
  1213. for (uptr i = 0; i < modules.size(); ++i) {
  1214. char uuid_str[128];
  1215. FormatUUID(uuid_str, sizeof(uuid_str), modules[i].uuid());
  1216. Printf("0x%zx-0x%zx %s (%s) %s\n", modules[i].base_address(),
  1217. modules[i].max_executable_address(), modules[i].full_name(),
  1218. ModuleArchToString(modules[i].arch()), uuid_str);
  1219. }
  1220. Printf("End of module map.\n");
  1221. }
  1222. void CheckNoDeepBind(const char *filename, int flag) {
  1223. // Do nothing.
  1224. }
  1225. bool GetRandom(void *buffer, uptr length, bool blocking) {
  1226. if (!buffer || !length || length > 256)
  1227. return false;
  1228. // arc4random never fails.
  1229. REAL(arc4random_buf)(buffer, length);
  1230. return true;
  1231. }
  1232. u32 GetNumberOfCPUs() {
  1233. return (u32)sysconf(_SC_NPROCESSORS_ONLN);
  1234. }
  1235. void InitializePlatformCommonFlags(CommonFlags *cf) {}
  1236. } // namespace __sanitizer
  1237. #endif // SANITIZER_MAC