1 //===-- sanitizer_posix_libcdep.cc ----------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements libc-dependent POSIX-specific functions
10 // from sanitizer_libc.h.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
17 #include "sanitizer_common.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_platform_limits_netbsd.h"
20 #include "sanitizer_platform_limits_posix.h"
21 #include "sanitizer_posix.h"
22 #include "sanitizer_procmaps.h"
23 #include "sanitizer_stacktrace.h"
24 #include "sanitizer_symbolizer.h"
32 #include <sys/resource.h>
35 #include <sys/types.h>
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.
43 #define MAP_NORESERVE 0
46 typedef void (*sa_sigaction_t
)(int, siginfo_t
*, void *);
48 namespace __sanitizer
{
54 uptr
GetThreadSelf() {
55 return (uptr
)pthread_self();
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 madvise((void*)beg_aligned
, end_aligned
- beg_aligned
, MADV_DONTNEED
);
66 void NoHugePagesInRegion(uptr addr
, uptr size
) {
67 #ifdef MADV_NOHUGEPAGE // May not be defined on old systems.
68 madvise((void *)addr
, size
, MADV_NOHUGEPAGE
);
69 #endif // MADV_NOHUGEPAGE
72 void DontDumpShadowMemory(uptr addr
, uptr length
) {
74 madvise((void *)addr
, length
, MADV_DONTDUMP
);
78 static rlim_t
getlim(int res
) {
80 CHECK_EQ(0, getrlimit(res
, &rlim
));
84 static void setlim(int res
, rlim_t lim
) {
85 // The following magic is to prevent clang from replacing it with memset.
86 volatile struct rlimit rlim
;
89 if (setrlimit(res
, const_cast<struct rlimit
*>(&rlim
))) {
90 Report("ERROR: %s setrlimit() failed %d\n", SanitizerToolName
, errno
);
95 void DisableCoreDumperIfNecessary() {
96 if (common_flags()->disable_coredump
) {
97 setlim(RLIMIT_CORE
, 0);
101 bool StackSizeIsUnlimited() {
102 rlim_t stack_size
= getlim(RLIMIT_STACK
);
103 return (stack_size
== RLIM_INFINITY
);
106 uptr
GetStackSizeLimitInBytes() {
107 return (uptr
)getlim(RLIMIT_STACK
);
110 void SetStackSizeLimitInBytes(uptr limit
) {
111 setlim(RLIMIT_STACK
, (rlim_t
)limit
);
112 CHECK(!StackSizeIsUnlimited());
115 bool AddressSpaceIsUnlimited() {
116 rlim_t as_size
= getlim(RLIMIT_AS
);
117 return (as_size
== RLIM_INFINITY
);
120 void SetAddressSpaceUnlimited() {
121 setlim(RLIMIT_AS
, RLIM_INFINITY
);
122 CHECK(AddressSpaceIsUnlimited());
125 void SleepForSeconds(int seconds
) {
129 void SleepForMillis(int millis
) {
130 usleep(millis
* 1000);
135 // If we are handling SIGABRT, unhandle it first.
136 // TODO(vitalybuka): Check if handler belongs to sanitizer.
137 if (GetHandleSignalMode(SIGABRT
) != kHandleSignalNo
) {
138 struct sigaction sigact
;
139 internal_memset(&sigact
, 0, sizeof(sigact
));
140 sigact
.sa_sigaction
= (sa_sigaction_t
)SIG_DFL
;
141 internal_sigaction(SIGABRT
, &sigact
, nullptr);
148 int Atexit(void (*function
)(void)) {
150 return atexit(function
);
156 bool SupportsColoredOutput(fd_t fd
) {
157 return isatty(fd
) != 0;
161 // TODO(glider): different tools may require different altstack size.
162 static const uptr kAltStackSize
= SIGSTKSZ
* 4; // SIGSTKSZ is not enough.
164 void SetAlternateSignalStack() {
165 stack_t altstack
, oldstack
;
166 CHECK_EQ(0, sigaltstack(nullptr, &oldstack
));
167 // If the alternate stack is already in place, do nothing.
168 // Android always sets an alternate stack, but it's too small for us.
169 if (!SANITIZER_ANDROID
&& !(oldstack
.ss_flags
& SS_DISABLE
)) return;
170 // TODO(glider): the mapped stack should have the MAP_STACK flag in the
171 // future. It is not required by man 2 sigaltstack now (they're using
173 void* base
= MmapOrDie(kAltStackSize
, __func__
);
174 altstack
.ss_sp
= (char*) base
;
175 altstack
.ss_flags
= 0;
176 altstack
.ss_size
= kAltStackSize
;
177 CHECK_EQ(0, sigaltstack(&altstack
, nullptr));
180 void UnsetAlternateSignalStack() {
181 stack_t altstack
, oldstack
;
182 altstack
.ss_sp
= nullptr;
183 altstack
.ss_flags
= SS_DISABLE
;
184 altstack
.ss_size
= kAltStackSize
; // Some sane value required on Darwin.
185 CHECK_EQ(0, sigaltstack(&altstack
, &oldstack
));
186 UnmapOrDie(oldstack
.ss_sp
, oldstack
.ss_size
);
189 static void MaybeInstallSigaction(int signum
,
190 SignalHandlerType handler
) {
191 if (GetHandleSignalMode(signum
) == kHandleSignalNo
) return;
193 struct sigaction sigact
;
194 internal_memset(&sigact
, 0, sizeof(sigact
));
195 sigact
.sa_sigaction
= (sa_sigaction_t
)handler
;
196 // Do not block the signal from being received in that signal's handler.
197 // Clients are responsible for handling this correctly.
198 sigact
.sa_flags
= SA_SIGINFO
| SA_NODEFER
;
199 if (common_flags()->use_sigaltstack
) sigact
.sa_flags
|= SA_ONSTACK
;
200 CHECK_EQ(0, internal_sigaction(signum
, &sigact
, nullptr));
201 VReport(1, "Installed the sigaction for signal %d\n", signum
);
204 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
205 // Set the alternate signal stack for the main thread.
206 // This will cause SetAlternateSignalStack to be called twice, but the stack
207 // will be actually set only once.
208 if (common_flags()->use_sigaltstack
) SetAlternateSignalStack();
209 MaybeInstallSigaction(SIGSEGV
, handler
);
210 MaybeInstallSigaction(SIGBUS
, handler
);
211 MaybeInstallSigaction(SIGABRT
, handler
);
212 MaybeInstallSigaction(SIGFPE
, handler
);
213 MaybeInstallSigaction(SIGILL
, handler
);
216 bool SignalContext::IsStackOverflow() const {
217 // Access at a reasonable offset above SP, or slightly below it (to account
218 // for x86_64 or PowerPC redzone, ARM push of multiple registers, etc) is
219 // probably a stack overflow.
221 // On s390, the fault address in siginfo points to start of the page, not
222 // to the precise word that was accessed. Mask off the low bits of sp to
223 // take it into account.
224 bool IsStackAccess
= addr
>= (sp
& ~0xFFF) && addr
< sp
+ 0xFFFF;
226 bool IsStackAccess
= addr
+ 512 > sp
&& addr
< sp
+ 0xFFFF;
230 // Large stack frames can be allocated with e.g.
232 // stdux r1,r1,r0 # store sp to [sp-10000] and update sp by -10000
233 // If the store faults then sp will not have been updated, so test above
234 // will not work, because the fault address will be more than just "slightly"
236 if (!IsStackAccess
&& IsAccessibleMemoryRange(pc
, 4)) {
237 u32 inst
= *(unsigned *)pc
;
238 u32 ra
= (inst
>> 16) & 0x1F;
239 u32 opcd
= inst
>> 26;
240 u32 xo
= (inst
>> 1) & 0x3FF;
241 // Check for store-with-update to sp. The instructions we accept are:
242 // stbu rs,d(ra) stbux rs,ra,rb
243 // sthu rs,d(ra) sthux rs,ra,rb
244 // stwu rs,d(ra) stwux rs,ra,rb
245 // stdu rs,ds(ra) stdux rs,ra,rb
246 // where ra is r1 (the stack pointer).
248 (opcd
== 39 || opcd
== 45 || opcd
== 37 || opcd
== 62 ||
249 (opcd
== 31 && (xo
== 247 || xo
== 439 || xo
== 183 || xo
== 181))))
250 IsStackAccess
= true;
252 #endif // __powerpc__
254 // We also check si_code to filter out SEGV caused by something else other
255 // then hitting the guard page or unmapped memory, like, for example,
256 // unaligned memory access.
257 auto si
= static_cast<const siginfo_t
*>(siginfo
);
258 return IsStackAccess
&&
259 (si
->si_code
== si_SEGV_MAPERR
|| si
->si_code
== si_SEGV_ACCERR
);
262 #endif // SANITIZER_GO
264 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
265 uptr page_size
= GetPageSizeCached();
266 // Checking too large memory ranges is slow.
267 CHECK_LT(size
, page_size
* 10);
272 internal_write(sock_pair
[1], reinterpret_cast<void *>(beg
), size
);
275 if (internal_iserror(bytes_written
, &write_errno
)) {
276 CHECK_EQ(EFAULT
, write_errno
);
279 result
= (bytes_written
== size
);
281 internal_close(sock_pair
[0]);
282 internal_close(sock_pair
[1]);
286 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {
287 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
288 // to read the file mappings from /proc/self/maps. Luckily, neither the
289 // process will be able to load additional libraries, so it's fine to use the
291 MemoryMappingLayout::CacheMemoryMappings();
292 // Same for /proc/self/exe in the symbolizer.
294 Symbolizer::GetOrInit()->PrepareForSandboxing();
298 #if SANITIZER_ANDROID || SANITIZER_GO
299 int GetNamedMappingFd(const char *name
, uptr size
) {
303 int GetNamedMappingFd(const char *name
, uptr size
) {
304 if (!common_flags()->decorate_proc_maps
)
307 CHECK(internal_strlen(name
) < sizeof(shmname
) - 10);
308 internal_snprintf(shmname
, sizeof(shmname
), "%zu [%s]", internal_getpid(),
310 int fd
= shm_open(shmname
, O_RDWR
| O_CREAT
| O_TRUNC
, S_IRWXU
);
312 int res
= internal_ftruncate(fd
, size
);
314 res
= shm_unlink(shmname
);
320 void *MmapFixedNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
321 int fd
= name
? GetNamedMappingFd(name
, size
) : -1;
322 unsigned flags
= MAP_PRIVATE
| MAP_FIXED
| MAP_NORESERVE
;
323 if (fd
== -1) flags
|= MAP_ANON
;
325 uptr PageSize
= GetPageSizeCached();
326 uptr p
= internal_mmap((void *)(fixed_addr
& ~(PageSize
- 1)),
327 RoundUpTo(size
, PageSize
), PROT_READ
| PROT_WRITE
,
330 if (internal_iserror(p
, &reserrno
))
331 Report("ERROR: %s failed to "
332 "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
333 SanitizerToolName
, size
, size
, fixed_addr
, reserrno
);
334 IncreaseTotalMmap(size
);
338 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
) {
339 int fd
= name
? GetNamedMappingFd(name
, size
) : -1;
340 unsigned flags
= MAP_PRIVATE
| MAP_FIXED
| MAP_NORESERVE
;
341 if (fd
== -1) flags
|= MAP_ANON
;
343 return (void *)internal_mmap((void *)fixed_addr
, size
, PROT_NONE
, flags
, fd
,
347 void *MmapNoAccess(uptr size
) {
348 unsigned flags
= MAP_PRIVATE
| MAP_ANON
| MAP_NORESERVE
;
349 return (void *)internal_mmap(nullptr, size
, PROT_NONE
, flags
, -1, 0);
352 // This function is defined elsewhere if we intercepted pthread_attr_getstack.
354 SANITIZER_WEAK_ATTRIBUTE
int
355 real_pthread_attr_getstack(void *attr
, void **addr
, size_t *size
);
358 int my_pthread_attr_getstack(void *attr
, void **addr
, uptr
*size
) {
359 #if !SANITIZER_GO && !SANITIZER_MAC
360 if (&real_pthread_attr_getstack
)
361 return real_pthread_attr_getstack((pthread_attr_t
*)attr
, addr
,
364 return pthread_attr_getstack((pthread_attr_t
*)attr
, addr
, (size_t *)size
);
368 void AdjustStackSize(void *attr_
) {
369 pthread_attr_t
*attr
= (pthread_attr_t
*)attr_
;
372 my_pthread_attr_getstack(attr
, (void**)&stackaddr
, &stacksize
);
373 // GLibC will return (0 - stacksize) as the stack address in the case when
374 // stacksize is set, but stackaddr is not.
375 bool stack_set
= (stackaddr
!= 0) && (stackaddr
+ stacksize
!= 0);
376 // We place a lot of tool data into TLS, account for that.
377 const uptr minstacksize
= GetTlsSize() + 128*1024;
378 if (stacksize
< minstacksize
) {
380 if (stacksize
!= 0) {
381 VPrintf(1, "Sanitizer: increasing stacksize %zu->%zu\n", stacksize
,
383 pthread_attr_setstacksize(attr
, minstacksize
);
386 Printf("Sanitizer: pre-allocated stack size is insufficient: "
387 "%zu < %zu\n", stacksize
, minstacksize
);
388 Printf("Sanitizer: pthread_create is likely to fail.\n");
392 #endif // !SANITIZER_GO
394 pid_t
StartSubprocess(const char *program
, const char *const argv
[],
395 fd_t stdin_fd
, fd_t stdout_fd
, fd_t stderr_fd
) {
396 auto file_closer
= at_scope_exit([&] {
397 if (stdin_fd
!= kInvalidFd
) {
398 internal_close(stdin_fd
);
400 if (stdout_fd
!= kInvalidFd
) {
401 internal_close(stdout_fd
);
403 if (stderr_fd
!= kInvalidFd
) {
404 internal_close(stderr_fd
);
408 int pid
= internal_fork();
412 if (internal_iserror(pid
, &rverrno
)) {
413 Report("WARNING: failed to fork (errno %d)\n", rverrno
);
420 if (stdin_fd
!= kInvalidFd
) {
421 internal_close(STDIN_FILENO
);
422 internal_dup2(stdin_fd
, STDIN_FILENO
);
423 internal_close(stdin_fd
);
425 if (stdout_fd
!= kInvalidFd
) {
426 internal_close(STDOUT_FILENO
);
427 internal_dup2(stdout_fd
, STDOUT_FILENO
);
428 internal_close(stdout_fd
);
430 if (stderr_fd
!= kInvalidFd
) {
431 internal_close(STDERR_FILENO
);
432 internal_dup2(stderr_fd
, STDERR_FILENO
);
433 internal_close(stderr_fd
);
436 for (int fd
= sysconf(_SC_OPEN_MAX
); fd
> 2; fd
--) internal_close(fd
);
438 execv(program
, const_cast<char **>(&argv
[0]));
445 bool IsProcessRunning(pid_t pid
) {
447 uptr waitpid_status
= internal_waitpid(pid
, &process_status
, WNOHANG
);
449 if (internal_iserror(waitpid_status
, &local_errno
)) {
450 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno
);
453 return waitpid_status
== 0;
456 int WaitForProcess(pid_t pid
) {
458 uptr waitpid_status
= internal_waitpid(pid
, &process_status
, 0);
460 if (internal_iserror(waitpid_status
, &local_errno
)) {
461 VReport(1, "Waiting on the process failed (errno %d).\n", local_errno
);
464 return process_status
;
467 bool IsStateDetached(int state
) {
468 return state
== PTHREAD_CREATE_DETACHED
;
471 } // namespace __sanitizer
473 #endif // SANITIZER_POSIX