1 /*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define _GNU_SOURCE 1
18 #include <errno.h>
19 #include <stdint.h>
20 #include <string.h>
21 #include <sys/param.h>
22 #include <sys/ptrace.h>
23 #include <sys/types.h>
24 #include <ucontext.h>
25 #include <unistd.h>
26
27 #include <stdlib.h>
28
29 #include <string>
30
31 #include <android-base/threads.h>
32 #include <backtrace/Backtrace.h>
33 #include <backtrace/BacktraceMap.h>
34
35 #include "BacktraceAsyncSafeLog.h"
36 #include "BacktraceCurrent.h"
37 #include "ThreadEntry.h"
38
ReadWord(uint64_t ptr,word_t * out_value)39 bool BacktraceCurrent::ReadWord(uint64_t ptr, word_t* out_value) {
40 #if defined(__aarch64__)
41 // Tagged pointer after Android R would lead top byte to have random values
42 // https://source.android.com/devices/tech/debug/tagged-pointers
43 ptr &= (1ULL << 56) - 1;
44 #endif
45
46 if (!VerifyReadWordArgs(ptr, out_value)) {
47 return false;
48 }
49
50 backtrace_map_t map;
51 FillInMap(ptr, &map);
52 if (BacktraceMap::IsValid(map) && map.flags & PROT_READ) {
53 *out_value = *reinterpret_cast<word_t*>(ptr);
54 return true;
55 } else {
56 BACK_ASYNC_SAFE_LOGW("pointer %p not in a readable map", reinterpret_cast<void*>(ptr));
57 *out_value = static_cast<word_t>(-1);
58 return false;
59 }
60 }
61
Read(uint64_t addr,uint8_t * buffer,size_t bytes)62 size_t BacktraceCurrent::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
63 #if defined(__aarch64__)
64 // Tagged pointer after Android R would lead top byte to have random values
65 // https://source.android.com/devices/tech/debug/tagged-pointers
66 addr &= (1ULL << 56) - 1;
67 #endif
68
69 backtrace_map_t map;
70 FillInMap(addr, &map);
71 if (!BacktraceMap::IsValid(map) || !(map.flags & PROT_READ)) {
72 return 0;
73 }
74 bytes = MIN(map.end - addr, bytes);
75 memcpy(buffer, reinterpret_cast<uint8_t*>(addr), bytes);
76 return bytes;
77 }
78
Unwind(size_t num_ignore_frames,void * ucontext)79 bool BacktraceCurrent::Unwind(size_t num_ignore_frames, void* ucontext) {
80 if (GetMap() == nullptr) {
81 // Without a map object, we can't do anything.
82 error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
83 return false;
84 }
85
86 error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
87 if (ucontext) {
88 return UnwindFromContext(num_ignore_frames, ucontext);
89 }
90
91 if (Tid() != static_cast<pid_t>(android::base::GetThreadId())) {
92 return UnwindThread(num_ignore_frames);
93 }
94
95 return UnwindFromContext(num_ignore_frames, nullptr);
96 }
97
DiscardFrame(const backtrace_frame_data_t & frame)98 bool BacktraceCurrent::DiscardFrame(const backtrace_frame_data_t& frame) {
99 if (BacktraceMap::IsValid(frame.map)) {
100 const std::string library = basename(frame.map.name.c_str());
101 if (library == "libunwind.so" || library == "libbacktrace.so") {
102 return true;
103 }
104 }
105 return false;
106 }
107
108 static pthread_mutex_t g_sigaction_mutex = PTHREAD_MUTEX_INITIALIZER;
109
110 // Since errno is stored per thread, changing it in the signal handler
111 // modifies the value on the thread in which the signal handler executes.
112 // If a signal occurs between a call and an errno check, it's possible
113 // to get the errno set here. Always save and restore it just in case
114 // code would modify it.
115 class ErrnoRestorer {
116 public:
ErrnoRestorer()117 ErrnoRestorer() : saved_errno_(errno) {}
~ErrnoRestorer()118 ~ErrnoRestorer() {
119 errno = saved_errno_;
120 }
121
122 private:
123 int saved_errno_;
124 };
125
SignalLogOnly(int,siginfo_t *,void *)126 static void SignalLogOnly(int, siginfo_t*, void*) {
127 ErrnoRestorer restore;
128
129 BACK_ASYNC_SAFE_LOGE("pid %d, tid %d: Received a spurious signal %d\n", getpid(),
130 static_cast<int>(android::base::GetThreadId()), THREAD_SIGNAL);
131 }
132
SignalHandler(int,siginfo_t *,void * sigcontext)133 static void SignalHandler(int, siginfo_t*, void* sigcontext) {
134 ErrnoRestorer restore;
135
136 ThreadEntry* entry = ThreadEntry::Get(getpid(), android::base::GetThreadId(), false);
137 if (!entry) {
138 BACK_ASYNC_SAFE_LOGE("pid %d, tid %d entry not found", getpid(),
139 static_cast<int>(android::base::GetThreadId()));
140 return;
141 }
142
143 entry->CopyUcontextFromSigcontext(sigcontext);
144
145 // Indicate the ucontext is now valid.
146 entry->Wake();
147
148 // Pause the thread until the unwind is complete. This avoids having
149 // the thread run ahead causing problems.
150 // The number indicates that we are waiting for the second Wake() call
151 // overall which is made by the thread requesting an unwind.
152 if (entry->Wait(2)) {
153 // Do not remove the entry here because that can result in a deadlock
154 // if the code cannot properly send a signal to the thread under test.
155 entry->Wake();
156 } else {
157 // At this point, it is possible that entry has been freed, so just exit.
158 BACK_ASYNC_SAFE_LOGE("Timed out waiting for unwind thread to indicate it completed.");
159 }
160 }
161
UnwindThread(size_t num_ignore_frames)162 bool BacktraceCurrent::UnwindThread(size_t num_ignore_frames) {
163 // Prevent multiple threads trying to set the trigger action on different
164 // threads at the same time.
165 pthread_mutex_lock(&g_sigaction_mutex);
166
167 ThreadEntry* entry = ThreadEntry::Get(Pid(), Tid());
168 entry->Lock();
169
170 struct sigaction act, oldact;
171 memset(&act, 0, sizeof(act));
172 act.sa_sigaction = SignalHandler;
173 act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
174 sigemptyset(&act.sa_mask);
175 if (sigaction(THREAD_SIGNAL, &act, &oldact) != 0) {
176 BACK_ASYNC_SAFE_LOGE("sigaction failed: %s", strerror(errno));
177 ThreadEntry::Remove(entry);
178 pthread_mutex_unlock(&g_sigaction_mutex);
179 error_.error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
180 return false;
181 }
182
183 if (tgkill(Pid(), Tid(), THREAD_SIGNAL) != 0) {
184 // Do not emit an error message, this might be expected. Set the
185 // error and let the caller decide.
186 if (errno == ESRCH) {
187 error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
188 } else {
189 error_.error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
190 }
191
192 sigaction(THREAD_SIGNAL, &oldact, nullptr);
193 ThreadEntry::Remove(entry);
194 pthread_mutex_unlock(&g_sigaction_mutex);
195 return false;
196 }
197
198 // Wait for the thread to get the ucontext. The number indicates
199 // that we are waiting for the first Wake() call made by the thread.
200 bool wait_completed = entry->Wait(1);
201
202 if (!wait_completed && oldact.sa_sigaction == nullptr) {
203 // If the wait failed, it could be that the signal could not be delivered
204 // within the timeout. Add a signal handler that's simply going to log
205 // something so that we don't crash if the signal eventually gets
206 // delivered. Only do this if there isn't already an action set up.
207 memset(&act, 0, sizeof(act));
208 act.sa_sigaction = SignalLogOnly;
209 act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
210 sigemptyset(&act.sa_mask);
211 sigaction(THREAD_SIGNAL, &act, nullptr);
212 } else {
213 sigaction(THREAD_SIGNAL, &oldact, nullptr);
214 }
215 // After the thread has received the signal, allow other unwinders to
216 // continue.
217 pthread_mutex_unlock(&g_sigaction_mutex);
218
219 bool unwind_done = false;
220 if (wait_completed) {
221 unwind_done = UnwindFromContext(num_ignore_frames, entry->GetUcontext());
222
223 // Tell the signal handler to exit and release the entry.
224 entry->Wake();
225
226 // Wait for the thread to indicate it is done with the ThreadEntry.
227 if (!entry->Wait(3)) {
228 // Send a warning, but do not mark as a failure to unwind.
229 BACK_ASYNC_SAFE_LOGW("Timed out waiting for signal handler to indicate it finished.");
230 }
231 } else {
232 // Check to see if the thread has disappeared.
233 if (tgkill(Pid(), Tid(), 0) == -1 && errno == ESRCH) {
234 error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
235 } else {
236 error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT;
237 BACK_ASYNC_SAFE_LOGE("Timed out waiting for signal handler to get ucontext data.");
238 }
239 }
240
241 ThreadEntry::Remove(entry);
242
243 return unwind_done;
244 }
245