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