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