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
) {
285 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
286 if (internal_syscall(SYSCALL(newfstatat
), AT_FDCWD
, filename
, &st
, 0))
288 if (internal_stat(filename
, &st
))
291 // Sanity check: filename is a regular file.
292 return S_ISREG(st
.st_mode
);
296 #if SANITIZER_FREEBSD
297 return (uptr
)pthread_self();
299 return internal_syscall(SYSCALL(gettid
));
304 #if SANITIZER_FREEBSD
309 internal_memset(&tv
, 0, sizeof(tv
));
310 internal_syscall(SYSCALL(gettimeofday
), (uptr
)&tv
, 0);
311 return (u64
)tv
.tv_sec
* 1000*1000*1000 + tv
.tv_usec
* 1000;
314 // Like getenv, but reads env directly from /proc (on Linux) or parses the
315 // 'environ' array (on FreeBSD) and does not use libc. This function should be
316 // called first inside __asan_init.
317 const char *GetEnv(const char *name
) {
318 #if SANITIZER_FREEBSD
319 if (::environ
!= 0) {
320 uptr NameLen
= internal_strlen(name
);
321 for (char **Env
= ::environ
; *Env
!= 0; Env
++) {
322 if (internal_strncmp(*Env
, name
, NameLen
) == 0 && (*Env
)[NameLen
] == '=')
323 return (*Env
) + NameLen
+ 1;
326 return 0; // Not found.
327 #elif SANITIZER_LINUX
328 static char *environ
;
334 len
= ReadFileToBuffer("/proc/self/environ",
335 &environ
, &environ_size
, 1 << 26);
337 if (!environ
|| len
== 0) return 0;
338 uptr namelen
= internal_strlen(name
);
339 const char *p
= environ
;
340 while (*p
!= '\0') { // will happen at the \0\0 that terminates the buffer
341 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
343 (char*)internal_memchr(p
, '\0', len
- (p
- environ
));
344 if (endp
== 0) // this entry isn't NUL terminated
346 else if (!internal_memcmp(p
, name
, namelen
) && p
[namelen
] == '=') // Match.
347 return p
+ namelen
+ 1; // point after =
350 return 0; // Not found.
352 #error "Unsupported platform"
357 SANITIZER_WEAK_ATTRIBUTE
extern void *__libc_stack_end
;
361 static void ReadNullSepFileToArray(const char *path
, char ***arr
,
365 *arr
= (char **)MmapOrDie(arr_size
* sizeof(char *), "NullSepFileArray");
366 ReadFileToBuffer(path
, &buff
, &buff_size
, 1024 * 1024);
369 for (count
= 1, i
= 1; ; i
++) {
371 if (buff
[i
+1] == 0) break;
372 (*arr
)[count
] = &buff
[i
+1];
373 CHECK_LE(count
, arr_size
- 1); // FIXME: make this more flexible.
381 static void GetArgsAndEnv(char*** argv
, char*** envp
) {
383 if (&__libc_stack_end
) {
385 uptr
* stack_end
= (uptr
*)__libc_stack_end
;
386 int argc
= *stack_end
;
387 *argv
= (char**)(stack_end
+ 1);
388 *envp
= (char**)(stack_end
+ argc
+ 2);
391 static const int kMaxArgv
= 2000, kMaxEnvp
= 2000;
392 ReadNullSepFileToArray("/proc/self/cmdline", argv
, kMaxArgv
);
393 ReadNullSepFileToArray("/proc/self/environ", envp
, kMaxEnvp
);
400 GetArgsAndEnv(&argv
, &envp
);
401 uptr rv
= internal_execve("/proc/self/exe", argv
, envp
);
403 CHECK_EQ(internal_iserror(rv
, &rverrno
), true);
404 Printf("execve failed, errno %d\n", rverrno
);
408 // Stub implementation of GetThreadStackAndTls for Go.
410 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
411 uptr
*tls_addr
, uptr
*tls_size
) {
417 #endif // SANITIZER_GO
425 BlockingMutex::BlockingMutex(LinkerInitialized
) {
429 BlockingMutex::BlockingMutex() {
430 internal_memset(this, 0, sizeof(*this));
433 void BlockingMutex::Lock() {
434 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
435 if (atomic_exchange(m
, MtxLocked
, memory_order_acquire
) == MtxUnlocked
)
437 while (atomic_exchange(m
, MtxSleeping
, memory_order_acquire
) != MtxUnlocked
) {
438 #if SANITIZER_FREEBSD
439 _umtx_op(m
, UMTX_OP_WAIT_UINT
, MtxSleeping
, 0, 0);
441 internal_syscall(SYSCALL(futex
), (uptr
)m
, FUTEX_WAIT
, MtxSleeping
, 0, 0, 0);
446 void BlockingMutex::Unlock() {
447 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
448 u32 v
= atomic_exchange(m
, MtxUnlocked
, memory_order_relaxed
);
449 CHECK_NE(v
, MtxUnlocked
);
450 if (v
== MtxSleeping
) {
451 #if SANITIZER_FREEBSD
452 _umtx_op(m
, UMTX_OP_WAKE
, 1, 0, 0);
454 internal_syscall(SYSCALL(futex
), (uptr
)m
, FUTEX_WAKE
, 1, 0, 0, 0);
459 void BlockingMutex::CheckLocked() {
460 atomic_uint32_t
*m
= reinterpret_cast<atomic_uint32_t
*>(&opaque_storage_
);
461 CHECK_NE(MtxUnlocked
, atomic_load(m
, memory_order_relaxed
));
464 // ----------------- sanitizer_linux.h
465 // The actual size of this structure is specified by d_reclen.
466 // Note that getdents64 uses a different structure format. We only provide the
467 // 32-bit syscall here.
468 struct linux_dirent
{
476 unsigned short d_reclen
;
481 uptr
internal_ptrace(int request
, int pid
, void *addr
, void *data
) {
482 return internal_syscall(SYSCALL(ptrace
), request
, pid
, (uptr
)addr
,
486 uptr
internal_waitpid(int pid
, int *status
, int options
) {
487 return internal_syscall(SYSCALL(wait4
), pid
, (uptr
)status
, options
,
491 uptr
internal_getpid() {
492 return internal_syscall(SYSCALL(getpid
));
495 uptr
internal_getppid() {
496 return internal_syscall(SYSCALL(getppid
));
499 uptr
internal_getdents(fd_t fd
, struct linux_dirent
*dirp
, unsigned int count
) {
500 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
501 return internal_syscall(SYSCALL(getdents64
), fd
, (uptr
)dirp
, count
);
503 return internal_syscall(SYSCALL(getdents
), fd
, (uptr
)dirp
, count
);
507 uptr
internal_lseek(fd_t fd
, OFF_T offset
, int whence
) {
508 return internal_syscall(SYSCALL(lseek
), fd
, offset
, whence
);
512 uptr
internal_prctl(int option
, uptr arg2
, uptr arg3
, uptr arg4
, uptr arg5
) {
513 return internal_syscall(SYSCALL(prctl
), option
, arg2
, arg3
, arg4
, arg5
);
517 uptr
internal_sigaltstack(const struct sigaltstack
*ss
,
518 struct sigaltstack
*oss
) {
519 return internal_syscall(SYSCALL(sigaltstack
), (uptr
)ss
, (uptr
)oss
);
522 int internal_fork() {
523 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
524 return internal_syscall(SYSCALL(clone
), SIGCHLD
, 0);
526 return internal_syscall(SYSCALL(fork
));
531 // Doesn't set sa_restorer, use with caution (see below).
532 int internal_sigaction_norestorer(int signum
, const void *act
, void *oldact
) {
533 __sanitizer_kernel_sigaction_t k_act
, k_oldact
;
534 internal_memset(&k_act
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
535 internal_memset(&k_oldact
, 0, sizeof(__sanitizer_kernel_sigaction_t
));
536 const __sanitizer_sigaction
*u_act
= (__sanitizer_sigaction
*)act
;
537 __sanitizer_sigaction
*u_oldact
= (__sanitizer_sigaction
*)oldact
;
539 k_act
.handler
= u_act
->handler
;
540 k_act
.sigaction
= u_act
->sigaction
;
541 internal_memcpy(&k_act
.sa_mask
, &u_act
->sa_mask
,
542 sizeof(__sanitizer_kernel_sigset_t
));
543 k_act
.sa_flags
= u_act
->sa_flags
;
544 // FIXME: most often sa_restorer is unset, however the kernel requires it
545 // to point to a valid signal restorer that calls the rt_sigreturn syscall.
546 // If sa_restorer passed to the kernel is NULL, the program may crash upon
547 // signal delivery or fail to unwind the stack in the signal handler.
548 // libc implementation of sigaction() passes its own restorer to
549 // rt_sigaction, so we need to do the same (we'll need to reimplement the
550 // restorers; for x86_64 the restorer address can be obtained from
551 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
552 k_act
.sa_restorer
= u_act
->sa_restorer
;
555 uptr result
= internal_syscall(SYSCALL(rt_sigaction
), (uptr
)signum
,
556 (uptr
)(u_act
? &k_act
: NULL
),
557 (uptr
)(u_oldact
? &k_oldact
: NULL
),
558 (uptr
)sizeof(__sanitizer_kernel_sigset_t
));
560 if ((result
== 0) && u_oldact
) {
561 u_oldact
->handler
= k_oldact
.handler
;
562 u_oldact
->sigaction
= k_oldact
.sigaction
;
563 internal_memcpy(&u_oldact
->sa_mask
, &k_oldact
.sa_mask
,
564 sizeof(__sanitizer_kernel_sigset_t
));
565 u_oldact
->sa_flags
= k_oldact
.sa_flags
;
566 u_oldact
->sa_restorer
= k_oldact
.sa_restorer
;
570 #endif // SANITIZER_LINUX
572 uptr
internal_sigprocmask(int how
, __sanitizer_sigset_t
*set
,
573 __sanitizer_sigset_t
*oldset
) {
574 #if SANITIZER_FREEBSD
575 return internal_syscall(SYSCALL(sigprocmask
), how
, set
, oldset
);
577 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
578 __sanitizer_kernel_sigset_t
*k_oldset
= (__sanitizer_kernel_sigset_t
*)oldset
;
579 return internal_syscall(SYSCALL(rt_sigprocmask
), (uptr
)how
,
580 (uptr
)&k_set
->sig
[0], (uptr
)&k_oldset
->sig
[0],
581 sizeof(__sanitizer_kernel_sigset_t
));
585 void internal_sigfillset(__sanitizer_sigset_t
*set
) {
586 internal_memset(set
, 0xff, sizeof(*set
));
590 void internal_sigdelset(__sanitizer_sigset_t
*set
, int signum
) {
593 CHECK_LT(signum
, sizeof(*set
) * 8);
594 __sanitizer_kernel_sigset_t
*k_set
= (__sanitizer_kernel_sigset_t
*)set
;
595 const uptr idx
= signum
/ (sizeof(k_set
->sig
[0]) * 8);
596 const uptr bit
= signum
% (sizeof(k_set
->sig
[0]) * 8);
597 k_set
->sig
[idx
] &= ~(1 << bit
);
599 #endif // SANITIZER_LINUX
601 // ThreadLister implementation.
602 ThreadLister::ThreadLister(int pid
)
607 entry_((struct linux_dirent
*)buffer_
.data()),
609 char task_directory_path
[80];
610 internal_snprintf(task_directory_path
, sizeof(task_directory_path
),
611 "/proc/%d/task/", pid
);
612 uptr openrv
= internal_open(task_directory_path
, O_RDONLY
| O_DIRECTORY
);
613 if (internal_iserror(openrv
)) {
615 Report("Can't open /proc/%d/task for reading.\n", pid
);
618 descriptor_
= openrv
;
622 int ThreadLister::GetNextTID() {
627 if ((char *)entry_
>= &buffer_
[bytes_read_
] && !GetDirectoryEntries())
629 if (entry_
->d_ino
!= 0 && entry_
->d_name
[0] >= '0' &&
630 entry_
->d_name
[0] <= '9') {
631 // Found a valid tid.
632 tid
= (int)internal_atoll(entry_
->d_name
);
634 entry_
= (struct linux_dirent
*)(((char *)entry_
) + entry_
->d_reclen
);
639 void ThreadLister::Reset() {
640 if (error_
|| descriptor_
< 0)
642 internal_lseek(descriptor_
, 0, SEEK_SET
);
645 ThreadLister::~ThreadLister() {
646 if (descriptor_
>= 0)
647 internal_close(descriptor_
);
650 bool ThreadLister::error() { return error_
; }
652 bool ThreadLister::GetDirectoryEntries() {
653 CHECK_GE(descriptor_
, 0);
654 CHECK_NE(error_
, true);
655 bytes_read_
= internal_getdents(descriptor_
,
656 (struct linux_dirent
*)buffer_
.data(),
658 if (internal_iserror(bytes_read_
)) {
659 Report("Can't read directory entries from /proc/%d/task.\n", pid_
);
662 } else if (bytes_read_
== 0) {
665 entry_
= (struct linux_dirent
*)buffer_
.data();
670 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
671 return EXEC_PAGESIZE
;
673 return sysconf(_SC_PAGESIZE
); // EXEC_PAGESIZE may not be trustworthy.
677 static char proc_self_exe_cache_str
[kMaxPathLength
];
678 static uptr proc_self_exe_cache_len
= 0;
680 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
681 if (proc_self_exe_cache_len
> 0) {
682 // If available, use the cached module name.
683 uptr module_name_len
=
684 internal_snprintf(buf
, buf_len
, "%s", proc_self_exe_cache_str
);
685 CHECK_LT(module_name_len
, buf_len
);
686 return module_name_len
;
688 #if SANITIZER_FREEBSD
689 const int Mib
[4] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1 };
690 size_t Size
= buf_len
;
691 bool IsErr
= (sysctl(Mib
, 4, buf
, &Size
, NULL
, 0) != 0);
692 int readlink_error
= IsErr
? errno
: 0;
693 uptr module_name_len
= Size
;
695 uptr module_name_len
= internal_readlink(
696 "/proc/self/exe", buf
, buf_len
);
698 bool IsErr
= internal_iserror(module_name_len
, &readlink_error
);
701 // We can't read /proc/self/exe for some reason, assume the name of the
702 // binary is unknown.
703 Report("WARNING: readlink(\"/proc/self/exe\") failed with errno %d, "
704 "some stack frames may not be symbolized\n", readlink_error
);
705 module_name_len
= internal_snprintf(buf
, buf_len
, "/proc/self/exe");
706 CHECK_LT(module_name_len
, buf_len
);
708 return module_name_len
;
711 void CacheBinaryName() {
712 if (!proc_self_exe_cache_len
) {
713 proc_self_exe_cache_len
=
714 ReadBinaryName(proc_self_exe_cache_str
, kMaxPathLength
);
718 // Match full names of the form /path/to/base_name{-,.}*
719 bool LibraryNameIs(const char *full_name
, const char *base_name
) {
720 const char *name
= full_name
;
722 while (*name
!= '\0') name
++;
723 while (name
> full_name
&& *name
!= '/') name
--;
724 if (*name
== '/') name
++;
725 uptr base_name_length
= internal_strlen(base_name
);
726 if (internal_strncmp(name
, base_name
, base_name_length
)) return false;
727 return (name
[base_name_length
] == '-' || name
[base_name_length
] == '.');
730 #if !SANITIZER_ANDROID
731 // Call cb for each region mapped by map.
732 void ForEachMappedRegion(link_map
*map
, void (*cb
)(const void *, uptr
)) {
733 #if !SANITIZER_FREEBSD
734 typedef ElfW(Phdr
) Elf_Phdr
;
735 typedef ElfW(Ehdr
) Elf_Ehdr
;
736 #endif // !SANITIZER_FREEBSD
737 char *base
= (char *)map
->l_addr
;
738 Elf_Ehdr
*ehdr
= (Elf_Ehdr
*)base
;
739 char *phdrs
= base
+ ehdr
->e_phoff
;
740 char *phdrs_end
= phdrs
+ ehdr
->e_phnum
* ehdr
->e_phentsize
;
742 // Find the segment with the minimum base so we can "relocate" the p_vaddr
743 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
744 // objects have a non-zero base.
745 uptr preferred_base
= (uptr
)-1;
746 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
747 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
748 if (phdr
->p_type
== PT_LOAD
&& preferred_base
> (uptr
)phdr
->p_vaddr
)
749 preferred_base
= (uptr
)phdr
->p_vaddr
;
752 // Compute the delta from the real base to get a relocation delta.
753 sptr delta
= (uptr
)base
- preferred_base
;
754 // Now we can figure out what the loader really mapped.
755 for (char *iter
= phdrs
; iter
!= phdrs_end
; iter
+= ehdr
->e_phentsize
) {
756 Elf_Phdr
*phdr
= (Elf_Phdr
*)iter
;
757 if (phdr
->p_type
== PT_LOAD
) {
758 uptr seg_start
= phdr
->p_vaddr
+ delta
;
759 uptr seg_end
= seg_start
+ phdr
->p_memsz
;
760 // None of these values are aligned. We consider the ragged edges of the
761 // load command as defined, since they are mapped from the file.
762 seg_start
= RoundDownTo(seg_start
, GetPageSizeCached());
763 seg_end
= RoundUpTo(seg_end
, GetPageSizeCached());
764 cb((void *)seg_start
, seg_end
- seg_start
);
770 #if defined(__x86_64__) && SANITIZER_LINUX
771 // We cannot use glibc's clone wrapper, because it messes with the child
772 // task's TLS. It writes the PID and TID of the child task to its thread
773 // descriptor, but in our case the child task shares the thread descriptor with
774 // the parent (because we don't know how to allocate a new thread
775 // descriptor to keep glibc happy). So the stock version of clone(), when
776 // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
777 uptr
internal_clone(int (*fn
)(void *), void *child_stack
, int flags
, void *arg
,
778 int *parent_tidptr
, void *newtls
, int *child_tidptr
) {
780 if (!fn
|| !child_stack
)
782 CHECK_EQ(0, (uptr
)child_stack
% 16);
783 child_stack
= (char *)child_stack
- 2 * sizeof(unsigned long long);
784 ((unsigned long long *)child_stack
)[0] = (uptr
)fn
;
785 ((unsigned long long *)child_stack
)[1] = (uptr
)arg
;
786 register void *r8
__asm__("r8") = newtls
;
787 register int *r10
__asm__("r10") = child_tidptr
;
788 __asm__
__volatile__(
789 /* %rax = syscall(%rax = SYSCALL(clone),
791 * %rsi = child_stack,
792 * %rdx = parent_tidptr,
794 * %r10 = child_tidptr)
801 "testq %%rax,%%rax\n"
804 /* In the child. Terminate unwind chain. */
805 // XXX: We should also terminate the CFI unwind chain
806 // here. Unfortunately clang 3.2 doesn't support the
807 // necessary CFI directives, so we skip that part.
810 /* Call "fn(arg)". */
815 /* Call _exit(%rax). */
820 /* Return to parent. */
823 : "a"(SYSCALL(clone
)), "i"(SYSCALL(exit
)),
829 : "rsp", "memory", "r11", "rcx");
832 #endif // defined(__x86_64__) && SANITIZER_LINUX
834 #if SANITIZER_ANDROID
835 static atomic_uint8_t android_log_initialized
;
837 void AndroidLogInit() {
838 atomic_store(&android_log_initialized
, 1, memory_order_release
);
840 // This thing is not, strictly speaking, async signal safe, but it does not seem
841 // to cause any issues. Alternative is writing to log devices directly, but
842 // their location and message format might change in the future, so we'd really
843 // like to avoid that.
844 void AndroidLogWrite(const char *buffer
) {
845 if (!atomic_load(&android_log_initialized
, memory_order_acquire
))
848 char *copy
= internal_strdup(buffer
);
851 // __android_log_write has an implicit message length limit.
852 // Print one line at a time.
854 q
= internal_strchr(p
, '\n');
856 __android_log_write(ANDROID_LOG_INFO
, NULL
, p
);
862 void GetExtraActivationFlags(char *buf
, uptr size
) {
863 CHECK(size
> PROP_VALUE_MAX
);
864 __system_property_get("asan.options", buf
);
868 bool IsDeadlySignal(int signum
) {
869 return (signum
== SIGSEGV
) && common_flags()->handle_segv
;
872 } // namespace __sanitizer
874 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX