1 //===-- sanitizer_stoptheworld_linux_libcdep.cpp --------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // See sanitizer_stoptheworld.h for details. 10 // This implementation was inspired by Markus Gutschke's linuxthreads.cc. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "sanitizer_platform.h" 15 16 #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__mips__) || \ 17 defined(__aarch64__) || defined(__powerpc64__) || \ 18 defined(__s390__) || defined(__i386__) || \ 19 defined(__arm__)) 20 21 #include "sanitizer_stoptheworld.h" 22 23 #include "sanitizer_platform_limits_posix.h" 24 #include "sanitizer_atomic.h" 25 26 #include <errno.h> 27 #include <sched.h> // for CLONE_* definitions 28 #include <stddef.h> 29 #include <sys/prctl.h> // for PR_* definitions 30 #include <sys/ptrace.h> // for PTRACE_* definitions 31 #include <sys/types.h> // for pid_t 32 #include <sys/uio.h> // for iovec 33 #include <elf.h> // for NT_PRSTATUS 34 #if defined(__aarch64__) && !SANITIZER_ANDROID 35 // GLIBC 2.20+ sys/user does not include asm/ptrace.h 36 # include <asm/ptrace.h> 37 #endif 38 #include <sys/user.h> // for user_regs_struct 39 #if SANITIZER_ANDROID && SANITIZER_MIPS 40 # include <asm/reg.h> // for mips SP register in sys/user.h 41 #endif 42 #include <sys/wait.h> // for signal-related stuff 43 44 #ifdef sa_handler 45 # undef sa_handler 46 #endif 47 48 #ifdef sa_sigaction 49 # undef sa_sigaction 50 #endif 51 52 #include "sanitizer_common.h" 53 #include "sanitizer_flags.h" 54 #include "sanitizer_libc.h" 55 #include "sanitizer_linux.h" 56 #include "sanitizer_mutex.h" 57 #include "sanitizer_placement_new.h" 58 59 // Sufficiently old kernel headers don't provide this value, but we can still 60 // call prctl with it. If the runtime kernel is new enough, the prctl call will 61 // have the desired effect; if the kernel is too old, the call will error and we 62 // can ignore said error. 63 #ifndef PR_SET_PTRACER 64 #define PR_SET_PTRACER 0x59616d61 65 #endif 66 67 // This module works by spawning a Linux task which then attaches to every 68 // thread in the caller process with ptrace. This suspends the threads, and 69 // PTRACE_GETREGS can then be used to obtain their register state. The callback 70 // supplied to StopTheWorld() is run in the tracer task while the threads are 71 // suspended. 72 // The tracer task must be placed in a different thread group for ptrace to 73 // work, so it cannot be spawned as a pthread. Instead, we use the low-level 74 // clone() interface (we want to share the address space with the caller 75 // process, so we prefer clone() over fork()). 76 // 77 // We don't use any libc functions, relying instead on direct syscalls. There 78 // are two reasons for this: 79 // 1. calling a library function while threads are suspended could cause a 80 // deadlock, if one of the treads happens to be holding a libc lock; 81 // 2. it's generally not safe to call libc functions from the tracer task, 82 // because clone() does not set up a thread-local storage for it. Any 83 // thread-local variables used by libc will be shared between the tracer task 84 // and the thread which spawned it. 85 86 namespace __sanitizer { 87 88 class SuspendedThreadsListLinux : public SuspendedThreadsList { 89 public: 90 SuspendedThreadsListLinux() { thread_ids_.reserve(1024); } 91 92 tid_t GetThreadID(uptr index) const; 93 uptr ThreadCount() const; 94 bool ContainsTid(tid_t thread_id) const; 95 void Append(tid_t tid); 96 97 PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer, 98 uptr *sp) const; 99 uptr RegisterCount() const; 100 101 private: 102 InternalMmapVector<tid_t> thread_ids_; 103 }; 104 105 // Structure for passing arguments into the tracer thread. 106 struct TracerThreadArgument { 107 StopTheWorldCallback callback; 108 void *callback_argument; 109 // The tracer thread waits on this mutex while the parent finishes its 110 // preparations. 111 BlockingMutex mutex; 112 // Tracer thread signals its completion by setting done. 113 atomic_uintptr_t done; 114 uptr parent_pid; 115 }; 116 117 // This class handles thread suspending/unsuspending in the tracer thread. 118 class ThreadSuspender { 119 public: 120 explicit ThreadSuspender(pid_t pid, TracerThreadArgument *arg) 121 : arg(arg) 122 , pid_(pid) { 123 CHECK_GE(pid, 0); 124 } 125 bool SuspendAllThreads(); 126 void ResumeAllThreads(); 127 void KillAllThreads(); 128 SuspendedThreadsListLinux &suspended_threads_list() { 129 return suspended_threads_list_; 130 } 131 TracerThreadArgument *arg; 132 private: 133 SuspendedThreadsListLinux suspended_threads_list_; 134 pid_t pid_; 135 bool SuspendThread(tid_t thread_id); 136 }; 137 138 bool ThreadSuspender::SuspendThread(tid_t tid) { 139 // Are we already attached to this thread? 140 // Currently this check takes linear time, however the number of threads is 141 // usually small. 142 if (suspended_threads_list_.ContainsTid(tid)) return false; 143 int pterrno; 144 if (internal_iserror(internal_ptrace(PTRACE_ATTACH, tid, nullptr, nullptr), 145 &pterrno)) { 146 // Either the thread is dead, or something prevented us from attaching. 147 // Log this event and move on. 148 VReport(1, "Could not attach to thread %zu (errno %d).\n", (uptr)tid, 149 pterrno); 150 return false; 151 } else { 152 VReport(2, "Attached to thread %zu.\n", (uptr)tid); 153 // The thread is not guaranteed to stop before ptrace returns, so we must 154 // wait on it. Note: if the thread receives a signal concurrently, 155 // we can get notification about the signal before notification about stop. 156 // In such case we need to forward the signal to the thread, otherwise 157 // the signal will be missed (as we do PTRACE_DETACH with arg=0) and 158 // any logic relying on signals will break. After forwarding we need to 159 // continue to wait for stopping, because the thread is not stopped yet. 160 // We do ignore delivery of SIGSTOP, because we want to make stop-the-world 161 // as invisible as possible. 162 for (;;) { 163 int status; 164 uptr waitpid_status; 165 HANDLE_EINTR(waitpid_status, internal_waitpid(tid, &status, __WALL)); 166 int wperrno; 167 if (internal_iserror(waitpid_status, &wperrno)) { 168 // Got a ECHILD error. I don't think this situation is possible, but it 169 // doesn't hurt to report it. 170 VReport(1, "Waiting on thread %zu failed, detaching (errno %d).\n", 171 (uptr)tid, wperrno); 172 internal_ptrace(PTRACE_DETACH, tid, nullptr, nullptr); 173 return false; 174 } 175 if (WIFSTOPPED(status) && WSTOPSIG(status) != SIGSTOP) { 176 internal_ptrace(PTRACE_CONT, tid, nullptr, 177 (void*)(uptr)WSTOPSIG(status)); 178 continue; 179 } 180 break; 181 } 182 suspended_threads_list_.Append(tid); 183 return true; 184 } 185 } 186 187 void ThreadSuspender::ResumeAllThreads() { 188 for (uptr i = 0; i < suspended_threads_list_.ThreadCount(); i++) { 189 pid_t tid = suspended_threads_list_.GetThreadID(i); 190 int pterrno; 191 if (!internal_iserror(internal_ptrace(PTRACE_DETACH, tid, nullptr, nullptr), 192 &pterrno)) { 193 VReport(2, "Detached from thread %d.\n", tid); 194 } else { 195 // Either the thread is dead, or we are already detached. 196 // The latter case is possible, for instance, if this function was called 197 // from a signal handler. 198 VReport(1, "Could not detach from thread %d (errno %d).\n", tid, pterrno); 199 } 200 } 201 } 202 203 void ThreadSuspender::KillAllThreads() { 204 for (uptr i = 0; i < suspended_threads_list_.ThreadCount(); i++) 205 internal_ptrace(PTRACE_KILL, suspended_threads_list_.GetThreadID(i), 206 nullptr, nullptr); 207 } 208 209 bool ThreadSuspender::SuspendAllThreads() { 210 ThreadLister thread_lister(pid_); 211 bool retry = true; 212 InternalMmapVector<tid_t> threads; 213 threads.reserve(128); 214 for (int i = 0; i < 30 && retry; ++i) { 215 retry = false; 216 switch (thread_lister.ListThreads(&threads)) { 217 case ThreadLister::Error: 218 ResumeAllThreads(); 219 return false; 220 case ThreadLister::Incomplete: 221 retry = true; 222 break; 223 case ThreadLister::Ok: 224 break; 225 } 226 for (tid_t tid : threads) 227 if (SuspendThread(tid)) 228 retry = true; 229 }; 230 return suspended_threads_list_.ThreadCount(); 231 } 232 233 // Pointer to the ThreadSuspender instance for use in signal handler. 234 static ThreadSuspender *thread_suspender_instance = nullptr; 235 236 // Synchronous signals that should not be blocked. 237 static const int kSyncSignals[] = { SIGABRT, SIGILL, SIGFPE, SIGSEGV, SIGBUS, 238 SIGXCPU, SIGXFSZ }; 239 240 static void TracerThreadDieCallback() { 241 // Generally a call to Die() in the tracer thread should be fatal to the 242 // parent process as well, because they share the address space. 243 // This really only works correctly if all the threads are suspended at this 244 // point. So we correctly handle calls to Die() from within the callback, but 245 // not those that happen before or after the callback. Hopefully there aren't 246 // a lot of opportunities for that to happen... 247 ThreadSuspender *inst = thread_suspender_instance; 248 if (inst && stoptheworld_tracer_pid == internal_getpid()) { 249 inst->KillAllThreads(); 250 thread_suspender_instance = nullptr; 251 } 252 } 253 254 // Signal handler to wake up suspended threads when the tracer thread dies. 255 static void TracerThreadSignalHandler(int signum, __sanitizer_siginfo *siginfo, 256 void *uctx) { 257 SignalContext ctx(siginfo, uctx); 258 Printf("Tracer caught signal %d: addr=0x%zx pc=0x%zx sp=0x%zx\n", signum, 259 ctx.addr, ctx.pc, ctx.sp); 260 ThreadSuspender *inst = thread_suspender_instance; 261 if (inst) { 262 if (signum == SIGABRT) 263 inst->KillAllThreads(); 264 else 265 inst->ResumeAllThreads(); 266 RAW_CHECK(RemoveDieCallback(TracerThreadDieCallback)); 267 thread_suspender_instance = nullptr; 268 atomic_store(&inst->arg->done, 1, memory_order_relaxed); 269 } 270 internal__exit((signum == SIGABRT) ? 1 : 2); 271 } 272 273 // Size of alternative stack for signal handlers in the tracer thread. 274 static const int kHandlerStackSize = 8192; 275 276 // This function will be run as a cloned task. 277 static int TracerThread(void* argument) { 278 TracerThreadArgument *tracer_thread_argument = 279 (TracerThreadArgument *)argument; 280 281 internal_prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); 282 // Check if parent is already dead. 283 if (internal_getppid() != tracer_thread_argument->parent_pid) 284 internal__exit(4); 285 286 // Wait for the parent thread to finish preparations. 287 tracer_thread_argument->mutex.Lock(); 288 tracer_thread_argument->mutex.Unlock(); 289 290 RAW_CHECK(AddDieCallback(TracerThreadDieCallback)); 291 292 ThreadSuspender thread_suspender(internal_getppid(), tracer_thread_argument); 293 // Global pointer for the signal handler. 294 thread_suspender_instance = &thread_suspender; 295 296 // Alternate stack for signal handling. 297 InternalMmapVector<char> handler_stack_memory(kHandlerStackSize); 298 stack_t handler_stack; 299 internal_memset(&handler_stack, 0, sizeof(handler_stack)); 300 handler_stack.ss_sp = handler_stack_memory.data(); 301 handler_stack.ss_size = kHandlerStackSize; 302 internal_sigaltstack(&handler_stack, nullptr); 303 304 // Install our handler for synchronous signals. Other signals should be 305 // blocked by the mask we inherited from the parent thread. 306 for (uptr i = 0; i < ARRAY_SIZE(kSyncSignals); i++) { 307 __sanitizer_sigaction act; 308 internal_memset(&act, 0, sizeof(act)); 309 act.sigaction = TracerThreadSignalHandler; 310 act.sa_flags = SA_ONSTACK | SA_SIGINFO; 311 internal_sigaction_norestorer(kSyncSignals[i], &act, 0); 312 } 313 314 int exit_code = 0; 315 if (!thread_suspender.SuspendAllThreads()) { 316 VReport(1, "Failed suspending threads.\n"); 317 exit_code = 3; 318 } else { 319 tracer_thread_argument->callback(thread_suspender.suspended_threads_list(), 320 tracer_thread_argument->callback_argument); 321 thread_suspender.ResumeAllThreads(); 322 exit_code = 0; 323 } 324 RAW_CHECK(RemoveDieCallback(TracerThreadDieCallback)); 325 thread_suspender_instance = nullptr; 326 atomic_store(&tracer_thread_argument->done, 1, memory_order_relaxed); 327 return exit_code; 328 } 329 330 class ScopedStackSpaceWithGuard { 331 public: 332 explicit ScopedStackSpaceWithGuard(uptr stack_size) { 333 stack_size_ = stack_size; 334 guard_size_ = GetPageSizeCached(); 335 // FIXME: Omitting MAP_STACK here works in current kernels but might break 336 // in the future. 337 guard_start_ = (uptr)MmapOrDie(stack_size_ + guard_size_, 338 "ScopedStackWithGuard"); 339 CHECK(MprotectNoAccess((uptr)guard_start_, guard_size_)); 340 } 341 ~ScopedStackSpaceWithGuard() { 342 UnmapOrDie((void *)guard_start_, stack_size_ + guard_size_); 343 } 344 void *Bottom() const { 345 return (void *)(guard_start_ + stack_size_ + guard_size_); 346 } 347 348 private: 349 uptr stack_size_; 350 uptr guard_size_; 351 uptr guard_start_; 352 }; 353 354 // We have a limitation on the stack frame size, so some stuff had to be moved 355 // into globals. 356 static __sanitizer_sigset_t blocked_sigset; 357 static __sanitizer_sigset_t old_sigset; 358 359 class StopTheWorldScope { 360 public: 361 StopTheWorldScope() { 362 // Make this process dumpable. Processes that are not dumpable cannot be 363 // attached to. 364 process_was_dumpable_ = internal_prctl(PR_GET_DUMPABLE, 0, 0, 0, 0); 365 if (!process_was_dumpable_) 366 internal_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); 367 } 368 369 ~StopTheWorldScope() { 370 // Restore the dumpable flag. 371 if (!process_was_dumpable_) 372 internal_prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); 373 } 374 375 private: 376 int process_was_dumpable_; 377 }; 378 379 // When sanitizer output is being redirected to file (i.e. by using log_path), 380 // the tracer should write to the parent's log instead of trying to open a new 381 // file. Alert the logging code to the fact that we have a tracer. 382 struct ScopedSetTracerPID { 383 explicit ScopedSetTracerPID(uptr tracer_pid) { 384 stoptheworld_tracer_pid = tracer_pid; 385 stoptheworld_tracer_ppid = internal_getpid(); 386 } 387 ~ScopedSetTracerPID() { 388 stoptheworld_tracer_pid = 0; 389 stoptheworld_tracer_ppid = 0; 390 } 391 }; 392 393 void StopTheWorld(StopTheWorldCallback callback, void *argument) { 394 StopTheWorldScope in_stoptheworld; 395 // Prepare the arguments for TracerThread. 396 struct TracerThreadArgument tracer_thread_argument; 397 tracer_thread_argument.callback = callback; 398 tracer_thread_argument.callback_argument = argument; 399 tracer_thread_argument.parent_pid = internal_getpid(); 400 atomic_store(&tracer_thread_argument.done, 0, memory_order_relaxed); 401 const uptr kTracerStackSize = 2 * 1024 * 1024; 402 ScopedStackSpaceWithGuard tracer_stack(kTracerStackSize); 403 // Block the execution of TracerThread until after we have set ptrace 404 // permissions. 405 tracer_thread_argument.mutex.Lock(); 406 // Signal handling story. 407 // We don't want async signals to be delivered to the tracer thread, 408 // so we block all async signals before creating the thread. An async signal 409 // handler can temporary modify errno, which is shared with this thread. 410 // We ought to use pthread_sigmask here, because sigprocmask has undefined 411 // behavior in multithreaded programs. However, on linux sigprocmask is 412 // equivalent to pthread_sigmask with the exception that pthread_sigmask 413 // does not allow to block some signals used internally in pthread 414 // implementation. We are fine with blocking them here, we are really not 415 // going to pthread_cancel the thread. 416 // The tracer thread should not raise any synchronous signals. But in case it 417 // does, we setup a special handler for sync signals that properly kills the 418 // parent as well. Note: we don't pass CLONE_SIGHAND to clone, so handlers 419 // in the tracer thread won't interfere with user program. Double note: if a 420 // user does something along the lines of 'kill -11 pid', that can kill the 421 // process even if user setup own handler for SEGV. 422 // Thing to watch out for: this code should not change behavior of user code 423 // in any observable way. In particular it should not override user signal 424 // handlers. 425 internal_sigfillset(&blocked_sigset); 426 for (uptr i = 0; i < ARRAY_SIZE(kSyncSignals); i++) 427 internal_sigdelset(&blocked_sigset, kSyncSignals[i]); 428 int rv = internal_sigprocmask(SIG_BLOCK, &blocked_sigset, &old_sigset); 429 CHECK_EQ(rv, 0); 430 uptr tracer_pid = internal_clone( 431 TracerThread, tracer_stack.Bottom(), 432 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_UNTRACED, 433 &tracer_thread_argument, nullptr /* parent_tidptr */, 434 nullptr /* newtls */, nullptr /* child_tidptr */); 435 internal_sigprocmask(SIG_SETMASK, &old_sigset, 0); 436 int local_errno = 0; 437 if (internal_iserror(tracer_pid, &local_errno)) { 438 VReport(1, "Failed spawning a tracer thread (errno %d).\n", local_errno); 439 tracer_thread_argument.mutex.Unlock(); 440 } else { 441 ScopedSetTracerPID scoped_set_tracer_pid(tracer_pid); 442 // On some systems we have to explicitly declare that we want to be traced 443 // by the tracer thread. 444 internal_prctl(PR_SET_PTRACER, tracer_pid, 0, 0, 0); 445 // Allow the tracer thread to start. 446 tracer_thread_argument.mutex.Unlock(); 447 // NOTE: errno is shared between this thread and the tracer thread. 448 // internal_waitpid() may call syscall() which can access/spoil errno, 449 // so we can't call it now. Instead we for the tracer thread to finish using 450 // the spin loop below. Man page for sched_yield() says "In the Linux 451 // implementation, sched_yield() always succeeds", so let's hope it does not 452 // spoil errno. Note that this spin loop runs only for brief periods before 453 // the tracer thread has suspended us and when it starts unblocking threads. 454 while (atomic_load(&tracer_thread_argument.done, memory_order_relaxed) == 0) 455 sched_yield(); 456 // Now the tracer thread is about to exit and does not touch errno, 457 // wait for it. 458 for (;;) { 459 uptr waitpid_status = internal_waitpid(tracer_pid, nullptr, __WALL); 460 if (!internal_iserror(waitpid_status, &local_errno)) 461 break; 462 if (local_errno == EINTR) 463 continue; 464 VReport(1, "Waiting on the tracer thread failed (errno %d).\n", 465 local_errno); 466 break; 467 } 468 } 469 } 470 471 // Platform-specific methods from SuspendedThreadsList. 472 #if SANITIZER_ANDROID && defined(__arm__) 473 typedef pt_regs regs_struct; 474 #define REG_SP ARM_sp 475 476 #elif SANITIZER_LINUX && defined(__arm__) 477 typedef user_regs regs_struct; 478 #define REG_SP uregs[13] 479 480 #elif defined(__i386__) || defined(__x86_64__) 481 typedef user_regs_struct regs_struct; 482 #if defined(__i386__) 483 #define REG_SP esp 484 #else 485 #define REG_SP rsp 486 #endif 487 488 #elif defined(__powerpc__) || defined(__powerpc64__) 489 typedef pt_regs regs_struct; 490 #define REG_SP gpr[PT_R1] 491 492 #elif defined(__mips__) 493 typedef struct user regs_struct; 494 # if SANITIZER_ANDROID 495 # define REG_SP regs[EF_R29] 496 # else 497 # define REG_SP regs[EF_REG29] 498 # endif 499 500 #elif defined(__aarch64__) 501 typedef struct user_pt_regs regs_struct; 502 #define REG_SP sp 503 #define ARCH_IOVEC_FOR_GETREGSET 504 505 #elif defined(__s390__) 506 typedef _user_regs_struct regs_struct; 507 #define REG_SP gprs[15] 508 #define ARCH_IOVEC_FOR_GETREGSET 509 510 #else 511 #error "Unsupported architecture" 512 #endif // SANITIZER_ANDROID && defined(__arm__) 513 514 tid_t SuspendedThreadsListLinux::GetThreadID(uptr index) const { 515 CHECK_LT(index, thread_ids_.size()); 516 return thread_ids_[index]; 517 } 518 519 uptr SuspendedThreadsListLinux::ThreadCount() const { 520 return thread_ids_.size(); 521 } 522 523 bool SuspendedThreadsListLinux::ContainsTid(tid_t thread_id) const { 524 for (uptr i = 0; i < thread_ids_.size(); i++) { 525 if (thread_ids_[i] == thread_id) return true; 526 } 527 return false; 528 } 529 530 void SuspendedThreadsListLinux::Append(tid_t tid) { 531 thread_ids_.push_back(tid); 532 } 533 534 PtraceRegistersStatus SuspendedThreadsListLinux::GetRegistersAndSP( 535 uptr index, uptr *buffer, uptr *sp) const { 536 pid_t tid = GetThreadID(index); 537 regs_struct regs; 538 int pterrno; 539 #ifdef ARCH_IOVEC_FOR_GETREGSET 540 struct iovec regset_io; 541 regset_io.iov_base = ®s; 542 regset_io.iov_len = sizeof(regs_struct); 543 bool isErr = internal_iserror(internal_ptrace(PTRACE_GETREGSET, tid, 544 (void*)NT_PRSTATUS, (void*)®set_io), 545 &pterrno); 546 #else 547 bool isErr = internal_iserror(internal_ptrace(PTRACE_GETREGS, tid, nullptr, 548 ®s), &pterrno); 549 #endif 550 if (isErr) { 551 VReport(1, "Could not get registers from thread %d (errno %d).\n", tid, 552 pterrno); 553 // ESRCH means that the given thread is not suspended or already dead. 554 // Therefore it's unsafe to inspect its data (e.g. walk through stack) and 555 // we should notify caller about this. 556 return pterrno == ESRCH ? REGISTERS_UNAVAILABLE_FATAL 557 : REGISTERS_UNAVAILABLE; 558 } 559 560 *sp = regs.REG_SP; 561 internal_memcpy(buffer, ®s, sizeof(regs)); 562 return REGISTERS_AVAILABLE; 563 } 564 565 uptr SuspendedThreadsListLinux::RegisterCount() const { 566 return sizeof(regs_struct) / sizeof(uptr); 567 } 568 } // namespace __sanitizer 569 570 #endif // SANITIZER_LINUX && (defined(__x86_64__) || defined(__mips__) 571 // || defined(__aarch64__) || defined(__powerpc64__) 572 // || defined(__s390__) || defined(__i386__) || defined(__arm__) 573