sanitizer_posix_libcdep.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. //===-- sanitizer_posix_libcdep.cpp ---------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is shared between AddressSanitizer and ThreadSanitizer
  10. // run-time libraries and implements libc-dependent POSIX-specific functions
  11. // from sanitizer_libc.h.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_platform.h"
  14. #if SANITIZER_POSIX
  15. #include "sanitizer_common.h"
  16. #include "sanitizer_flags.h"
  17. #include "sanitizer_platform_limits_netbsd.h"
  18. #include "sanitizer_platform_limits_posix.h"
  19. #include "sanitizer_platform_limits_solaris.h"
  20. #include "sanitizer_posix.h"
  21. #include "sanitizer_procmaps.h"
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <pthread.h>
  25. #include <signal.h>
  26. #include <stdlib.h>
  27. #include <sys/mman.h>
  28. #include <sys/resource.h>
  29. #include <sys/stat.h>
  30. #include <sys/time.h>
  31. #include <sys/types.h>
  32. #include <sys/wait.h>
  33. #include <unistd.h>
  34. #if SANITIZER_FREEBSD
  35. // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
  36. // that, it was never implemented. So just define it to zero.
  37. #undef MAP_NORESERVE
  38. #define MAP_NORESERVE 0
  39. #endif
  40. typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
  41. namespace __sanitizer {
  42. u32 GetUid() {
  43. return getuid();
  44. }
  45. uptr GetThreadSelf() {
  46. return (uptr)pthread_self();
  47. }
  48. void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
  49. uptr page_size = GetPageSizeCached();
  50. uptr beg_aligned = RoundUpTo(beg, page_size);
  51. uptr end_aligned = RoundDownTo(end, page_size);
  52. if (beg_aligned < end_aligned)
  53. internal_madvise(beg_aligned, end_aligned - beg_aligned,
  54. SANITIZER_MADVISE_DONTNEED);
  55. }
  56. void SetShadowRegionHugePageMode(uptr addr, uptr size) {
  57. #ifdef MADV_NOHUGEPAGE // May not be defined on old systems.
  58. if (common_flags()->no_huge_pages_for_shadow)
  59. internal_madvise(addr, size, MADV_NOHUGEPAGE);
  60. else
  61. internal_madvise(addr, size, MADV_HUGEPAGE);
  62. #endif // MADV_NOHUGEPAGE
  63. }
  64. bool DontDumpShadowMemory(uptr addr, uptr length) {
  65. #if defined(MADV_DONTDUMP)
  66. return internal_madvise(addr, length, MADV_DONTDUMP) == 0;
  67. #elif defined(MADV_NOCORE)
  68. return internal_madvise(addr, length, MADV_NOCORE) == 0;
  69. #else
  70. return true;
  71. #endif // MADV_DONTDUMP
  72. }
  73. static rlim_t getlim(int res) {
  74. rlimit rlim;
  75. CHECK_EQ(0, getrlimit(res, &rlim));
  76. return rlim.rlim_cur;
  77. }
  78. static void setlim(int res, rlim_t lim) {
  79. struct rlimit rlim;
  80. if (getrlimit(res, const_cast<struct rlimit *>(&rlim))) {
  81. Report("ERROR: %s getrlimit() failed %d\n", SanitizerToolName, errno);
  82. Die();
  83. }
  84. rlim.rlim_cur = lim;
  85. if (setrlimit(res, const_cast<struct rlimit *>(&rlim))) {
  86. Report("ERROR: %s setrlimit() failed %d\n", SanitizerToolName, errno);
  87. Die();
  88. }
  89. }
  90. void DisableCoreDumperIfNecessary() {
  91. if (common_flags()->disable_coredump) {
  92. setlim(RLIMIT_CORE, 0);
  93. }
  94. }
  95. bool StackSizeIsUnlimited() {
  96. rlim_t stack_size = getlim(RLIMIT_STACK);
  97. return (stack_size == RLIM_INFINITY);
  98. }
  99. void SetStackSizeLimitInBytes(uptr limit) {
  100. setlim(RLIMIT_STACK, (rlim_t)limit);
  101. CHECK(!StackSizeIsUnlimited());
  102. }
  103. bool AddressSpaceIsUnlimited() {
  104. rlim_t as_size = getlim(RLIMIT_AS);
  105. return (as_size == RLIM_INFINITY);
  106. }
  107. void SetAddressSpaceUnlimited() {
  108. setlim(RLIMIT_AS, RLIM_INFINITY);
  109. CHECK(AddressSpaceIsUnlimited());
  110. }
  111. void Abort() {
  112. #if !SANITIZER_GO
  113. // If we are handling SIGABRT, unhandle it first.
  114. // TODO(vitalybuka): Check if handler belongs to sanitizer.
  115. if (GetHandleSignalMode(SIGABRT) != kHandleSignalNo) {
  116. struct sigaction sigact;
  117. internal_memset(&sigact, 0, sizeof(sigact));
  118. sigact.sa_handler = SIG_DFL;
  119. internal_sigaction(SIGABRT, &sigact, nullptr);
  120. }
  121. #endif
  122. abort();
  123. }
  124. int Atexit(void (*function)(void)) {
  125. #if !SANITIZER_GO
  126. return atexit(function);
  127. #else
  128. return 0;
  129. #endif
  130. }
  131. bool CreateDir(const char *pathname) { return mkdir(pathname, 0755) == 0; }
  132. bool SupportsColoredOutput(fd_t fd) {
  133. return isatty(fd) != 0;
  134. }
  135. #if !SANITIZER_GO
  136. // TODO(glider): different tools may require different altstack size.
  137. static uptr GetAltStackSize() {
  138. // Note: since GLIBC_2.31, SIGSTKSZ may be a function call, so this may be
  139. // more costly that you think. However GetAltStackSize is only call 2-3 times
  140. // per thread so don't cache the evaluation.
  141. return SIGSTKSZ * 4;
  142. }
  143. void SetAlternateSignalStack() {
  144. stack_t altstack, oldstack;
  145. CHECK_EQ(0, sigaltstack(nullptr, &oldstack));
  146. // If the alternate stack is already in place, do nothing.
  147. // Android always sets an alternate stack, but it's too small for us.
  148. if (!SANITIZER_ANDROID && !(oldstack.ss_flags & SS_DISABLE)) return;
  149. // TODO(glider): the mapped stack should have the MAP_STACK flag in the
  150. // future. It is not required by man 2 sigaltstack now (they're using
  151. // malloc()).
  152. altstack.ss_size = GetAltStackSize();
  153. altstack.ss_sp = (char *)MmapOrDie(altstack.ss_size, __func__);
  154. altstack.ss_flags = 0;
  155. CHECK_EQ(0, sigaltstack(&altstack, nullptr));
  156. }
  157. void UnsetAlternateSignalStack() {
  158. stack_t altstack, oldstack;
  159. altstack.ss_sp = nullptr;
  160. altstack.ss_flags = SS_DISABLE;
  161. altstack.ss_size = GetAltStackSize(); // Some sane value required on Darwin.
  162. CHECK_EQ(0, sigaltstack(&altstack, &oldstack));
  163. UnmapOrDie(oldstack.ss_sp, oldstack.ss_size);
  164. }
  165. static void MaybeInstallSigaction(int signum,
  166. SignalHandlerType handler) {
  167. if (GetHandleSignalMode(signum) == kHandleSignalNo) return;
  168. struct sigaction sigact;
  169. internal_memset(&sigact, 0, sizeof(sigact));
  170. sigact.sa_sigaction = (sa_sigaction_t)handler;
  171. // Do not block the signal from being received in that signal's handler.
  172. // Clients are responsible for handling this correctly.
  173. sigact.sa_flags = SA_SIGINFO | SA_NODEFER;
  174. if (common_flags()->use_sigaltstack) sigact.sa_flags |= SA_ONSTACK;
  175. CHECK_EQ(0, internal_sigaction(signum, &sigact, nullptr));
  176. VReport(1, "Installed the sigaction for signal %d\n", signum);
  177. }
  178. void InstallDeadlySignalHandlers(SignalHandlerType handler) {
  179. // Set the alternate signal stack for the main thread.
  180. // This will cause SetAlternateSignalStack to be called twice, but the stack
  181. // will be actually set only once.
  182. if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
  183. MaybeInstallSigaction(SIGSEGV, handler);
  184. MaybeInstallSigaction(SIGBUS, handler);
  185. MaybeInstallSigaction(SIGABRT, handler);
  186. MaybeInstallSigaction(SIGFPE, handler);
  187. MaybeInstallSigaction(SIGILL, handler);
  188. MaybeInstallSigaction(SIGTRAP, handler);
  189. }
  190. bool SignalContext::IsStackOverflow() const {
  191. // Access at a reasonable offset above SP, or slightly below it (to account
  192. // for x86_64 or PowerPC redzone, ARM push of multiple registers, etc) is
  193. // probably a stack overflow.
  194. #ifdef __s390__
  195. // On s390, the fault address in siginfo points to start of the page, not
  196. // to the precise word that was accessed. Mask off the low bits of sp to
  197. // take it into account.
  198. bool IsStackAccess = addr >= (sp & ~0xFFF) && addr < sp + 0xFFFF;
  199. #else
  200. // Let's accept up to a page size away from top of stack. Things like stack
  201. // probing can trigger accesses with such large offsets.
  202. bool IsStackAccess = addr + GetPageSizeCached() > sp && addr < sp + 0xFFFF;
  203. #endif
  204. #if __powerpc__
  205. // Large stack frames can be allocated with e.g.
  206. // lis r0,-10000
  207. // stdux r1,r1,r0 # store sp to [sp-10000] and update sp by -10000
  208. // If the store faults then sp will not have been updated, so test above
  209. // will not work, because the fault address will be more than just "slightly"
  210. // below sp.
  211. if (!IsStackAccess && IsAccessibleMemoryRange(pc, 4)) {
  212. u32 inst = *(unsigned *)pc;
  213. u32 ra = (inst >> 16) & 0x1F;
  214. u32 opcd = inst >> 26;
  215. u32 xo = (inst >> 1) & 0x3FF;
  216. // Check for store-with-update to sp. The instructions we accept are:
  217. // stbu rs,d(ra) stbux rs,ra,rb
  218. // sthu rs,d(ra) sthux rs,ra,rb
  219. // stwu rs,d(ra) stwux rs,ra,rb
  220. // stdu rs,ds(ra) stdux rs,ra,rb
  221. // where ra is r1 (the stack pointer).
  222. if (ra == 1 &&
  223. (opcd == 39 || opcd == 45 || opcd == 37 || opcd == 62 ||
  224. (opcd == 31 && (xo == 247 || xo == 439 || xo == 183 || xo == 181))))
  225. IsStackAccess = true;
  226. }
  227. #endif // __powerpc__
  228. // We also check si_code to filter out SEGV caused by something else other
  229. // then hitting the guard page or unmapped memory, like, for example,
  230. // unaligned memory access.
  231. auto si = static_cast<const siginfo_t *>(siginfo);
  232. return IsStackAccess &&
  233. (si->si_code == si_SEGV_MAPERR || si->si_code == si_SEGV_ACCERR);
  234. }
  235. #endif // SANITIZER_GO
  236. bool IsAccessibleMemoryRange(uptr beg, uptr size) {
  237. uptr page_size = GetPageSizeCached();
  238. // Checking too large memory ranges is slow.
  239. CHECK_LT(size, page_size * 10);
  240. int sock_pair[2];
  241. if (pipe(sock_pair))
  242. return false;
  243. uptr bytes_written =
  244. internal_write(sock_pair[1], reinterpret_cast<void *>(beg), size);
  245. int write_errno;
  246. bool result;
  247. if (internal_iserror(bytes_written, &write_errno)) {
  248. CHECK_EQ(EFAULT, write_errno);
  249. result = false;
  250. } else {
  251. result = (bytes_written == size);
  252. }
  253. internal_close(sock_pair[0]);
  254. internal_close(sock_pair[1]);
  255. return result;
  256. }
  257. void PlatformPrepareForSandboxing(void *args) {
  258. // Some kinds of sandboxes may forbid filesystem access, so we won't be able
  259. // to read the file mappings from /proc/self/maps. Luckily, neither the
  260. // process will be able to load additional libraries, so it's fine to use the
  261. // cached mappings.
  262. MemoryMappingLayout::CacheMemoryMappings();
  263. }
  264. static bool MmapFixed(uptr fixed_addr, uptr size, int additional_flags,
  265. const char *name) {
  266. size = RoundUpTo(size, GetPageSizeCached());
  267. fixed_addr = RoundDownTo(fixed_addr, GetPageSizeCached());
  268. uptr p =
  269. MmapNamed((void *)fixed_addr, size, PROT_READ | PROT_WRITE,
  270. MAP_PRIVATE | MAP_FIXED | additional_flags | MAP_ANON, name);
  271. int reserrno;
  272. if (internal_iserror(p, &reserrno)) {
  273. Report("ERROR: %s failed to "
  274. "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
  275. SanitizerToolName, size, size, fixed_addr, reserrno);
  276. return false;
  277. }
  278. IncreaseTotalMmap(size);
  279. return true;
  280. }
  281. bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
  282. return MmapFixed(fixed_addr, size, MAP_NORESERVE, name);
  283. }
  284. bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) {
  285. #if SANITIZER_FREEBSD
  286. if (common_flags()->no_huge_pages_for_shadow)
  287. return MmapFixedNoReserve(fixed_addr, size, name);
  288. // MAP_NORESERVE is implicit with FreeBSD
  289. return MmapFixed(fixed_addr, size, MAP_ALIGNED_SUPER, name);
  290. #else
  291. bool r = MmapFixedNoReserve(fixed_addr, size, name);
  292. if (r)
  293. SetShadowRegionHugePageMode(fixed_addr, size);
  294. return r;
  295. #endif
  296. }
  297. uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
  298. base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size, name)
  299. : MmapNoAccess(size);
  300. size_ = size;
  301. name_ = name;
  302. (void)os_handle_; // unsupported
  303. return reinterpret_cast<uptr>(base_);
  304. }
  305. // Uses fixed_addr for now.
  306. // Will use offset instead once we've implemented this function for real.
  307. uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size, const char *name) {
  308. return reinterpret_cast<uptr>(
  309. MmapFixedOrDieOnFatalError(fixed_addr, size, name));
  310. }
  311. uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size,
  312. const char *name) {
  313. return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size, name));
  314. }
  315. void ReservedAddressRange::Unmap(uptr addr, uptr size) {
  316. CHECK_LE(size, size_);
  317. if (addr == reinterpret_cast<uptr>(base_))
  318. // If we unmap the whole range, just null out the base.
  319. base_ = (size == size_) ? nullptr : reinterpret_cast<void*>(addr + size);
  320. else
  321. CHECK_EQ(addr + size, reinterpret_cast<uptr>(base_) + size_);
  322. size_ -= size;
  323. UnmapOrDie(reinterpret_cast<void*>(addr), size);
  324. }
  325. void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
  326. return (void *)MmapNamed((void *)fixed_addr, size, PROT_NONE,
  327. MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE | MAP_ANON,
  328. name);
  329. }
  330. void *MmapNoAccess(uptr size) {
  331. unsigned flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;
  332. return (void *)internal_mmap(nullptr, size, PROT_NONE, flags, -1, 0);
  333. }
  334. // This function is defined elsewhere if we intercepted pthread_attr_getstack.
  335. extern "C" {
  336. SANITIZER_WEAK_ATTRIBUTE int
  337. real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
  338. } // extern "C"
  339. int my_pthread_attr_getstack(void *attr, void **addr, uptr *size) {
  340. #if !SANITIZER_GO && !SANITIZER_APPLE
  341. if (&real_pthread_attr_getstack)
  342. return real_pthread_attr_getstack((pthread_attr_t *)attr, addr,
  343. (size_t *)size);
  344. #endif
  345. return pthread_attr_getstack((pthread_attr_t *)attr, addr, (size_t *)size);
  346. }
  347. #if !SANITIZER_GO
  348. void AdjustStackSize(void *attr_) {
  349. pthread_attr_t *attr = (pthread_attr_t *)attr_;
  350. uptr stackaddr = 0;
  351. uptr stacksize = 0;
  352. my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
  353. // GLibC will return (0 - stacksize) as the stack address in the case when
  354. // stacksize is set, but stackaddr is not.
  355. bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
  356. // We place a lot of tool data into TLS, account for that.
  357. const uptr minstacksize = GetTlsSize() + 128*1024;
  358. if (stacksize < minstacksize) {
  359. if (!stack_set) {
  360. if (stacksize != 0) {
  361. VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
  362. minstacksize);
  363. pthread_attr_setstacksize(attr, minstacksize);
  364. }
  365. } else {
  366. Printf("Sanitizer: pre-allocated stack size is insufficient: "
  367. "%zu < %zu\n", stacksize, minstacksize);
  368. Printf("Sanitizer: pthread_create is likely to fail.\n");
  369. }
  370. }
  371. }
  372. #endif // !SANITIZER_GO
  373. pid_t StartSubprocess(const char *program, const char *const argv[],
  374. const char *const envp[], fd_t stdin_fd, fd_t stdout_fd,
  375. fd_t stderr_fd) {
  376. auto file_closer = at_scope_exit([&] {
  377. if (stdin_fd != kInvalidFd) {
  378. internal_close(stdin_fd);
  379. }
  380. if (stdout_fd != kInvalidFd) {
  381. internal_close(stdout_fd);
  382. }
  383. if (stderr_fd != kInvalidFd) {
  384. internal_close(stderr_fd);
  385. }
  386. });
  387. int pid = internal_fork();
  388. if (pid < 0) {
  389. int rverrno;
  390. if (internal_iserror(pid, &rverrno)) {
  391. Report("WARNING: failed to fork (errno %d)\n", rverrno);
  392. }
  393. return pid;
  394. }
  395. if (pid == 0) {
  396. // Child subprocess
  397. if (stdin_fd != kInvalidFd) {
  398. internal_close(STDIN_FILENO);
  399. internal_dup2(stdin_fd, STDIN_FILENO);
  400. internal_close(stdin_fd);
  401. }
  402. if (stdout_fd != kInvalidFd) {
  403. internal_close(STDOUT_FILENO);
  404. internal_dup2(stdout_fd, STDOUT_FILENO);
  405. internal_close(stdout_fd);
  406. }
  407. if (stderr_fd != kInvalidFd) {
  408. internal_close(STDERR_FILENO);
  409. internal_dup2(stderr_fd, STDERR_FILENO);
  410. internal_close(stderr_fd);
  411. }
  412. for (int fd = sysconf(_SC_OPEN_MAX); fd > 2; fd--) internal_close(fd);
  413. internal_execve(program, const_cast<char **>(&argv[0]),
  414. const_cast<char *const *>(envp));
  415. internal__exit(1);
  416. }
  417. return pid;
  418. }
  419. bool IsProcessRunning(pid_t pid) {
  420. int process_status;
  421. uptr waitpid_status = internal_waitpid(pid, &process_status, WNOHANG);
  422. int local_errno;
  423. if (internal_iserror(waitpid_status, &local_errno)) {
  424. VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
  425. return false;
  426. }
  427. return waitpid_status == 0;
  428. }
  429. int WaitForProcess(pid_t pid) {
  430. int process_status;
  431. uptr waitpid_status = internal_waitpid(pid, &process_status, 0);
  432. int local_errno;
  433. if (internal_iserror(waitpid_status, &local_errno)) {
  434. VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
  435. return -1;
  436. }
  437. return process_status;
  438. }
  439. bool IsStateDetached(int state) {
  440. return state == PTHREAD_CREATE_DETACHED;
  441. }
  442. } // namespace __sanitizer
  443. #endif // SANITIZER_POSIX