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