1 //===-- sanitizer_linux.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 linux-specific functions from
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
14 #if SANITIZER_FREEBSD || SANITIZER_LINUX
16 #include "sanitizer_common.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_internal_defs.h"
19 #include "sanitizer_libc.h"
20 #include "sanitizer_linux.h"
21 #include "sanitizer_mutex.h"
22 #include "sanitizer_placement_new.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_stacktrace.h"
25 #include "sanitizer_symbolizer.h"
27 #if !SANITIZER_FREEBSD
28 #include <asm/param.h>
34 #if !SANITIZER_ANDROID
40 #include <sys/ptrace.h>
41 #include <sys/resource.h>
43 #include <sys/syscall.h>
45 #include <sys/types.h>
49 #include <sys/sysctl.h>
50 #include <machine/atomic.h>
52 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
53 // FreeBSD 9.2 and 10.0.
56 extern char **environ
; // provided by crt1
57 #endif // SANITIZER_FREEBSD
59 #if !SANITIZER_ANDROID
60 #include <sys/signal.h>
64 #include <android/log.h>
65 #include <sys/system_properties.h>
70 struct kernel_timeval
{
75 // <linux/futex.h> is broken on some linux distributions.
76 const int FUTEX_WAIT
= 0;
77 const int FUTEX_WAKE
= 1;
78 #endif // SANITIZER_LINUX
80 // Are we using 32-bit or 64-bit Linux syscalls?
81 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
82 // but it still needs to use 64-bit syscalls.
83 #if SANITIZER_LINUX && (defined(__x86_64__) || SANITIZER_WORDSIZE == 64)
84 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
86 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
89 namespace __sanitizer
{
91 #if SANITIZER_LINUX && defined(__x86_64__)
92 #include "sanitizer_syscall_linux_x86_64.inc"
94 #include "sanitizer_syscall_generic.inc"
97 // --------------- sanitizer_libc.h
98 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
,
100 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
101 return internal_syscall(SYSCALL(mmap
), (uptr
)addr
, length
, prot
, flags
, fd
,
104 return internal_syscall(SYSCALL(mmap2
), addr
, length
, prot
, flags
, fd
,
109 uptr
internal_munmap(void *addr
, uptr length
) {
110 return internal_syscall(SYSCALL(munmap
), (uptr
)addr
, length
);
113 uptr
internal_close(fd_t fd
) {
114 return internal_syscall(SYSCALL(close
), fd
);
117 uptr
internal_open(const char *filename
, int flags
) {
118 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
119 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
);
121 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
);
125 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
126 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
127 return internal_syscall(SYSCALL(openat
), AT_FDCWD
, (uptr
)filename
, flags
,
130 return internal_syscall(SYSCALL(open
), (uptr
)filename
, flags
, mode
);
134 uptr
OpenFile(const char *filename
, bool write
) {
135 return internal_open(filename
,
136 write
? O_RDWR
| O_CREAT
/*| O_CLOEXEC*/ : O_RDONLY
, 0660);
139 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
141 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(read
), fd
, (uptr
)buf
,
146 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
148 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(write
), fd
, (uptr
)buf
,
153 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
155 HANDLE_EINTR(res
, (sptr
)internal_syscall(SYSCALL(ftruncate
), fd
, size
));
159 #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && !SANITIZER_FREEBSD
160 static void stat64_to_stat(struct stat64
*in
, struct stat
*out
) {
161 internal_memset(out
, 0, sizeof(*out
));
162 out
->st_dev
= in
->st_dev
;
163 out
->st_ino
= in
->st_ino
;
164 out
->st_mode
= in
->st_mode
;
165 out
->st_nlink
= in
->st_nlink
;
166 out
->st_uid
= in
->st_uid
;
167 out
->st_gid
= in
->st_gid
;
168 out
->st_rdev
= in
->st_rdev
;
169 out
->st_size
= in
->st_size
;
170 out
->st_blksize
= in
->st_blksize
;
171 out
->st_blocks
= in
->st_blocks
;
172 out
->st_atime
= in
->st_atime
;
173 out
->st_mtime
= in
->st_mtime
;
174 out
->st_ctime
= in
->st_ctime
;
175 out
->st_ino
= in
->st_ino
;
179 uptr
internal_stat(const char *path
, void *buf
) {
180 #if SANITIZER_FREEBSD
181 return internal_syscall(SYSCALL(stat
), path
, buf
);
182 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
183 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
,
185 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
186 return internal_syscall(SYSCALL(stat
), (uptr
)path
, (uptr
)buf
);
189 int res
= internal_syscall(SYSCALL(stat64
), path
, &buf64
);
190 stat64_to_stat(&buf64
, (struct stat
*)buf
);
195 uptr
internal_lstat(const char *path
, void *buf
) {
196 #if SANITIZER_FREEBSD
197 return internal_syscall(SYSCALL(lstat
), path
, buf
);
198 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
199 return internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, (uptr
)path
,
200 (uptr
)buf
, AT_SYMLINK_NOFOLLOW
);
201 #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
202 return internal_syscall(SYSCALL(lstat
), (uptr
)path
, (uptr
)buf
);
205 int res
= internal_syscall(SYSCALL(lstat64
), path
, &buf64
);
206 stat64_to_stat(&buf64
, (struct stat
*)buf
);
211 uptr
internal_fstat(fd_t fd
, void *buf
) {
212 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
213 return internal_syscall(SYSCALL(fstat
), fd
, (uptr
)buf
);
216 int res
= internal_syscall(SYSCALL(fstat64
), fd
, &buf64
);
217 stat64_to_stat(&buf64
, (struct stat
*)buf
);
222 uptr
internal_filesize(fd_t fd
) {
224 if (internal_fstat(fd
, &st
))
226 return (uptr
)st
.st_size
;
229 uptr
internal_dup2(int oldfd
, int newfd
) {
230 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
231 return internal_syscall(SYSCALL(dup3
), oldfd
, newfd
, 0);
233 return internal_syscall(SYSCALL(dup2
), oldfd
, newfd
);
237 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
238 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
239 return internal_syscall(SYSCALL(readlinkat
), AT_FDCWD
,
240 (uptr
)path
, (uptr
)buf
, bufsize
);
242 return internal_syscall(SYSCALL(readlink
), (uptr
)path
, (uptr
)buf
, bufsize
);
246 uptr
internal_unlink(const char *path
) {
247 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
248 return internal_syscall(SYSCALL(unlinkat
), AT_FDCWD
, (uptr
)path
, 0);
250 return internal_syscall(SYSCALL(unlink
), (uptr
)path
);
254 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
255 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
256 return internal_syscall(SYSCALL(renameat
), AT_FDCWD
, (uptr
)oldpath
, AT_FDCWD
,
259 return internal_syscall(SYSCALL(rename
), (uptr
)oldpath
, (uptr
)newpath
);
263 uptr
internal_sched_yield() {
264 return internal_syscall(SYSCALL(sched_yield
));
267 void internal__exit(int exitcode
) {
268 #if SANITIZER_FREEBSD
269 internal_syscall(SYSCALL(exit
), exitcode
);
271 internal_syscall(SYSCALL(exit_group
), exitcode
);
273 Die(); // Unreachable.
276 uptr
internal_execve(const char *filename
, char *const argv
[],
277 char *const envp
[]) {
278 return internal_syscall(SYSCALL(execve
), (uptr
)filename
, (uptr
)argv
,
282 // ----------------- sanitizer_common.h
283 bool FileExists(const char *filename
) {
284 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
286 if (internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, filename
, &st
, 0))
290 if (internal_stat(filename
, &st
))
292 // Sanity check: filename is a regular file.
293 return S_ISREG(st
.st_mode
);
298 #if SANITIZER_FREEBSD
299 return (uptr
)pthread_self();
301 return internal_syscall(SYSCALL(gettid
));
306 #if SANITIZER_FREEBSD
311 internal_memset(&tv
, 0, sizeof(tv
));
312 internal_syscall(SYSCALL(gettimeofday
), (uptr
)&tv
, 0);
313 return (u64
)tv
.tv_sec
* 1000*1000*1000 + tv
.tv_usec
* 1000;
316 // Like getenv, but reads env directly from /proc (on Linux) or parses the
317 // 'environ' array (on FreeBSD) and does not use libc. This function should be
318 // called first inside __asan_init.
319 const char *GetEnv(const char *name
) {
320 #if SANITIZER_FREEBSD
321 if (::environ
!= 0) {
322 uptr NameLen
= internal_strlen(name
);
323 for (char **Env
= ::environ
; *Env
!= 0; Env
++) {
324 if (internal_strncmp(*Env
, name
, NameLen
) == 0 && (*Env
)[NameLen
] == '=')
325 return (*Env
) + NameLen
+ 1;
328 return 0; // Not found.
329 #elif SANITIZER_LINUX
330 static char *environ
;
336 len
= ReadFileToBuffer("/proc/self/environ",
337 &environ
, &environ_size
, 1 << 26);
339 if (!environ
|| len
== 0) return 0;
340 uptr namelen
= internal_strlen(name
);
341 const char *p
= environ
;
342 while (*p
!= '\0') { // will happen at the \0\0 that terminates the buffer
343 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
345 (char*)internal_memchr(p
, '\0', len
- (p
- environ
));
346 if (endp
== 0) // this entry isn't NUL terminated
348 else if (!internal_memcmp(p
, name
, namelen
) && p
[namelen
] == '=') // Match.
349 return p
+ namelen
+ 1; // point after =
352 return 0; // Not found.
354 #error "Unsupported platform"
359 SANITIZER_WEAK_ATTRIBUTE
extern void *__libc_stack_end
;
363 static void ReadNullSepFileToArray(const char *path
, char ***arr
,
367 *arr
= (char **)MmapOrDie(arr_size
* sizeof(char *), "NullSepFileArray");
368 ReadFileToBuffer(path
, &buff
, &buff_size
, 1024 * 1024);
371 for (count
= 1, i
= 1; ; i
++) {
373 if (buff
[i
+1] == 0) break;
374 (*arr
)[count
] = &buff
[i
+1];
375 CHECK_LE(count
, arr_size
- 1); // FIXME: make this more flexible.
383 static void GetArgsAndEnv(char*** argv
, char*** envp
) {
385 if (&__libc_stack_end
) {
387 uptr
* stack_end
= (uptr
*)__libc_stack_end
;
388 int argc
= *stack_end
;
389 *argv
= (char**)(stack_end
+ 1);
390 *envp
= (char**)(stack_end
+ argc
+ 2);
393 static const int kMaxArgv
= 2000, kMaxEnvp
= 2000;
394 ReadNullSepFileToArray("/proc/self/cmdline", argv
, kMaxArgv
);
395 ReadNullSepFileToArray("/proc/self/environ", envp
, kMaxEnvp
);
402 GetArgsAndEnv(&argv
, &envp
);
403 uptr rv
= internal_execve("/proc/self/exe", argv
, envp
);
405 CHECK_EQ(internal_iserror(rv
, &rverrno
), true);
406 Printf("execve failed, errno %d\n", rverrno
);
410 // Stub implementation of GetThreadStackAndTls for Go.
412 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
413 uptr
*tls_addr
, uptr
*tls_size
) {
419 #endif // SANITIZER_GO
427 BlockingMutex::BlockingMutex(LinkerInitialized
) {
431 BlockingMutex::BlockingMutex() {
432 internal_memset(this, 0, sizeof(*this));
435 void BlockingMutex::Lock() {
436 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
437 if (atomic_exchange(m
, MtxLocked
, memory_order_acquire
) == MtxUnlocked
)
439 while (atomic_exchange(m
, MtxSleeping
, memory_order_acquire
) != MtxUnlocked
) {
440 #if SANITIZER_FREEBSD
441 _umtx_op(m
, UMTX_OP_WAIT_UINT
, MtxSleeping
, 0, 0);
443 internal_syscall(SYSCALL(futex
), (uptr
)m
, FUTEX_WAIT
, MtxSleeping
, 0, 0, 0);
448 void BlockingMutex::Unlock() {
449 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
450 u32 v
= atomic_exchange(m
, MtxUnlocked
, memory_order_relaxed
);
451 CHECK_NE(v
, MtxUnlocked
);
452 if (v
== MtxSleeping
) {
453 #if SANITIZER_FREEBSD
454 _umtx_op(m
, UMTX_OP_WAKE
, 1, 0, 0);
456 internal_syscall(SYSCALL(futex
), (uptr
)m
, FUTEX_WAKE
, 1, 0, 0, 0);
461 void BlockingMutex::CheckLocked() {
462 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
463 CHECK_NE(MtxUnlocked
, atomic_load(m
, memory_order_relaxed
));
466 // ----------------- sanitizer_linux.h
467 // The actual size of this structure is specified by d_reclen.
468 // Note that getdents64 uses a different structure format. We only provide the
469 // 32-bit syscall here.
470 struct linux_dirent
{
478 unsigned short d_reclen
;
483 uptr
internal_ptrace(int request
, int pid
, void *addr
, void *data
) {
484 return internal_syscall(SYSCALL(ptrace
), request
, pid
, (uptr
)addr
,
488 uptr
internal_waitpid(int pid
, int *status
, int options
) {
489 return internal_syscall(SYSCALL(wait4
), pid
, (uptr
)status
, options
,
493 uptr
internal_getpid() {
494 return internal_syscall(SYSCALL(getpid
));
497 uptr
internal_getppid() {
498 return internal_syscall(SYSCALL(getppid
));
501 uptr
internal_getdents(fd_t fd
, struct linux_dirent
*dirp
, unsigned int count
) {
502 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
503 return internal_syscall(SYSCALL(getdents64
), fd
, (uptr
)dirp
, count
);
505 return internal_syscall(SYSCALL(getdents
), fd
, (uptr
)dirp
, count
);
509 uptr
internal_lseek(fd_t fd
, OFF_T offset
, int whence
) {
510 return internal_syscall(SYSCALL(lseek
), fd
, offset
, whence
);
514 uptr
internal_prctl(int option
, uptr arg2
, uptr arg3
, uptr arg4
, uptr arg5
) {
515 return internal_syscall(SYSCALL(prctl
), option
, arg2
, arg3
, arg4
, arg5
);
519 uptr
internal_sigaltstack(const struct sigaltstack
*ss
,
520 struct sigaltstack
*oss
) {
521 return internal_syscall(SYSCALL(sigaltstack
), (uptr
)ss
, (uptr
)oss
);
524 int internal_fork() {
525 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
526 return internal_syscall(SYSCALL(clone
), SIGCHLD
, 0);
528 return internal_syscall(SYSCALL(fork
));
533 // Doesn't set sa_restorer, use with caution (see below).
534 int internal_sigaction_norestorer(int signum
, const void *act
, void *oldact
) {
535 __sanitizer_kernel_sigaction_t k_act
, k_oldact
;
536 internal_memset(&k_act
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
537 internal_memset(&k_oldact
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
538 const __sanitizer_sigaction
*u_act
= (__sanitizer_sigaction
*)act
;
539 __sanitizer_sigaction
*u_oldact
= (__sanitizer_sigaction
*)oldact
;
541 k_act
.handler
= u_act
->handler
;
542 k_act
.sigaction
= u_act
->sigaction
;
543 internal_memcpy(&k_act
.sa_mask
, &u_act
->sa_mask
,
544 sizeof(__sanitizer_kernel_sigset_t
));
545 k_act
.sa_flags
= u_act
->sa_flags
;
546 // FIXME: most often sa_restorer is unset, however the kernel requires it
547 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
548 // If sa_restorer passed to the kernel is NULL, the program may crash upon
549 // signal delivery or fail to unwind the stack in the signal handler.
550 // libc implementation of sigaction() passes its own restorer to
551 // rt_sigaction, so we need to do the same (we'll need to reimplement the
552 // restorers; for x86_64 the restorer address can be obtained from
553 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
554 k_act
.sa_restorer
= u_act
->sa_restorer
;
557 uptr result
= internal_syscall(SYSCALL(rt_sigaction
), (uptr
)signum
,
558 (uptr
)(u_act
? &k_act
: NULL
),
559 (uptr
)(u_oldact
? &k_oldact
: NULL
),
560 (uptr
)sizeof(__sanitizer_kernel_sigset_t
));
562 if ((result
== 0) && u_oldact
) {
563 u_oldact
->handler
= k_oldact
.handler
;
564 u_oldact
->sigaction
= k_oldact
.sigaction
;
565 internal_memcpy(&u_oldact
->sa_mask
, &k_oldact
.sa_mask
,
566 sizeof(__sanitizer_kernel_sigset_t
));
567 u_oldact
->sa_flags
= k_oldact
.sa_flags
;
568 u_oldact
->sa_restorer
= k_oldact
.sa_restorer
;
572 #endif // SANITIZER_LINUX
574 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
575 __sanitizer_sigset_t
*oldset
) {
576 #if SANITIZER_FREEBSD
577 return internal_syscall(SYSCALL(sigprocmask
), how
, set
, oldset
);
579 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
580 __sanitizer_kernel_sigset_t
*k_oldset
= (__sanitizer_kernel_sigset_t
*)oldset
;
581 return internal_syscall(SYSCALL(rt_sigprocmask
), (uptr
)how
,
582 (uptr
)&k_set
->sig
[0], (uptr
)&k_oldset
->sig
[0],
583 sizeof(__sanitizer_kernel_sigset_t
));
587 void internal_sigfillset(__sanitizer_sigset_t
*set
) {
588 internal_memset(set
, 0xff, sizeof(*set
));
592 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
595 CHECK_LT(signum
, sizeof(*set
) * 8);
596 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
597 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
598 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
599 k_set
->sig
[idx
] &= ~(1 << bit
);
601 #endif // SANITIZER_LINUX
603 // ThreadLister implementation.
604 ThreadLister::ThreadLister(int pid
)
609 entry_((struct linux_dirent
*)buffer_
.data()),
611 char task_directory_path
[80];
612 internal_snprintf(task_directory_path
, sizeof(task_directory_path
),
613 "/proc/%d/task/", pid
);
614 uptr openrv
= internal_open(task_directory_path
, O_RDONLY
| O_DIRECTORY
);
615 if (internal_iserror(openrv
)) {
617 Report("Can't open /proc/%d/task for reading.\n", pid
);
620 descriptor_
= openrv
;
624 int ThreadLister::GetNextTID() {
629 if ((char *)entry_
>= &buffer_
[bytes_read_
] && !GetDirectoryEntries())
631 if (entry_
->d_ino
!= 0 && entry_
->d_name
[0] >= '0' &&
632 entry_
->d_name
[0] <= '9') {
633 // Found a valid tid.
634 tid
= (int)internal_atoll(entry_
->d_name
);
636 entry_
= (struct linux_dirent
*)(((char *)entry_
) + entry_
->d_reclen
);
641 void ThreadLister::Reset() {
642 if (error_
|| descriptor_
< 0)
644 internal_lseek(descriptor_
, 0, SEEK_SET
);
647 ThreadLister::~ThreadLister() {
648 if (descriptor_
>= 0)
649 internal_close(descriptor_
);
652 bool ThreadLister::error() { return error_
; }
654 bool ThreadLister::GetDirectoryEntries() {
655 CHECK_GE(descriptor_
, 0);
656 CHECK_NE(error_
, true);
657 bytes_read_
= internal_getdents(descriptor_
,
658 (struct linux_dirent
*)buffer_
.data(),
660 if (internal_iserror(bytes_read_
)) {
661 Report("Can't read directory entries from /proc/%d/task.\n", pid_
);
664 } else if (bytes_read_
== 0) {
667 entry_
= (struct linux_dirent
*)buffer_
.data();
672 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
673 return EXEC_PAGESIZE
;
675 return sysconf(_SC_PAGESIZE
); // EXEC_PAGESIZE may not be trustworthy.
679 static char proc_self_exe_cache_str
[kMaxPathLength
];
680 static uptr proc_self_exe_cache_len
= 0;
682 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
683 if (proc_self_exe_cache_len
> 0) {
684 // If available, use the cached module name.
685 uptr module_name_len
=
686 internal_snprintf(buf
, buf_len
, "%s", proc_self_exe_cache_str
);
687 CHECK_LT(module_name_len
, buf_len
);
688 return module_name_len
;
690 #if SANITIZER_FREEBSD
691 const int Mib
[4] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1 };
692 size_t Size
= buf_len
;
693 bool IsErr
= (sysctl(Mib
, 4, buf
, &Size
, NULL
, 0) != 0);
694 int readlink_error
= IsErr
? errno
: 0;
695 uptr module_name_len
= Size
;
697 uptr module_name_len
= internal_readlink(
698 "/proc/self/exe", buf
, buf_len
);
700 bool IsErr
= internal_iserror(module_name_len
, &readlink_error
);
703 // We can't read /proc/self/exe for some reason, assume the name of the
704 // binary is unknown.
705 Report("WARNING: readlink(\"/proc/self/exe\") failed with errno %d, "
706 "some stack frames may not be symbolized\n", readlink_error
);
707 module_name_len
= internal_snprintf(buf
, buf_len
, "/proc/self/exe");
708 CHECK_LT(module_name_len
, buf_len
);
710 return module_name_len
;
713 void CacheBinaryName() {
714 if (!proc_self_exe_cache_len
) {
715 proc_self_exe_cache_len
=
716 ReadBinaryName(proc_self_exe_cache_str
, kMaxPathLength
);
720 // Match full names of the form /path/to/base_name{-,.}*
721 bool LibraryNameIs(const char *full_name
, const char *base_name
) {
722 const char *name
= full_name
;
724 while (*name
!= '\0') name
++;
725 while (name
> full_name
&& *name
!= '/') name
--;
726 if (*name
== '/') name
++;
727 uptr base_name_length
= internal_strlen(base_name
);
728 if (internal_strncmp(name
, base_name
, base_name_length
)) return false;
729 return (name
[base_name_length
] == '-' || name
[base_name_length
] == '.');
732 #if !SANITIZER_ANDROID
733 // Call cb for each region mapped by map.
734 void ForEachMappedRegion(link_map
*map
, void (*cb
)(const void *, uptr
)) {
735 #if !SANITIZER_FREEBSD
736 typedef ElfW(Phdr
) Elf_Phdr
;
737 typedef ElfW(Ehdr
) Elf_Ehdr
;
738 #endif // !SANITIZER_FREEBSD
739 char *base
= (char *)map
->l_addr
;
740 Elf_Ehdr
*ehdr
= (Elf_Ehdr
*)base
;
741 char *phdrs
= base
+ ehdr
->e_phoff
;
742 char *phdrs_end
= phdrs
+ ehdr
->e_phnum
* ehdr
->e_phentsize
;
744 // Find the segment with the minimum base so we can "relocate" the p_vaddr
745 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
746 // objects have a non-zero base.
747 uptr preferred_base
= (uptr
)-1;
748 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
749 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
750 if (phdr
->p_type
== PT_LOAD
&& preferred_base
> (uptr
)phdr
->p_vaddr
)
751 preferred_base
= (uptr
)phdr
->p_vaddr
;
754 // Compute the delta from the real base to get a relocation delta.
755 sptr delta
= (uptr
)base
- preferred_base
;
756 // Now we can figure out what the loader really mapped.
757 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
758 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
759 if (phdr
->p_type
== PT_LOAD
) {
760 uptr seg_start
= phdr
->p_vaddr
+ delta
;
761 uptr seg_end
= seg_start
+ phdr
->p_memsz
;
762 // None of these values are aligned. We consider the ragged edges of the
763 // load command as defined, since they are mapped from the file.
764 seg_start
= RoundDownTo(seg_start
, GetPageSizeCached());
765 seg_end
= RoundUpTo(seg_end
, GetPageSizeCached());
766 cb((void *)seg_start
, seg_end
- seg_start
);
772 #if defined(__x86_64__) && SANITIZER_LINUX
773 // We cannot use glibc's clone wrapper, because it messes with the child
774 // task's TLS. It writes the PID and TID of the child task to its thread
775 // descriptor, but in our case the child task shares the thread descriptor with
776 // the parent (because we don't know how to allocate a new thread
777 // descriptor to keep glibc happy). So the stock version of clone(), when
778 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
779 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
780 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
782 if (!fn
|| !child_stack
)
784 CHECK_EQ(0, (uptr
)child_stack
% 16);
785 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
786 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
787 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
788 register void *r8
__asm__("r8") = newtls
;
789 register int *r10
__asm__("r10") = child_tidptr
;
790 __asm__
__volatile__(
791 /* %rax = syscall(%rax = SYSCALL(clone),
793 * %rsi = child_stack,
794 * %rdx = parent_tidptr,
796 * %r10 = child_tidptr)
803 "testq %%rax,%%rax\n"
806 /* In the child. Terminate unwind chain. */
807 // XXX: We should also terminate the CFI unwind chain
808 // here. Unfortunately clang 3.2 doesn't support the
809 // necessary CFI directives, so we skip that part.
812 /* Call "fn(arg)". */
817 /* Call _exit(%rax). */
822 /* Return to parent. */
825 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
831 : "rsp", "memory", "r11", "rcx");
834 #endif // defined(__x86_64__) && SANITIZER_LINUX
836 #if SANITIZER_ANDROID
837 static atomic_uint8_t android_log_initialized
;
839 void AndroidLogInit() {
840 atomic_store(&android_log_initialized
, 1, memory_order_release
);
842 // This thing is not, strictly speaking, async signal safe, but it does not seem
843 // to cause any issues. Alternative is writing to log devices directly, but
844 // their location and message format might change in the future, so we'd really
845 // like to avoid that.
846 void AndroidLogWrite(const char *buffer
) {
847 if (!atomic_load(&android_log_initialized
, memory_order_acquire
))
850 char *copy
= internal_strdup(buffer
);
853 // __android_log_write has an implicit message length limit.
854 // Print one line at a time.
856 q
= internal_strchr(p
, '\n');
858 __android_log_write(ANDROID_LOG_INFO
, NULL
, p
);
864 void GetExtraActivationFlags(char *buf
, uptr size
) {
865 CHECK(size
> PROP_VALUE_MAX
);
866 __system_property_get("asan.options", buf
);
870 bool IsDeadlySignal(int signum
) {
871 return (signum
== SIGSEGV
) && common_flags()->handle_segv
;
874 } // namespace __sanitizer
876 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX