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