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 namespace __sanitizer {
53 uptr GetThreadSelf() {
54 return (uptr)pthread_self();
57 void FlushUnneededShadowMemory(uptr addr, uptr size) {
58 madvise((void*)addr, size, MADV_DONTNEED);
61 void NoHugePagesInRegion(uptr addr, uptr size) {
62 #ifdef MADV_NOHUGEPAGE // May not be defined on old systems.
63 madvise((void *)addr, size, MADV_NOHUGEPAGE);
64 #endif // MADV_NOHUGEPAGE
67 void DontDumpShadowMemory(uptr addr, uptr length) {
69 madvise((void *)addr, length, MADV_DONTDUMP);
73 static rlim_t getlim(int res) {
75 CHECK_EQ(0, getrlimit(res, &rlim));
79 static void setlim(int res, rlim_t lim) {
80 // The following magic is to prevent clang from replacing it with memset.
81 volatile struct rlimit rlim;
84 if (setrlimit(res, const_cast<struct rlimit *>(&rlim))) {
85 Report("ERROR: %s setrlimit() failed %d\n", SanitizerToolName, errno);
90 void DisableCoreDumperIfNecessary() {
91 if (common_flags()->disable_coredump) {
92 setlim(RLIMIT_CORE, 0);
96 bool StackSizeIsUnlimited() {
97 rlim_t stack_size = getlim(RLIMIT_STACK);
98 return (stack_size == RLIM_INFINITY);
101 uptr GetStackSizeLimitInBytes() {
102 return (uptr)getlim(RLIMIT_STACK);
105 void SetStackSizeLimitInBytes(uptr limit) {
106 setlim(RLIMIT_STACK, (rlim_t)limit);
107 CHECK(!StackSizeIsUnlimited());
110 bool AddressSpaceIsUnlimited() {
111 rlim_t as_size = getlim(RLIMIT_AS);
112 return (as_size == RLIM_INFINITY);
115 void SetAddressSpaceUnlimited() {
116 setlim(RLIMIT_AS, RLIM_INFINITY);
117 CHECK(AddressSpaceIsUnlimited());
120 void SleepForSeconds(int seconds) {
124 void SleepForMillis(int millis) {
125 usleep(millis * 1000);
132 int Atexit(void (*function)(void)) {
134 return atexit(function);
140 bool SupportsColoredOutput(fd_t fd) {
141 return isatty(fd) != 0;
145 // TODO(glider): different tools may require different altstack size.
146 static const uptr kAltStackSize = SIGSTKSZ * 4; // SIGSTKSZ is not enough.
148 void SetAlternateSignalStack() {
149 stack_t altstack, oldstack;
150 CHECK_EQ(0, sigaltstack(nullptr, &oldstack));
151 // If the alternate stack is already in place, do nothing.
152 // Android always sets an alternate stack, but it's too small for us.
153 if (!SANITIZER_ANDROID && !(oldstack.ss_flags & SS_DISABLE)) return;
154 // TODO(glider): the mapped stack should have the MAP_STACK flag in the
155 // future. It is not required by man 2 sigaltstack now (they're using
157 void* base = MmapOrDie(kAltStackSize, __func__);
158 altstack.ss_sp = (char*) base;
159 altstack.ss_flags = 0;
160 altstack.ss_size = kAltStackSize;
161 CHECK_EQ(0, sigaltstack(&altstack, nullptr));
164 void UnsetAlternateSignalStack() {
165 stack_t altstack, oldstack;
166 altstack.ss_sp = nullptr;
167 altstack.ss_flags = SS_DISABLE;
168 altstack.ss_size = kAltStackSize; // Some sane value required on Darwin.
169 CHECK_EQ(0, sigaltstack(&altstack, &oldstack));
170 UnmapOrDie(oldstack.ss_sp, oldstack.ss_size);
173 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
174 static void MaybeInstallSigaction(int signum,
175 SignalHandlerType handler) {
176 if (!IsHandledDeadlySignal(signum))
178 struct sigaction sigact;
179 internal_memset(&sigact, 0, sizeof(sigact));
180 sigact.sa_sigaction = (sa_sigaction_t)handler;
181 // Do not block the signal from being received in that signal's handler.
182 // Clients are responsible for handling this correctly.
183 sigact.sa_flags = SA_SIGINFO | SA_NODEFER;
184 if (common_flags()->use_sigaltstack) sigact.sa_flags |= SA_ONSTACK;
185 CHECK_EQ(0, internal_sigaction(signum, &sigact, nullptr));
186 VReport(1, "Installed the sigaction for signal %d\n", signum);
189 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
190 // Set the alternate signal stack for the main thread.
191 // This will cause SetAlternateSignalStack to be called twice, but the stack
192 // will be actually set only once.
193 if (common_flags()->use_sigaltstack) SetAlternateSignalStack();
194 MaybeInstallSigaction(SIGSEGV, handler);
195 MaybeInstallSigaction(SIGBUS, handler);
196 MaybeInstallSigaction(SIGABRT, handler);
197 MaybeInstallSigaction(SIGFPE, handler);
198 MaybeInstallSigaction(SIGILL, handler);
200 #endif // SANITIZER_GO
202 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
203 uptr page_size = GetPageSizeCached();
204 // Checking too large memory ranges is slow.
205 CHECK_LT(size, page_size * 10);
210 internal_write(sock_pair[1], reinterpret_cast<void *>(beg), size);
213 if (internal_iserror(bytes_written, &write_errno)) {
214 CHECK_EQ(EFAULT, write_errno);
217 result = (bytes_written == size);
219 internal_close(sock_pair[0]);
220 internal_close(sock_pair[1]);
224 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
225 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
226 // to read the file mappings from /proc/self/maps. Luckily, neither the
227 // process will be able to load additional libraries, so it's fine to use the
229 MemoryMappingLayout::CacheMemoryMappings();
230 // Same for /proc/self/exe in the symbolizer.
232 Symbolizer::GetOrInit()->PrepareForSandboxing();
233 CovPrepareForSandboxing(args);
237 #if SANITIZER_ANDROID || SANITIZER_GO
238 int GetNamedMappingFd(const char *name, uptr size) {
242 int GetNamedMappingFd(const char *name, uptr size) {
243 if (!common_flags()->decorate_proc_maps)
246 CHECK(internal_strlen(name) < sizeof(shmname) - 10);
247 internal_snprintf(shmname, sizeof(shmname), "%zu [%s]", internal_getpid(),
249 int fd = shm_open(shmname, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);
251 int res = internal_ftruncate(fd, size);
253 res = shm_unlink(shmname);
259 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
260 int fd = name ? GetNamedMappingFd(name, size) : -1;
261 unsigned flags = MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE;
262 if (fd == -1) flags |= MAP_ANON;
264 uptr PageSize = GetPageSizeCached();
265 uptr p = internal_mmap((void *)(fixed_addr & ~(PageSize - 1)),
266 RoundUpTo(size, PageSize), PROT_READ | PROT_WRITE,
269 if (internal_iserror(p, &reserrno))
270 Report("ERROR: %s failed to "
271 "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
272 SanitizerToolName, size, size, fixed_addr, reserrno);
273 IncreaseTotalMmap(size);
277 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
278 int fd = name ? GetNamedMappingFd(name, size) : -1;
279 unsigned flags = MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE;
280 if (fd == -1) flags |= MAP_ANON;
282 return (void *)internal_mmap((void *)fixed_addr, size, PROT_NONE, flags, fd,
286 void *MmapNoAccess(uptr size) {
287 unsigned flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;
288 return (void *)internal_mmap(nullptr, size, PROT_NONE, flags, -1, 0);
291 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
293 SANITIZER_WEAK_ATTRIBUTE int
294 real_pthread_attr_getstack(void *attr, void **addr, size_t *size);
297 int my_pthread_attr_getstack(void *attr, void **addr, uptr *size) {
298 #if !SANITIZER_GO && !SANITIZER_MAC
299 if (&real_pthread_attr_getstack)
300 return real_pthread_attr_getstack((pthread_attr_t *)attr, addr,
303 return pthread_attr_getstack((pthread_attr_t *)attr, addr, (size_t *)size);
307 void AdjustStackSize(void *attr_) {
308 pthread_attr_t *attr = (pthread_attr_t *)attr_;
311 my_pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
312 // GLibC will return (0 - stacksize) as the stack address in the case when
313 // stacksize is set, but stackaddr is not.
314 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
315 // We place a lot of tool data into TLS, account for that.
316 const uptr minstacksize = GetTlsSize() + 128*1024;
317 if (stacksize < minstacksize) {
319 if (stacksize != 0) {
320 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
322 pthread_attr_setstacksize(attr, minstacksize);
325 Printf("Sanitizer: pre-allocated stack size is insufficient: "
326 "%zu < %zu\n", stacksize, minstacksize);
327 Printf("Sanitizer: pthread_create is likely to fail.\n");
331 #endif // !SANITIZER_GO
333 pid_t StartSubprocess(const char *program, const char *const argv[],
334 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
335 auto file_closer = at_scope_exit([&] {
336 if (stdin_fd != kInvalidFd) {
337 internal_close(stdin_fd);
339 if (stdout_fd != kInvalidFd) {
340 internal_close(stdout_fd);
342 if (stderr_fd != kInvalidFd) {
343 internal_close(stderr_fd);
347 int pid = internal_fork();
351 if (internal_iserror(pid, &rverrno)) {
352 Report("WARNING: failed to fork (errno %d)\n", rverrno);
359 if (stdin_fd != kInvalidFd) {
360 internal_close(STDIN_FILENO);
361 internal_dup2(stdin_fd, STDIN_FILENO);
362 internal_close(stdin_fd);
364 if (stdout_fd != kInvalidFd) {
365 internal_close(STDOUT_FILENO);
366 internal_dup2(stdout_fd, STDOUT_FILENO);
367 internal_close(stdout_fd);
369 if (stderr_fd != kInvalidFd) {
370 internal_close(STDERR_FILENO);
371 internal_dup2(stderr_fd, STDERR_FILENO);
372 internal_close(stderr_fd);
375 for (int fd = sysconf(_SC_OPEN_MAX); fd > 2; fd--) internal_close(fd);
377 execv(program, const_cast<char **>(&argv[0]));
384 bool IsProcessRunning(pid_t pid) {
386 uptr waitpid_status = internal_waitpid(pid, &process_status, WNOHANG);
388 if (internal_iserror(waitpid_status, &local_errno)) {
389 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
392 return waitpid_status == 0;
395 int WaitForProcess(pid_t pid) {
397 uptr waitpid_status = internal_waitpid(pid, &process_status, 0);
399 if (internal_iserror(waitpid_status, &local_errno)) {
400 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno);
403 return process_status;
406 } // namespace __sanitizer
408 #endif // SANITIZER_POSIX