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