1 //===-- sanitizer_posix_libcdep.cc ----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements libc-dependent POSIX-specific functions
12 // from sanitizer_libc.h.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
19 #include "sanitizer_common.h"
20 #include "sanitizer_flags.h"
21 #include "sanitizer_platform_limits_netbsd.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 #include "sanitizer_stacktrace.h"
27 #include "sanitizer_symbolizer.h"
35 #include <sys/resource.h>
38 #include <sys/types.h>
43 // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
44 // that, it was never implemented. So just define it to zero.
46 #define MAP_NORESERVE 0
49 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
51 namespace __sanitizer {
57 uptr GetThreadSelf() {
58 return (uptr)pthread_self();
61 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
62 uptr page_size = GetPageSizeCached();
63 uptr beg_aligned = RoundUpTo(beg, page_size);
64 uptr end_aligned = RoundDownTo(end, page_size);
65 if (beg_aligned < end_aligned)
66 // In the default Solaris compilation environment, madvise() is declared
67 // to take a caddr_t arg; casting it to void * results in an invalid
68 // conversion error, so use char * instead.
69 madvise((char *)beg_aligned, end_aligned - beg_aligned,
70 SANITIZER_MADVISE_DONTNEED);
73 void NoHugePagesInRegion(uptr addr, uptr size) {
74 #ifdef MADV_NOHUGEPAGE // May not be defined on old systems.
75 madvise((void *)addr, size, MADV_NOHUGEPAGE);
76 #endif // MADV_NOHUGEPAGE
79 void DontDumpShadowMemory(uptr addr, uptr length) {
81 madvise((void *)addr, length, MADV_DONTDUMP);
85 static rlim_t getlim(int res) {
87 CHECK_EQ(0, getrlimit(res, &rlim));
91 static void setlim(int res, rlim_t lim) {
92 // The following magic is to prevent clang from replacing it with memset.
93 volatile struct rlimit rlim;
96 if (setrlimit(res, const_cast<struct rlimit *>(&rlim))) {
97 Report("ERROR: %s setrlimit() failed %d\n", SanitizerToolName, errno);
102 void DisableCoreDumperIfNecessary() {
103 if (common_flags()->disable_coredump) {
104 setlim(RLIMIT_CORE, 0);
108 bool StackSizeIsUnlimited() {
109 rlim_t stack_size = getlim(RLIMIT_STACK);
110 return (stack_size == RLIM_INFINITY);
113 uptr GetStackSizeLimitInBytes() {
114 return (uptr)getlim(RLIMIT_STACK);
117 void SetStackSizeLimitInBytes(uptr limit) {
118 setlim(RLIMIT_STACK, (rlim_t)limit);
119 CHECK(!StackSizeIsUnlimited());
122 bool AddressSpaceIsUnlimited() {
123 rlim_t as_size = getlim(RLIMIT_AS);
124 return (as_size == RLIM_INFINITY);
127 void SetAddressSpaceUnlimited() {
128 setlim(RLIMIT_AS, RLIM_INFINITY);
129 CHECK(AddressSpaceIsUnlimited());
132 void SleepForSeconds(int seconds) {
136 void SleepForMillis(int millis) {
137 usleep(millis * 1000);
142 // If we are handling SIGABRT, unhandle it first.
143 // TODO(vitalybuka): Check if handler belongs to sanitizer.
144 if (GetHandleSignalMode(SIGABRT) != kHandleSignalNo) {
145 struct sigaction sigact;
146 internal_memset(&sigact, 0, sizeof(sigact));
147 sigact.sa_sigaction = (sa_sigaction_t)SIG_DFL;
148 internal_sigaction(SIGABRT, &sigact, nullptr);
155 int Atexit(void (*function)(void)) {
157 return atexit(function);
163 bool SupportsColoredOutput(fd_t fd) {
164 return isatty(fd) != 0;
168 // TODO(glider): different tools may require different altstack size.
169 static const uptr kAltStackSize = SIGSTKSZ * 4; // SIGSTKSZ is not enough.
171 void SetAlternateSignalStack() {
172 stack_t altstack, oldstack;
173 CHECK_EQ(0, sigaltstack(nullptr, &oldstack));
174 // If the alternate stack is already in place, do nothing.
175 // Android always sets an alternate stack, but it's too small for us.
176 if (!SANITIZER_ANDROID && !(oldstack.ss_flags & SS_DISABLE)) return;
177 // TODO(glider): the mapped stack should have the MAP_STACK flag in the
178 // future. It is not required by man 2 sigaltstack now (they're using
180 void* base = MmapOrDie(kAltStackSize, __func__);
181 altstack.ss_sp = (char*) base;
182 altstack.ss_flags = 0;
183 altstack.ss_size = kAltStackSize;
184 CHECK_EQ(0, sigaltstack(&altstack, nullptr));
187 void UnsetAlternateSignalStack() {
188 stack_t altstack, oldstack;
189 altstack.ss_sp = nullptr;
190 altstack.ss_flags = SS_DISABLE;
191 altstack.ss_size = kAltStackSize; // Some sane value required on Darwin.
192 CHECK_EQ(0, sigaltstack(&altstack, &oldstack));
193 UnmapOrDie(oldstack.ss_sp, oldstack.ss_size);
196 static void MaybeInstallSigaction(int signum,
197 SignalHandlerType handler) {
198 if (GetHandleSignalMode(signum) == kHandleSignalNo) return;
200 struct sigaction sigact;
201 internal_memset(&sigact, 0, sizeof(sigact));
202 sigact.sa_sigaction = (sa_sigaction_t)handler;
203 // Do not block the signal from being received in that signal's handler.
204 // Clients are responsible for handling this correctly.
205 sigact.sa_flags = SA_SIGINFO | SA_NODEFER;
206 if (common_flags()->use_sigaltstack) sigact.sa_flags |= SA_ONSTACK;
207 CHECK_EQ(0, internal_sigaction(signum, &sigact, nullptr));
208 VReport(1, "Installed the sigaction for signal %d\n", signum);
211 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
212 // Set the alternate signal stack for the main thread.
213 // This will cause SetAlternateSignalStack to be called twice, but the stack
214 // will be actually set only once.
215 if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
216 MaybeInstallSigaction(SIGSEGV, handler);
217 MaybeInstallSigaction(SIGBUS, handler);
218 MaybeInstallSigaction(SIGABRT, handler);
219 MaybeInstallSigaction(SIGFPE, handler);
220 MaybeInstallSigaction(SIGILL, handler);
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.
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;
233 bool IsStackAccess = addr + 512 > sp && addr < sp + 0xFFFF;
237 // Large stack frames can be allocated with e.g.
239 // stdux r1,r1,r0 # store sp to [sp-10000] and update sp by -10000
240 // If the store faults then sp will not have been updated, so test above
241 // will not work, because the fault address will be more than just "slightly"
243 if (!IsStackAccess && IsAccessibleMemoryRange(pc, 4)) {
244 u32 inst = *(unsigned *)pc;
245 u32 ra = (inst >> 16) & 0x1F;
246 u32 opcd = inst >> 26;
247 u32 xo = (inst >> 1) & 0x3FF;
248 // Check for store-with-update to sp. The instructions we accept are:
249 // stbu rs,d(ra) stbux rs,ra,rb
250 // sthu rs,d(ra) sthux rs,ra,rb
251 // stwu rs,d(ra) stwux rs,ra,rb
252 // stdu rs,ds(ra) stdux rs,ra,rb
253 // where ra is r1 (the stack pointer).
255 (opcd == 39 || opcd == 45 || opcd == 37 || opcd == 62 ||
256 (opcd == 31 && (xo == 247 || xo == 439 || xo == 183 || xo == 181))))
257 IsStackAccess = true;
259 #endif // __powerpc__
261 // We also check si_code to filter out SEGV caused by something else other
262 // then hitting the guard page or unmapped memory, like, for example,
263 // unaligned memory access.
264 auto si = static_cast<const siginfo_t *>(siginfo);
265 return IsStackAccess &&
266 (si->si_code == si_SEGV_MAPERR || si->si_code == si_SEGV_ACCERR);
269 #endif // SANITIZER_GO
271 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
272 uptr page_size = GetPageSizeCached();
273 // Checking too large memory ranges is slow.
274 CHECK_LT(size, page_size * 10);
279 internal_write(sock_pair[1], reinterpret_cast<void *>(beg), size);
282 if (internal_iserror(bytes_written, &write_errno)) {
283 CHECK_EQ(EFAULT, write_errno);
286 result = (bytes_written == size);
288 internal_close(sock_pair[0]);
289 internal_close(sock_pair[1]);
293 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
294 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
295 // to read the file mappings from /proc/self/maps. Luckily, neither the
296 // process will be able to load additional libraries, so it's fine to use the
298 MemoryMappingLayout::CacheMemoryMappings();
299 // Same for /proc/self/exe in the symbolizer.
301 Symbolizer::GetOrInit()->PrepareForSandboxing();
305 #if SANITIZER_ANDROID || SANITIZER_GO
306 int GetNamedMappingFd(const char *name, uptr size) {
310 int GetNamedMappingFd(const char *name, uptr size) {
311 if (!common_flags()->decorate_proc_maps)
314 CHECK(internal_strlen(name) < sizeof(shmname) - 10);
315 internal_snprintf(shmname, sizeof(shmname), "%zu [%s]", internal_getpid(),
317 int fd = shm_open(shmname, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);
319 int res = internal_ftruncate(fd, size);
321 res = shm_unlink(shmname);
327 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
328 int fd = name ? GetNamedMappingFd(name, size) : -1;
329 unsigned flags = MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE;
330 if (fd == -1) flags |= MAP_ANON;
332 uptr PageSize = GetPageSizeCached();
333 uptr p = internal_mmap((void *)(fixed_addr & ~(PageSize - 1)),
334 RoundUpTo(size, PageSize), PROT_READ | PROT_WRITE,
337 if (internal_iserror(p, &reserrno))
338 Report("ERROR: %s failed to "
339 "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
340 SanitizerToolName, size, size, fixed_addr, reserrno);
341 IncreaseTotalMmap(size);
345 uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
346 // We don't pass `name` along because, when you enable `decorate_proc_maps`
347 // AND actually use a named mapping AND are using a sanitizer intercepting
348 // `open` (e.g. TSAN, ESAN), then you'll get a failure during initialization.
349 // TODO(flowerhack): Fix the implementation of GetNamedMappingFd to solve
352 base_ = MmapFixedNoAccess(fixed_addr, size);
354 base_ = MmapNoAccess(size);
358 (void)os_handle_; // unsupported
359 return reinterpret_cast<uptr>(base_);
362 // Uses fixed_addr for now.
363 // Will use offset instead once we've implemented this function for real.
364 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size) {
365 return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
368 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size) {
369 return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
372 void ReservedAddressRange::Unmap(uptr addr, uptr size) {
373 void* addr_as_void = reinterpret_cast<void*>(addr);
374 uptr base_as_uptr = reinterpret_cast<uptr>(base_);
375 // Only unmap at the beginning or end of the range.
376 CHECK((addr_as_void == base_) || (addr + size == base_as_uptr + size_));
377 CHECK_LE(size, size_);
378 UnmapOrDie(reinterpret_cast<void*>(addr), size);
379 if (addr_as_void == base_) {
380 base_ = reinterpret_cast<void*>(addr + size);
382 size_ = size_ - size;
385 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
386 int fd = name ? GetNamedMappingFd(name, size) : -1;
387 unsigned flags = MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE;
388 if (fd == -1) flags |= MAP_ANON;
390 return (void *)internal_mmap((void *)fixed_addr, size, PROT_NONE, flags, fd,
394 void *MmapNoAccess(uptr size) {
395 unsigned flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;
396 return (void *)internal_mmap(nullptr, size, PROT_NONE, flags, -1, 0);
399 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
401 SANITIZER_WEAK_ATTRIBUTE int
402 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
405 int my_pthread_attr_getstack(void *attr, void **addr, uptr *size) {
406 #if !SANITIZER_GO && !SANITIZER_MAC
407 if (&real_pthread_attr_getstack)
408 return real_pthread_attr_getstack((pthread_attr_t *)attr, addr,
411 return pthread_attr_getstack((pthread_attr_t *)attr, addr, (size_t *)size);
415 void AdjustStackSize(void *attr_) {
416 pthread_attr_t *attr = (pthread_attr_t *)attr_;
419 my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
420 // GLibC will return (0 - stacksize) as the stack address in the case when
421 // stacksize is set, but stackaddr is not.
422 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
423 // We place a lot of tool data into TLS, account for that.
424 const uptr minstacksize = GetTlsSize() + 128*1024;
425 if (stacksize < minstacksize) {
427 if (stacksize != 0) {
428 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
430 pthread_attr_setstacksize(attr, minstacksize);
433 Printf("Sanitizer: pre-allocated stack size is insufficient: "
434 "%zu < %zu\n", stacksize, minstacksize);
435 Printf("Sanitizer: pthread_create is likely to fail.\n");
439 #endif // !SANITIZER_GO
441 pid_t StartSubprocess(const char *program, const char *const argv[],
442 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
443 auto file_closer = at_scope_exit([&] {
444 if (stdin_fd != kInvalidFd) {
445 internal_close(stdin_fd);
447 if (stdout_fd != kInvalidFd) {
448 internal_close(stdout_fd);
450 if (stderr_fd != kInvalidFd) {
451 internal_close(stderr_fd);
455 int pid = internal_fork();
459 if (internal_iserror(pid, &rverrno)) {
460 Report("WARNING: failed to fork (errno %d)\n", rverrno);
467 if (stdin_fd != kInvalidFd) {
468 internal_close(STDIN_FILENO);
469 internal_dup2(stdin_fd, STDIN_FILENO);
470 internal_close(stdin_fd);
472 if (stdout_fd != kInvalidFd) {
473 internal_close(STDOUT_FILENO);
474 internal_dup2(stdout_fd, STDOUT_FILENO);
475 internal_close(stdout_fd);
477 if (stderr_fd != kInvalidFd) {
478 internal_close(STDERR_FILENO);
479 internal_dup2(stderr_fd, STDERR_FILENO);
480 internal_close(stderr_fd);
483 for (int fd = sysconf(_SC_OPEN_MAX); fd > 2; fd--) internal_close(fd);
485 execv(program, const_cast<char **>(&argv[0]));
492 bool IsProcessRunning(pid_t pid) {
494 uptr waitpid_status = internal_waitpid(pid, &process_status, WNOHANG);
496 if (internal_iserror(waitpid_status, &local_errno)) {
497 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
500 return waitpid_status == 0;
503 int WaitForProcess(pid_t pid) {
505 uptr waitpid_status = internal_waitpid(pid, &process_status, 0);
507 if (internal_iserror(waitpid_status, &local_errno)) {
508 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
511 return process_status;
514 bool IsStateDetached(int state) {
515 return state == PTHREAD_CREATE_DETACHED;
518 } // namespace __sanitizer
520 #endif // SANITIZER_POSIX