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