#include "sanitizer_platform.h"
#if SANITIZER_LINUX && \
(defined(__x86_64__) || defined(__mips__) || defined(__aarch64__) || \
defined(__powerpc64__) || defined(__s390__) || defined(__i386__) || \
defined(__arm__) || SANITIZER_RISCV64 || SANITIZER_LOONGARCH64)
#include "sanitizer_stoptheworld.h"
#include "sanitizer_platform_limits_posix.h"
#include "sanitizer_atomic.h"
#include <errno.h>
#include <sched.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <elf.h>
#if (defined(__aarch64__) || defined(__powerpc64__) || \
SANITIZER_RISCV64 || SANITIZER_LOONGARCH64) && \
!SANITIZER_ANDROID
# include <asm/ptrace.h>
#endif
#include <sys/user.h>
# if SANITIZER_MIPS
# include <asm/sgidefs.h>
# include <asm/reg.h>
# endif
# include <sys/wait.h>
# ifdef sa_handler
# undef sa_handler
# endif
# ifdef sa_sigaction
# undef sa_sigaction
# endif
# include "sanitizer_common.h"
# include "sanitizer_flags.h"
# include "sanitizer_libc.h"
# include "sanitizer_linux.h"
# include "sanitizer_mutex.h"
# include "sanitizer_placement_new.h"
#ifndef PR_SET_PTRACER
#define PR_SET_PTRACER 0x59616d61
#endif
namespace __sanitizer {
class SuspendedThreadsListLinux final : public SuspendedThreadsList {
public:
SuspendedThreadsListLinux() { thread_ids_.reserve(1024); }
ThreadID GetThreadID(uptr index) const override;
uptr ThreadCount() const override;
bool ContainsTid(ThreadID thread_id) const;
void Append(ThreadID tid);
PtraceRegistersStatus GetRegistersAndSP(uptr index,
InternalMmapVector<uptr> *buffer,
uptr *sp) const override;
private:
InternalMmapVector<ThreadID> thread_ids_;
};
struct TracerThreadArgument {
StopTheWorldCallback callback;
void *callback_argument;
Mutex mutex;
atomic_uintptr_t done;
uptr parent_pid;
};
class ThreadSuspender {
public:
explicit ThreadSuspender(pid_t pid, TracerThreadArgument *arg)
: arg(arg)
, pid_(pid) {
CHECK_GE(pid, 0);
}
bool SuspendAllThreads();
void ResumeAllThreads();
void KillAllThreads();
SuspendedThreadsListLinux &suspended_threads_list() {
return suspended_threads_list_;
}
TracerThreadArgument *arg;
private:
SuspendedThreadsListLinux suspended_threads_list_;
pid_t pid_;
bool SuspendThread(ThreadID thread_id);
};
bool ThreadSuspender::SuspendThread(ThreadID tid) {
int pterrno;
if (internal_iserror(internal_ptrace(PTRACE_ATTACH, tid, nullptr, nullptr),
&pterrno)) {
VReport(1, "Could not attach to thread %zu (errno %d).\n", (uptr)tid,
pterrno);
return false;
} else {
VReport(2, "Attached to thread %zu.\n", (uptr)tid);
for (;;) {
int status;
uptr waitpid_status;
HANDLE_EINTR(waitpid_status, internal_waitpid(tid, &status, __WALL));
int wperrno;
if (internal_iserror(waitpid_status, &wperrno)) {
VReport(1, "Waiting on thread %zu failed, detaching (errno %d).\n",
(uptr)tid, wperrno);
internal_ptrace(PTRACE_DETACH, tid, nullptr, nullptr);
return false;
}
if (WIFSTOPPED(status) && WSTOPSIG(status) != SIGSTOP) {
internal_ptrace(PTRACE_CONT, tid, nullptr,
(void*)(uptr)WSTOPSIG(status));
continue;
}
break;
}
suspended_threads_list_.Append(tid);
return true;
}
}
void ThreadSuspender::ResumeAllThreads() {
for (uptr i = 0; i < suspended_threads_list_.ThreadCount(); i++) {
pid_t tid = suspended_threads_list_.GetThreadID(i);
int pterrno;
if (!internal_iserror(internal_ptrace(PTRACE_DETACH, tid, nullptr, nullptr),
&pterrno)) {
VReport(2, "Detached from thread %d.\n", tid);
} else {
VReport(1, "Could not detach from thread %d (errno %d).\n", tid, pterrno);
}
}
}
void ThreadSuspender::KillAllThreads() {
for (uptr i = 0; i < suspended_threads_list_.ThreadCount(); i++)
internal_ptrace(PTRACE_KILL, suspended_threads_list_.GetThreadID(i),
nullptr, nullptr);
}
bool ThreadSuspender::SuspendAllThreads() {
ThreadLister thread_lister(pid_);
bool retry = true;
InternalMmapVector<ThreadID> threads;
threads.reserve(128);
for (int i = 0; i < 30 && retry; ++i) {
retry = false;
switch (thread_lister.ListThreads(&threads)) {
case ThreadLister::Error:
ResumeAllThreads();
VReport(1, "Failed to list threads\n");
return false;
case ThreadLister::Incomplete:
VReport(1, "Incomplete list\n");
retry = true;
break;
case ThreadLister::Ok:
break;
}
for (ThreadID tid : threads) {
if (suspended_threads_list_.ContainsTid(tid))
continue;
if (SuspendThread(tid))
retry = true;
else
VReport(2, "%llu/status: %s\n", tid, thread_lister.LoadStatus(tid));
}
if (retry)
VReport(1, "SuspendAllThreads retry: %d\n", i);
}
return suspended_threads_list_.ThreadCount();
}
static ThreadSuspender *thread_suspender_instance = nullptr;
static const int kSyncSignals[] = { SIGABRT, SIGILL, SIGFPE, SIGSEGV, SIGBUS,
SIGXCPU, SIGXFSZ };
static void TracerThreadDieCallback() {
ThreadSuspender *inst = thread_suspender_instance;
if (inst && stoptheworld_tracer_pid == internal_getpid()) {
inst->KillAllThreads();
thread_suspender_instance = nullptr;
}
}
static void TracerThreadSignalHandler(int signum, __sanitizer_siginfo *siginfo,
void *uctx) {
SignalContext ctx(siginfo, uctx);
Printf("Tracer caught signal %d: addr=%p pc=%p sp=%p\n", signum,
(void *)ctx.addr, (void *)ctx.pc, (void *)ctx.sp);
ThreadSuspender *inst = thread_suspender_instance;
if (inst) {
if (signum == SIGABRT)
inst->KillAllThreads();
else
inst->ResumeAllThreads();
RAW_CHECK(RemoveDieCallback(TracerThreadDieCallback));
thread_suspender_instance = nullptr;
atomic_store(&inst->arg->done, 1, memory_order_relaxed);
}
internal__exit((signum == SIGABRT) ? 1 : 2);
}
static const int kHandlerStackSize = 8192;
static int TracerThread(void* argument) {
TracerThreadArgument *tracer_thread_argument =
(TracerThreadArgument *)argument;
internal_prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
if (internal_getppid() != tracer_thread_argument->parent_pid)
internal__exit(4);
tracer_thread_argument->mutex.Lock();
tracer_thread_argument->mutex.Unlock();
RAW_CHECK(AddDieCallback(TracerThreadDieCallback));
ThreadSuspender thread_suspender(internal_getppid(), tracer_thread_argument);
thread_suspender_instance = &thread_suspender;
InternalMmapVector<char> handler_stack_memory(kHandlerStackSize);
stack_t handler_stack;
internal_memset(&handler_stack, 0, sizeof(handler_stack));
handler_stack.ss_sp = handler_stack_memory.data();
handler_stack.ss_size = kHandlerStackSize;
internal_sigaltstack(&handler_stack, nullptr);
for (uptr i = 0; i < ARRAY_SIZE(kSyncSignals); i++) {
__sanitizer_sigaction act;
internal_memset(&act, 0, sizeof(act));
act.sigaction = TracerThreadSignalHandler;
act.sa_flags = SA_ONSTACK | SA_SIGINFO;
internal_sigaction_norestorer(kSyncSignals[i], &act, 0);
}
int exit_code = 0;
if (!thread_suspender.SuspendAllThreads()) {
VReport(1, "Failed suspending threads.\n");
exit_code = 3;
} else {
tracer_thread_argument->callback(thread_suspender.suspended_threads_list(),
tracer_thread_argument->callback_argument);
thread_suspender.ResumeAllThreads();
exit_code = 0;
}
RAW_CHECK(RemoveDieCallback(TracerThreadDieCallback));
thread_suspender_instance = nullptr;
atomic_store(&tracer_thread_argument->done, 1, memory_order_relaxed);
return exit_code;
}
class ScopedStackSpaceWithGuard {
public:
explicit ScopedStackSpaceWithGuard(uptr stack_size) {
stack_size_ = stack_size;
guard_size_ = GetPageSizeCached();
guard_start_ = (uptr)MmapOrDie(stack_size_ + guard_size_,
"ScopedStackWithGuard");
CHECK(MprotectNoAccess((uptr)guard_start_, guard_size_));
}
~ScopedStackSpaceWithGuard() {
UnmapOrDie((void *)guard_start_, stack_size_ + guard_size_);
}
void *Bottom() const {
return (void *)(guard_start_ + stack_size_ + guard_size_);
}
private:
uptr stack_size_;
uptr guard_size_;
uptr guard_start_;
};
static __sanitizer_sigset_t blocked_sigset;
static __sanitizer_sigset_t old_sigset;
class StopTheWorldScope {
public:
StopTheWorldScope() {
process_was_dumpable_ = internal_prctl(PR_GET_DUMPABLE, 0, 0, 0, 0);
if (!process_was_dumpable_)
internal_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
}
~StopTheWorldScope() {
if (!process_was_dumpable_)
internal_prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
}
private:
int process_was_dumpable_;
};
struct ScopedSetTracerPID {
explicit ScopedSetTracerPID(uptr tracer_pid) {
stoptheworld_tracer_pid = tracer_pid;
stoptheworld_tracer_ppid = internal_getpid();
}
~ScopedSetTracerPID() {
stoptheworld_tracer_pid = 0;
stoptheworld_tracer_ppid = 0;
}
};
static void TestPTrace() {
# if SANITIZER_SPARC
VReport(1, "WARNING: skipping TestPTrace() because this is SPARC\n");
VReport(1,
"If seccomp blocks ptrace, LeakSanitizer may hang without further "
"notice\n");
VReport(
1,
"If seccomp does not block ptrace, you can safely ignore this warning\n");
# else
static bool checked = false;
if (checked)
return;
checked = true;
int pid = internal_fork();
if (pid < 0) {
int rverrno;
if (internal_iserror(pid, &rverrno))
VReport(0, "WARNING: TestPTrace() failed to fork (errno %d)\n", rverrno);
return;
}
if (pid == 0) {
internal_ptrace(PTRACE_ATTACH, 0, nullptr, nullptr);
internal__exit(0);
} else {
int wstatus;
internal_waitpid(pid, &wstatus, 0);
if (WIFSIGNALED(wstatus)) {
VReport(0,
"WARNING: ptrace appears to be blocked (is seccomp enabled?). "
"LeakSanitizer may hang.\n");
VReport(0, "Child exited with signal %d.\n", WTERMSIG(wstatus));
}
}
# endif
}
void StopTheWorld(StopTheWorldCallback callback, void *argument) {
TestPTrace();
StopTheWorldScope in_stoptheworld;
struct TracerThreadArgument tracer_thread_argument;
tracer_thread_argument.callback = callback;
tracer_thread_argument.callback_argument = argument;
tracer_thread_argument.parent_pid = internal_getpid();
atomic_store(&tracer_thread_argument.done, 0, memory_order_relaxed);
const uptr kTracerStackSize = 2 * 1024 * 1024;
ScopedStackSpaceWithGuard tracer_stack(kTracerStackSize);
tracer_thread_argument.mutex.Lock();
internal_sigfillset(&blocked_sigset);
for (uptr i = 0; i < ARRAY_SIZE(kSyncSignals); i++)
internal_sigdelset(&blocked_sigset, kSyncSignals[i]);
int rv = internal_sigprocmask(SIG_BLOCK, &blocked_sigset, &old_sigset);
CHECK_EQ(rv, 0);
uptr tracer_pid = internal_clone(
TracerThread, tracer_stack.Bottom(),
CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_UNTRACED,
&tracer_thread_argument, nullptr ,
nullptr , nullptr );
internal_sigprocmask(SIG_SETMASK, &old_sigset, 0);
int local_errno = 0;
if (internal_iserror(tracer_pid, &local_errno)) {
VReport(1, "Failed spawning a tracer thread (errno %d).\n", local_errno);
tracer_thread_argument.mutex.Unlock();
} else {
ScopedSetTracerPID scoped_set_tracer_pid(tracer_pid);
internal_prctl(PR_SET_PTRACER, tracer_pid, 0, 0, 0);
tracer_thread_argument.mutex.Unlock();
while (atomic_load(&tracer_thread_argument.done, memory_order_relaxed) == 0)
sched_yield();
for (;;) {
uptr waitpid_status = internal_waitpid(tracer_pid, nullptr, __WALL);
if (!internal_iserror(waitpid_status, &local_errno))
break;
if (local_errno == EINTR)
continue;
VReport(1, "Waiting on the tracer thread failed (errno %d).\n",
local_errno);
break;
}
}
}
#if SANITIZER_ANDROID && defined(__arm__)
typedef pt_regs regs_struct;
#define REG_SP ARM_sp
#elif SANITIZER_LINUX && defined(__arm__)
typedef user_regs regs_struct;
#define REG_SP uregs[13]
#elif defined(__i386__) || defined(__x86_64__)
typedef user_regs_struct regs_struct;
#if defined(__i386__)
#define REG_SP esp
#else
#define REG_SP rsp
#endif
#define ARCH_IOVEC_FOR_GETREGSET
#ifndef NT_X86_XSTATE
#define NT_X86_XSTATE 0x202
#endif
#ifndef PTRACE_GETREGSET
#define PTRACE_GETREGSET 0x4204
#endif
static constexpr uptr kExtraRegs[] = {NT_X86_XSTATE, NT_FPREGSET};
#elif defined(__powerpc__) || defined(__powerpc64__)
typedef pt_regs regs_struct;
#define REG_SP gpr[PT_R1]
#elif defined(__mips__)
typedef struct user regs_struct;
# define REG_SP regs[EF_R29]
#elif defined(__aarch64__)
typedef struct user_pt_regs regs_struct;
#define REG_SP sp
static constexpr uptr kExtraRegs[] = {0};
#define ARCH_IOVEC_FOR_GETREGSET
#elif defined(__loongarch__)
typedef struct user_pt_regs regs_struct;
#define REG_SP regs[3]
static constexpr uptr kExtraRegs[] = {0};
#define ARCH_IOVEC_FOR_GETREGSET
#elif SANITIZER_RISCV64
typedef struct user_regs_struct regs_struct;
#undef REG_SP
#define REG_SP sp
static constexpr uptr kExtraRegs[] = {0};
#define ARCH_IOVEC_FOR_GETREGSET
#elif defined(__s390__)
typedef _user_regs_struct regs_struct;
#define REG_SP gprs[15]
static constexpr uptr kExtraRegs[] = {0};
#define ARCH_IOVEC_FOR_GETREGSET
#else
#error "Unsupported architecture"
#endif
ThreadID SuspendedThreadsListLinux::GetThreadID(uptr index) const {
CHECK_LT(index, thread_ids_.size());
return thread_ids_[index];
}
uptr SuspendedThreadsListLinux::ThreadCount() const {
return thread_ids_.size();
}
bool SuspendedThreadsListLinux::ContainsTid(ThreadID thread_id) const {
for (uptr i = 0; i < thread_ids_.size(); i++) {
if (thread_ids_[i] == thread_id) return true;
}
return false;
}
void SuspendedThreadsListLinux::Append(ThreadID tid) {
thread_ids_.push_back(tid);
}
PtraceRegistersStatus SuspendedThreadsListLinux::GetRegistersAndSP(
uptr index, InternalMmapVector<uptr> *buffer, uptr *sp) const {
pid_t tid = GetThreadID(index);
constexpr uptr uptr_sz = sizeof(uptr);
int pterrno;
#ifdef ARCH_IOVEC_FOR_GETREGSET
auto AppendF = [&](uptr regset) {
uptr size = buffer->size();
uptr size_up = RoundUpTo(size, 8 / uptr_sz);
buffer->reserve(Max<uptr>(1024, size_up));
struct iovec regset_io;
for (;; buffer->resize(buffer->capacity() * 2)) {
buffer->resize(buffer->capacity());
uptr available_bytes = (buffer->size() - size_up) * uptr_sz;
regset_io.iov_base = buffer->data() + size_up;
regset_io.iov_len = available_bytes;
bool fail =
internal_iserror(internal_ptrace(PTRACE_GETREGSET, tid,
(void *)regset, (void *)®set_io),
&pterrno);
if (fail) {
VReport(1, "Could not get regset %p from thread %d (errno %d).\n",
(void *)regset, tid, pterrno);
buffer->resize(size);
return false;
}
if (regset_io.iov_len + 64 < available_bytes)
break;
}
buffer->resize(size_up + RoundUpTo(regset_io.iov_len, uptr_sz) / uptr_sz);
return true;
};
buffer->clear();
bool fail = !AppendF(NT_PRSTATUS);
if (!fail) {
for (uptr regs : kExtraRegs)
if (regs && AppendF(regs))
break;
}
#else
buffer->resize(RoundUpTo(sizeof(regs_struct), uptr_sz) / uptr_sz);
bool fail = internal_iserror(
internal_ptrace(PTRACE_GETREGS, tid, nullptr, buffer->data()), &pterrno);
if (fail)
VReport(1, "Could not get registers from thread %d (errno %d).\n", tid,
pterrno);
#endif
if (fail) {
return pterrno == ESRCH ? REGISTERS_UNAVAILABLE_FATAL
: REGISTERS_UNAVAILABLE;
}
*sp = reinterpret_cast<regs_struct *>(buffer->data())[0].REG_SP;
return REGISTERS_AVAILABLE;
}
}
#endif