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