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_posix.h"
22 #include "sanitizer_posix.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_stacktrace.h"
25 #include "sanitizer_symbolizer.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 madvise((void*)beg_aligned, end_aligned - beg_aligned, MADV_DONTNEED);
67 void NoHugePagesInRegion(uptr addr, uptr size) {
68 #ifdef MADV_NOHUGEPAGE // May not be defined on old systems.
69 madvise((void *)addr, size, MADV_NOHUGEPAGE);
70 #endif // MADV_NOHUGEPAGE
73 void DontDumpShadowMemory(uptr addr, uptr length) {
75 madvise((void *)addr, length, MADV_DONTDUMP);
79 static rlim_t getlim(int res) {
81 CHECK_EQ(0, getrlimit(res, &rlim));
85 static void setlim(int res, rlim_t lim) {
86 // The following magic is to prevent clang from replacing it with memset.
87 volatile struct rlimit rlim;
90 if (setrlimit(res, const_cast<struct rlimit *>(&rlim))) {
91 Report("ERROR: %s setrlimit() failed %d\n", SanitizerToolName, errno);
96 void DisableCoreDumperIfNecessary() {
97 if (common_flags()->disable_coredump) {
98 setlim(RLIMIT_CORE, 0);
102 bool StackSizeIsUnlimited() {
103 rlim_t stack_size = getlim(RLIMIT_STACK);
104 return (stack_size == RLIM_INFINITY);
107 uptr GetStackSizeLimitInBytes() {
108 return (uptr)getlim(RLIMIT_STACK);
111 void SetStackSizeLimitInBytes(uptr limit) {
112 setlim(RLIMIT_STACK, (rlim_t)limit);
113 CHECK(!StackSizeIsUnlimited());
116 bool AddressSpaceIsUnlimited() {
117 rlim_t as_size = getlim(RLIMIT_AS);
118 return (as_size == RLIM_INFINITY);
121 void SetAddressSpaceUnlimited() {
122 setlim(RLIMIT_AS, RLIM_INFINITY);
123 CHECK(AddressSpaceIsUnlimited());
126 void SleepForSeconds(int seconds) {
130 void SleepForMillis(int millis) {
131 usleep(millis * 1000);
136 // If we are handling SIGABRT, unhandle it first.
137 // TODO(vitalybuka): Check if handler belongs to sanitizer.
138 if (GetHandleSignalMode(SIGABRT) != kHandleSignalNo) {
139 struct sigaction sigact;
140 internal_memset(&sigact, 0, sizeof(sigact));
141 sigact.sa_sigaction = (sa_sigaction_t)SIG_DFL;
142 internal_sigaction(SIGABRT, &sigact, nullptr);
149 int Atexit(void (*function)(void)) {
151 return atexit(function);
157 bool SupportsColoredOutput(fd_t fd) {
158 return isatty(fd) != 0;
162 // TODO(glider): different tools may require different altstack size.
163 static const uptr kAltStackSize = SIGSTKSZ * 4; // SIGSTKSZ is not enough.
165 void SetAlternateSignalStack() {
166 stack_t altstack, oldstack;
167 CHECK_EQ(0, sigaltstack(nullptr, &oldstack));
168 // If the alternate stack is already in place, do nothing.
169 // Android always sets an alternate stack, but it's too small for us.
170 if (!SANITIZER_ANDROID && !(oldstack.ss_flags & SS_DISABLE)) return;
171 // TODO(glider): the mapped stack should have the MAP_STACK flag in the
172 // future. It is not required by man 2 sigaltstack now (they're using
174 void* base = MmapOrDie(kAltStackSize, __func__);
175 altstack.ss_sp = (char*) base;
176 altstack.ss_flags = 0;
177 altstack.ss_size = kAltStackSize;
178 CHECK_EQ(0, sigaltstack(&altstack, nullptr));
181 void UnsetAlternateSignalStack() {
182 stack_t altstack, oldstack;
183 altstack.ss_sp = nullptr;
184 altstack.ss_flags = SS_DISABLE;
185 altstack.ss_size = kAltStackSize; // Some sane value required on Darwin.
186 CHECK_EQ(0, sigaltstack(&altstack, &oldstack));
187 UnmapOrDie(oldstack.ss_sp, oldstack.ss_size);
190 static void MaybeInstallSigaction(int signum,
191 SignalHandlerType handler) {
192 if (GetHandleSignalMode(signum) == kHandleSignalNo) return;
194 struct sigaction sigact;
195 internal_memset(&sigact, 0, sizeof(sigact));
196 sigact.sa_sigaction = (sa_sigaction_t)handler;
197 // Do not block the signal from being received in that signal's handler.
198 // Clients are responsible for handling this correctly.
199 sigact.sa_flags = SA_SIGINFO | SA_NODEFER;
200 if (common_flags()->use_sigaltstack) sigact.sa_flags |= SA_ONSTACK;
201 CHECK_EQ(0, internal_sigaction(signum, &sigact, nullptr));
202 VReport(1, "Installed the sigaction for signal %d\n", signum);
205 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
206 // Set the alternate signal stack for the main thread.
207 // This will cause SetAlternateSignalStack to be called twice, but the stack
208 // will be actually set only once.
209 if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
210 MaybeInstallSigaction(SIGSEGV, handler);
211 MaybeInstallSigaction(SIGBUS, handler);
212 MaybeInstallSigaction(SIGABRT, handler);
213 MaybeInstallSigaction(SIGFPE, handler);
214 MaybeInstallSigaction(SIGILL, handler);
216 #endif // SANITIZER_GO
218 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
219 uptr page_size = GetPageSizeCached();
220 // Checking too large memory ranges is slow.
221 CHECK_LT(size, page_size * 10);
226 internal_write(sock_pair[1], reinterpret_cast<void *>(beg), size);
229 if (internal_iserror(bytes_written, &write_errno)) {
230 CHECK_EQ(EFAULT, write_errno);
233 result = (bytes_written == size);
235 internal_close(sock_pair[0]);
236 internal_close(sock_pair[1]);
240 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
241 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
242 // to read the file mappings from /proc/self/maps. Luckily, neither the
243 // process will be able to load additional libraries, so it's fine to use the
245 MemoryMappingLayout::CacheMemoryMappings();
246 // Same for /proc/self/exe in the symbolizer.
248 Symbolizer::GetOrInit()->PrepareForSandboxing();
252 #if SANITIZER_ANDROID || SANITIZER_GO
253 int GetNamedMappingFd(const char *name, uptr size) {
257 int GetNamedMappingFd(const char *name, uptr size) {
258 if (!common_flags()->decorate_proc_maps)
261 CHECK(internal_strlen(name) < sizeof(shmname) - 10);
262 internal_snprintf(shmname, sizeof(shmname), "%zu [%s]", internal_getpid(),
264 int fd = shm_open(shmname, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);
266 int res = internal_ftruncate(fd, size);
268 res = shm_unlink(shmname);
274 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
275 int fd = name ? GetNamedMappingFd(name, size) : -1;
276 unsigned flags = MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE;
277 if (fd == -1) flags |= MAP_ANON;
279 uptr PageSize = GetPageSizeCached();
280 uptr p = internal_mmap((void *)(fixed_addr & ~(PageSize - 1)),
281 RoundUpTo(size, PageSize), PROT_READ | PROT_WRITE,
284 if (internal_iserror(p, &reserrno))
285 Report("ERROR: %s failed to "
286 "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
287 SanitizerToolName, size, size, fixed_addr, reserrno);
288 IncreaseTotalMmap(size);
292 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
293 int fd = name ? GetNamedMappingFd(name, size) : -1;
294 unsigned flags = MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE;
295 if (fd == -1) flags |= MAP_ANON;
297 return (void *)internal_mmap((void *)fixed_addr, size, PROT_NONE, flags, fd,
301 void *MmapNoAccess(uptr size) {
302 unsigned flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;
303 return (void *)internal_mmap(nullptr, size, PROT_NONE, flags, -1, 0);
306 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
308 SANITIZER_WEAK_ATTRIBUTE int
309 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
312 int my_pthread_attr_getstack(void *attr, void **addr, uptr *size) {
313 #if !SANITIZER_GO && !SANITIZER_MAC
314 if (&real_pthread_attr_getstack)
315 return real_pthread_attr_getstack((pthread_attr_t *)attr, addr,
318 return pthread_attr_getstack((pthread_attr_t *)attr, addr, (size_t *)size);
322 void AdjustStackSize(void *attr_) {
323 pthread_attr_t *attr = (pthread_attr_t *)attr_;
326 my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
327 // GLibC will return (0 - stacksize) as the stack address in the case when
328 // stacksize is set, but stackaddr is not.
329 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
330 // We place a lot of tool data into TLS, account for that.
331 const uptr minstacksize = GetTlsSize() + 128*1024;
332 if (stacksize < minstacksize) {
334 if (stacksize != 0) {
335 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
337 pthread_attr_setstacksize(attr, minstacksize);
340 Printf("Sanitizer: pre-allocated stack size is insufficient: "
341 "%zu < %zu\n", stacksize, minstacksize);
342 Printf("Sanitizer: pthread_create is likely to fail.\n");
346 #endif // !SANITIZER_GO
348 pid_t StartSubprocess(const char *program, const char *const argv[],
349 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
350 auto file_closer = at_scope_exit([&] {
351 if (stdin_fd != kInvalidFd) {
352 internal_close(stdin_fd);
354 if (stdout_fd != kInvalidFd) {
355 internal_close(stdout_fd);
357 if (stderr_fd != kInvalidFd) {
358 internal_close(stderr_fd);
362 int pid = internal_fork();
366 if (internal_iserror(pid, &rverrno)) {
367 Report("WARNING: failed to fork (errno %d)\n", rverrno);
374 if (stdin_fd != kInvalidFd) {
375 internal_close(STDIN_FILENO);
376 internal_dup2(stdin_fd, STDIN_FILENO);
377 internal_close(stdin_fd);
379 if (stdout_fd != kInvalidFd) {
380 internal_close(STDOUT_FILENO);
381 internal_dup2(stdout_fd, STDOUT_FILENO);
382 internal_close(stdout_fd);
384 if (stderr_fd != kInvalidFd) {
385 internal_close(STDERR_FILENO);
386 internal_dup2(stderr_fd, STDERR_FILENO);
387 internal_close(stderr_fd);
390 for (int fd = sysconf(_SC_OPEN_MAX); fd > 2; fd--) internal_close(fd);
392 execv(program, const_cast<char **>(&argv[0]));
399 bool IsProcessRunning(pid_t pid) {
401 uptr waitpid_status = internal_waitpid(pid, &process_status, WNOHANG);
403 if (internal_iserror(waitpid_status, &local_errno)) {
404 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
407 return waitpid_status == 0;
410 int WaitForProcess(pid_t pid) {
412 uptr waitpid_status = internal_waitpid(pid, &process_status, 0);
414 if (internal_iserror(waitpid_status, &local_errno)) {
415 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
418 return process_status;
421 bool IsStateDetached(int state) {
422 return state == PTHREAD_CREATE_DETACHED;
425 } // namespace __sanitizer
427 #endif // SANITIZER_POSIX