[Sanitizer] Kill the remainders of platform defines in favor of SANITIZER_ defines
[blocksruntime.git] / lib / sanitizer_common / sanitizer_stoptheworld_linux.cc
blob1731913e043e92c18fe635ca2cd93ae576b60911
1 //===-- sanitizer_stoptheworld_linux.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.
13 //===----------------------------------------------------------------------===//
16 #include "sanitizer_platform.h"
17 #if SANITIZER_LINUX
19 #include "sanitizer_stoptheworld.h"
21 #include <errno.h>
22 #include <sched.h> // for clone
23 #include <stddef.h>
24 #include <sys/prctl.h> // for PR_* definitions
25 #include <sys/ptrace.h> // for PTRACE_* definitions
26 #include <sys/types.h> // for pid_t
27 #if defined(SANITIZER_ANDROID) && defined(__arm__)
28 # include <linux/user.h> // for pt_regs
29 #else
30 # include <sys/user.h> // for user_regs_struct
31 #endif
32 #include <sys/wait.h> // for signal-related stuff
34 #include "sanitizer_common.h"
35 #include "sanitizer_libc.h"
36 #include "sanitizer_linux.h"
37 #include "sanitizer_mutex.h"
38 #include "sanitizer_placement_new.h"
40 // This module works by spawning a Linux task which then attaches to every
41 // thread in the caller process with ptrace. This suspends the threads, and
42 // PTRACE_GETREGS can then be used to obtain their register state. The callback
43 // supplied to StopTheWorld() is run in the tracer task while the threads are
44 // suspended.
45 // The tracer task must be placed in a different thread group for ptrace to
46 // work, so it cannot be spawned as a pthread. Instead, we use the low-level
47 // clone() interface (we want to share the address space with the caller
48 // process, so we prefer clone() over fork()).
50 // We avoid the use of libc for two reasons:
51 // 1. calling a library function while threads are suspended could cause a
52 // deadlock, if one of the treads happens to be holding a libc lock;
53 // 2. it's generally not safe to call libc functions from the tracer task,
54 // because clone() does not set up a thread-local storage for it. Any
55 // thread-local variables used by libc will be shared between the tracer task
56 // and the thread which spawned it.
58 // We deal with this by replacing libc calls with calls to our own
59 // implementations defined in sanitizer_libc.h and sanitizer_linux.h. However,
60 // there are still some libc functions which are used here:
62 // * All of the system calls ultimately go through the libc syscall() function.
63 // We're operating under the assumption that syscall()'s implementation does
64 // not acquire any locks or use any thread-local data (except for the errno
65 // variable, which we handle separately).
67 // * We lack custom implementations of sigfillset() and sigaction(), so we use
68 // the libc versions instead. The same assumptions as above apply.
70 // * It is safe to call libc functions before the cloned thread is spawned or
71 // after it has exited. The following functions are used in this manner:
72 // sigdelset()
73 // sigprocmask()
74 // clone()
76 COMPILER_CHECK(sizeof(SuspendedThreadID) == sizeof(pid_t));
78 namespace __sanitizer {
79 // This class handles thread suspending/unsuspending in the tracer thread.
80 class ThreadSuspender {
81 public:
82 explicit ThreadSuspender(pid_t pid)
83 : pid_(pid) {
84 CHECK_GE(pid, 0);
86 bool SuspendAllThreads();
87 void ResumeAllThreads();
88 void KillAllThreads();
89 SuspendedThreadsList &suspended_threads_list() {
90 return suspended_threads_list_;
92 private:
93 SuspendedThreadsList suspended_threads_list_;
94 pid_t pid_;
95 bool SuspendThread(SuspendedThreadID thread_id);
98 bool ThreadSuspender::SuspendThread(SuspendedThreadID thread_id) {
99 // Are we already attached to this thread?
100 // Currently this check takes linear time, however the number of threads is
101 // usually small.
102 if (suspended_threads_list_.Contains(thread_id))
103 return false;
104 if (internal_ptrace(PTRACE_ATTACH, thread_id, NULL, NULL) != 0) {
105 // Either the thread is dead, or something prevented us from attaching.
106 // Log this event and move on.
107 Report("Could not attach to thread %d (errno %d).\n", thread_id, errno);
108 return false;
109 } else {
110 if (SanitizerVerbosity > 0)
111 Report("Attached to thread %d.\n", thread_id);
112 // The thread is not guaranteed to stop before ptrace returns, so we must
113 // wait on it.
114 int waitpid_status;
115 HANDLE_EINTR(waitpid_status, internal_waitpid(thread_id, NULL, __WALL));
116 if (waitpid_status < 0) {
117 // Got a ECHILD error. I don't think this situation is possible, but it
118 // doesn't hurt to report it.
119 Report("Waiting on thread %d failed, detaching (errno %d).\n", thread_id,
120 errno);
121 internal_ptrace(PTRACE_DETACH, thread_id, NULL, NULL);
122 return false;
124 suspended_threads_list_.Append(thread_id);
125 return true;
129 void ThreadSuspender::ResumeAllThreads() {
130 for (uptr i = 0; i < suspended_threads_list_.thread_count(); i++) {
131 pid_t tid = suspended_threads_list_.GetThreadID(i);
132 if (internal_ptrace(PTRACE_DETACH, tid, NULL, NULL) == 0) {
133 if (SanitizerVerbosity > 0)
134 Report("Detached from thread %d.\n", tid);
135 } else {
136 // Either the thread is dead, or we are already detached.
137 // The latter case is possible, for instance, if this function was called
138 // from a signal handler.
139 Report("Could not detach from thread %d (errno %d).\n", tid, errno);
144 void ThreadSuspender::KillAllThreads() {
145 for (uptr i = 0; i < suspended_threads_list_.thread_count(); i++)
146 internal_ptrace(PTRACE_KILL, suspended_threads_list_.GetThreadID(i),
147 NULL, NULL);
150 bool ThreadSuspender::SuspendAllThreads() {
151 void *mem = InternalAlloc(sizeof(ThreadLister));
152 ThreadLister *thread_lister = new(mem) ThreadLister(pid_);
153 bool added_threads;
154 do {
155 // Run through the directory entries once.
156 added_threads = false;
157 pid_t tid = thread_lister->GetNextTID();
158 while (tid >= 0) {
159 if (SuspendThread(tid))
160 added_threads = true;
161 tid = thread_lister->GetNextTID();
163 if (thread_lister->error()) {
164 // Detach threads and fail.
165 ResumeAllThreads();
166 InternalFree(mem);
167 return false;
169 thread_lister->Reset();
170 } while (added_threads);
171 InternalFree(mem);
172 return true;
175 // Pointer to the ThreadSuspender instance for use in signal handler.
176 static ThreadSuspender *thread_suspender_instance = NULL;
178 // Signals that should not be blocked (this is used in the parent thread as well
179 // as the tracer thread).
180 static const int kUnblockedSignals[] = { SIGABRT, SIGILL, SIGFPE, SIGSEGV,
181 SIGBUS, SIGXCPU, SIGXFSZ };
183 // Structure for passing arguments into the tracer thread.
184 struct TracerThreadArgument {
185 StopTheWorldCallback callback;
186 void *callback_argument;
187 // The tracer thread waits on this mutex while the parent finished its
188 // preparations.
189 BlockingMutex mutex;
192 // Signal handler to wake up suspended threads when the tracer thread dies.
193 void TracerThreadSignalHandler(int signum, siginfo_t *siginfo, void *) {
194 if (thread_suspender_instance != NULL) {
195 if (signum == SIGABRT)
196 thread_suspender_instance->KillAllThreads();
197 else
198 thread_suspender_instance->ResumeAllThreads();
200 internal__exit((signum == SIGABRT) ? 1 : 2);
203 // Size of alternative stack for signal handlers in the tracer thread.
204 static const int kHandlerStackSize = 4096;
206 // This function will be run as a cloned task.
207 static int TracerThread(void* argument) {
208 TracerThreadArgument *tracer_thread_argument =
209 (TracerThreadArgument *)argument;
211 // Wait for the parent thread to finish preparations.
212 tracer_thread_argument->mutex.Lock();
213 tracer_thread_argument->mutex.Unlock();
215 ThreadSuspender thread_suspender(internal_getppid());
216 // Global pointer for the signal handler.
217 thread_suspender_instance = &thread_suspender;
219 // Alternate stack for signal handling.
220 InternalScopedBuffer<char> handler_stack_memory(kHandlerStackSize);
221 struct sigaltstack handler_stack;
222 internal_memset(&handler_stack, 0, sizeof(handler_stack));
223 handler_stack.ss_sp = handler_stack_memory.data();
224 handler_stack.ss_size = kHandlerStackSize;
225 internal_sigaltstack(&handler_stack, NULL);
227 // Install our handler for fatal signals. Other signals should be blocked by
228 // the mask we inherited from the caller thread.
229 for (uptr signal_index = 0; signal_index < ARRAY_SIZE(kUnblockedSignals);
230 signal_index++) {
231 struct sigaction new_sigaction;
232 internal_memset(&new_sigaction, 0, sizeof(new_sigaction));
233 new_sigaction.sa_sigaction = TracerThreadSignalHandler;
234 new_sigaction.sa_flags = SA_ONSTACK | SA_SIGINFO;
235 sigfillset(&new_sigaction.sa_mask);
236 sigaction(kUnblockedSignals[signal_index], &new_sigaction, NULL);
239 int exit_code = 0;
240 if (!thread_suspender.SuspendAllThreads()) {
241 Report("Failed suspending threads.\n");
242 exit_code = 3;
243 } else {
244 tracer_thread_argument->callback(thread_suspender.suspended_threads_list(),
245 tracer_thread_argument->callback_argument);
246 thread_suspender.ResumeAllThreads();
247 exit_code = 0;
249 thread_suspender_instance = NULL;
250 handler_stack.ss_flags = SS_DISABLE;
251 internal_sigaltstack(&handler_stack, NULL);
252 return exit_code;
255 class ScopedStackSpaceWithGuard {
256 public:
257 explicit ScopedStackSpaceWithGuard(uptr stack_size) {
258 stack_size_ = stack_size;
259 guard_size_ = GetPageSizeCached();
260 // FIXME: Omitting MAP_STACK here works in current kernels but might break
261 // in the future.
262 guard_start_ = (uptr)MmapOrDie(stack_size_ + guard_size_,
263 "ScopedStackWithGuard");
264 CHECK_EQ(guard_start_, (uptr)Mprotect((uptr)guard_start_, guard_size_));
266 ~ScopedStackSpaceWithGuard() {
267 UnmapOrDie((void *)guard_start_, stack_size_ + guard_size_);
269 void *Bottom() const {
270 return (void *)(guard_start_ + stack_size_ + guard_size_);
273 private:
274 uptr stack_size_;
275 uptr guard_size_;
276 uptr guard_start_;
279 static sigset_t blocked_sigset;
280 static sigset_t old_sigset;
281 static struct sigaction old_sigactions[ARRAY_SIZE(kUnblockedSignals)];
283 void StopTheWorld(StopTheWorldCallback callback, void *argument) {
284 // Block all signals that can be blocked safely, and install default handlers
285 // for the remaining signals.
286 // We cannot allow user-defined handlers to run while the ThreadSuspender
287 // thread is active, because they could conceivably call some libc functions
288 // which modify errno (which is shared between the two threads).
289 sigfillset(&blocked_sigset);
290 for (uptr signal_index = 0; signal_index < ARRAY_SIZE(kUnblockedSignals);
291 signal_index++) {
292 // Remove the signal from the set of blocked signals.
293 sigdelset(&blocked_sigset, kUnblockedSignals[signal_index]);
294 // Install the default handler.
295 struct sigaction new_sigaction;
296 internal_memset(&new_sigaction, 0, sizeof(new_sigaction));
297 new_sigaction.sa_handler = SIG_DFL;
298 sigfillset(&new_sigaction.sa_mask);
299 sigaction(kUnblockedSignals[signal_index], &new_sigaction,
300 &old_sigactions[signal_index]);
302 int sigprocmask_status = sigprocmask(SIG_BLOCK, &blocked_sigset, &old_sigset);
303 CHECK_EQ(sigprocmask_status, 0); // sigprocmask should never fail
304 // Make this process dumpable. Processes that are not dumpable cannot be
305 // attached to.
306 int process_was_dumpable = internal_prctl(PR_GET_DUMPABLE, 0, 0, 0, 0);
307 if (!process_was_dumpable)
308 internal_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
309 // Prepare the arguments for TracerThread.
310 struct TracerThreadArgument tracer_thread_argument;
311 tracer_thread_argument.callback = callback;
312 tracer_thread_argument.callback_argument = argument;
313 const uptr kTracerStackSize = 2 * 1024 * 1024;
314 ScopedStackSpaceWithGuard tracer_stack(kTracerStackSize);
315 // Block the execution of TracerThread until after we have set ptrace
316 // permissions.
317 tracer_thread_argument.mutex.Lock();
318 pid_t tracer_pid = clone(TracerThread, tracer_stack.Bottom(),
319 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_UNTRACED,
320 &tracer_thread_argument, 0, 0, 0);
321 if (tracer_pid < 0) {
322 Report("Failed spawning a tracer thread (errno %d).\n", errno);
323 tracer_thread_argument.mutex.Unlock();
324 } else {
325 // On some systems we have to explicitly declare that we want to be traced
326 // by the tracer thread.
327 #ifdef PR_SET_PTRACER
328 internal_prctl(PR_SET_PTRACER, tracer_pid, 0, 0, 0);
329 #endif
330 // Allow the tracer thread to start.
331 tracer_thread_argument.mutex.Unlock();
332 // Since errno is shared between this thread and the tracer thread, we
333 // must avoid using errno while the tracer thread is running.
334 // At this point, any signal will either be blocked or kill us, so waitpid
335 // should never return (and set errno) while the tracer thread is alive.
336 int waitpid_status = internal_waitpid(tracer_pid, NULL, __WALL);
337 if (waitpid_status < 0)
338 Report("Waiting on the tracer thread failed (errno %d).\n", errno);
340 // Restore the dumpable flag.
341 if (!process_was_dumpable)
342 internal_prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
343 // Restore the signal handlers.
344 for (uptr signal_index = 0; signal_index < ARRAY_SIZE(kUnblockedSignals);
345 signal_index++) {
346 sigaction(kUnblockedSignals[signal_index],
347 &old_sigactions[signal_index], NULL);
349 sigprocmask(SIG_SETMASK, &old_sigset, &old_sigset);
352 // Platform-specific methods from SuspendedThreadsList.
353 #if defined(SANITIZER_ANDROID) && defined(__arm__)
354 typedef pt_regs regs_struct;
355 #else
356 typedef user_regs_struct regs_struct;
357 #endif
359 int SuspendedThreadsList::GetRegistersAndSP(uptr index,
360 uptr *buffer,
361 uptr *sp) const {
362 pid_t tid = GetThreadID(index);
363 regs_struct regs;
364 if (internal_ptrace(PTRACE_GETREGS, tid, NULL, &regs) != 0) {
365 Report("Could not get registers from thread %d (errno %d).\n",
366 tid, errno);
367 return -1;
369 #if defined(__arm__)
370 *sp = regs.ARM_sp;
371 #elif SANITIZER_WORDSIZE == 32
372 *sp = regs.esp;
373 #else
374 *sp = regs.rsp;
375 #endif
376 internal_memcpy(buffer, &regs, sizeof(regs));
377 return 0;
380 uptr SuspendedThreadsList::RegisterCount() {
381 return sizeof(regs_struct) / sizeof(uptr);
383 } // namespace __sanitizer
385 #endif // SANITIZER_LINUX