1 //===-- sanitizer_posix_libcdep.cc ----------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.h"
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"
33 #include <sys/resource.h>
36 #include <sys/types.h>
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.
44 #define MAP_NORESERVE 0
47 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
49 namespace __sanitizer {
55 uptr GetThreadSelf() {
56 return (uptr)pthread_self();
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);
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;
76 #endif // MADV_NOHUGEPAGE
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;
86 #endif // MADV_DONTDUMP
89 static rlim_t getlim(int res) {
91 CHECK_EQ(0, getrlimit(res, &rlim));
95 static void setlim(int res, rlim_t lim) {
97 if (getrlimit(res, const_cast<struct rlimit *>(&rlim))) {
98 Report("ERROR: %s getrlimit() failed %d\n", SanitizerToolName, errno);
102 if (setrlimit(res, const_cast<struct rlimit *>(&rlim))) {
103 Report("ERROR: %s setrlimit() failed %d\n", SanitizerToolName, errno);
108 void DisableCoreDumperIfNecessary() {
109 if (common_flags()->disable_coredump) {
110 setlim(RLIMIT_CORE, 0);
114 bool StackSizeIsUnlimited() {
115 rlim_t stack_size = getlim(RLIMIT_STACK);
116 return (stack_size == RLIM_INFINITY);
119 void SetStackSizeLimitInBytes(uptr limit) {
120 setlim(RLIMIT_STACK, (rlim_t)limit);
121 CHECK(!StackSizeIsUnlimited());
124 bool AddressSpaceIsUnlimited() {
125 rlim_t as_size = getlim(RLIMIT_AS);
126 return (as_size == RLIM_INFINITY);
129 void SetAddressSpaceUnlimited() {
130 setlim(RLIMIT_AS, RLIM_INFINITY);
131 CHECK(AddressSpaceIsUnlimited());
134 void SleepForSeconds(int seconds) {
138 void SleepForMillis(int millis) {
139 usleep(millis * 1000);
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);
157 int Atexit(void (*function)(void)) {
159 return atexit(function);
165 bool SupportsColoredOutput(fd_t fd) {
166 return isatty(fd) != 0;
170 // TODO(glider): different tools may require different altstack size.
171 static const uptr kAltStackSize = SIGSTKSZ * 4; // SIGSTKSZ is not enough.
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
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));
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);
198 static void MaybeInstallSigaction(int signum,
199 SignalHandlerType handler) {
200 if (GetHandleSignalMode(signum) == kHandleSignalNo) return;
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);
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);
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.
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;
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;
242 // Large stack frames can be allocated with e.g.
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"
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).
260 (opcd == 39 || opcd == 45 || opcd == 37 || opcd == 62 ||
261 (opcd == 31 && (xo == 247 || xo == 439 || xo == 183 || xo == 181))))
262 IsStackAccess = true;
264 #endif // __powerpc__
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);
274 #endif // SANITIZER_GO
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);
284 internal_write(sock_pair[1], reinterpret_cast<void *>(beg), size);
287 if (internal_iserror(bytes_written, &write_errno)) {
288 CHECK_EQ(EFAULT, write_errno);
291 result = (bytes_written == size);
293 internal_close(sock_pair[0]);
294 internal_close(sock_pair[1]);
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
303 MemoryMappingLayout::CacheMemoryMappings();
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);
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);
318 IncreaseTotalMmap(size);
322 uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
323 base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size, name)
324 : MmapNoAccess(size);
327 (void)os_handle_; // unsupported
328 return reinterpret_cast<uptr>(base_);
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));
338 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size,
340 return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size, name));
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);
349 CHECK_EQ(addr + size, reinterpret_cast<uptr>(base_) + size_);
351 UnmapOrDie(reinterpret_cast<void*>(addr), size);
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,
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);
365 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
367 SANITIZER_WEAK_ATTRIBUTE int
368 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
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,
377 return pthread_attr_getstack((pthread_attr_t *)attr, addr, (size_t *)size);
381 void AdjustStackSize(void *attr_) {
382 pthread_attr_t *attr = (pthread_attr_t *)attr_;
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) {
393 if (stacksize != 0) {
394 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
396 pthread_attr_setstacksize(attr, minstacksize);
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");
405 #endif // !SANITIZER_GO
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);
413 if (stdout_fd != kInvalidFd) {
414 internal_close(stdout_fd);
416 if (stderr_fd != kInvalidFd) {
417 internal_close(stderr_fd);
421 int pid = internal_fork();
425 if (internal_iserror(pid, &rverrno)) {
426 Report("WARNING: failed to fork (errno %d)\n", rverrno);
433 if (stdin_fd != kInvalidFd) {
434 internal_close(STDIN_FILENO);
435 internal_dup2(stdin_fd, STDIN_FILENO);
436 internal_close(stdin_fd);
438 if (stdout_fd != kInvalidFd) {
439 internal_close(STDOUT_FILENO);
440 internal_dup2(stdout_fd, STDOUT_FILENO);
441 internal_close(stdout_fd);
443 if (stderr_fd != kInvalidFd) {
444 internal_close(STDERR_FILENO);
445 internal_dup2(stderr_fd, STDERR_FILENO);
446 internal_close(stderr_fd);
449 for (int fd = sysconf(_SC_OPEN_MAX); fd > 2; fd--) internal_close(fd);
451 execv(program, const_cast<char **>(&argv[0]));
458 bool IsProcessRunning(pid_t pid) {
460 uptr waitpid_status = internal_waitpid(pid, &process_status, WNOHANG);
462 if (internal_iserror(waitpid_status, &local_errno)) {
463 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
466 return waitpid_status == 0;
469 int WaitForProcess(pid_t pid) {
471 uptr waitpid_status = internal_waitpid(pid, &process_status, 0);
473 if (internal_iserror(waitpid_status, &local_errno)) {
474 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
477 return process_status;
480 bool IsStateDetached(int state) {
481 return state == PTHREAD_CREATE_DETACHED;
484 } // namespace __sanitizer
486 #endif // SANITIZER_POSIX