sanitizer_mac.cpp 46 KB

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