• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 #include <errno.h>
18 #include <signal.h>
19 #include <string.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 
23 #include <memory>
24 #include <mutex>
25 #include <string>
26 #include <vector>
27 
28 #include <android-base/errno_restorer.h>
29 #include <android-base/threads.h>
30 
31 #include <unwindstack/Log.h>
32 #include <unwindstack/Regs.h>
33 #include <unwindstack/Unwinder.h>
34 
35 #include "ThreadEntry.h"
36 
37 namespace unwindstack {
38 
SignalLogOnly(int,siginfo_t *,void *)39 static void SignalLogOnly(int, siginfo_t*, void*) {
40   android::base::ErrnoRestorer restore;
41 
42   Log::AsyncSafe("pid %d, tid %d: Received a spurious thread signal\n", getpid(),
43                  static_cast<int>(android::base::GetThreadId()));
44 }
45 
SignalHandler(int,siginfo_t *,void * sigcontext)46 static void SignalHandler(int, siginfo_t*, void* sigcontext) {
47   android::base::ErrnoRestorer restore;
48 
49   ThreadEntry* entry = ThreadEntry::Get(android::base::GetThreadId(), false);
50   if (!entry) {
51     return;
52   }
53 
54   entry->CopyUcontextFromSigcontext(sigcontext);
55 
56   // Indicate the ucontext is now valid.
57   entry->Wake();
58   // Pause the thread until the unwind is complete. This avoids having
59   // the thread run ahead causing problems.
60   // The number indicates that we are waiting for the second Wake() call
61   // overall which is made by the thread requesting an unwind.
62   if (entry->Wait(WAIT_FOR_UNWIND_TO_COMPLETE)) {
63     // Do not remove the entry here because that can result in a deadlock
64     // if the code cannot properly send a signal to the thread under test.
65     entry->Wake();
66   } else {
67     // At this point, it is possible that entry has been freed, so just exit.
68     Log::AsyncSafe("Timed out waiting for unwind thread to indicate it completed.");
69   }
70 }
71 
ThreadUnwinder(size_t max_frames,Maps * maps)72 ThreadUnwinder::ThreadUnwinder(size_t max_frames, Maps* maps)
73     : UnwinderFromPid(max_frames, getpid(), Regs::CurrentArch(), maps) {}
74 
ThreadUnwinder(size_t max_frames,Maps * maps,std::shared_ptr<Memory> & process_memory)75 ThreadUnwinder::ThreadUnwinder(size_t max_frames, Maps* maps,
76                                std::shared_ptr<Memory>& process_memory)
77     : UnwinderFromPid(max_frames, getpid(), Regs::CurrentArch(), maps, process_memory) {}
78 
ThreadUnwinder(size_t max_frames,const ThreadUnwinder * unwinder)79 ThreadUnwinder::ThreadUnwinder(size_t max_frames, const ThreadUnwinder* unwinder)
80     : UnwinderFromPid(max_frames, getpid(), Regs::CurrentArch()) {
81   process_memory_ = unwinder->process_memory_;
82   maps_ = unwinder->maps_;
83   jit_debug_ = unwinder->jit_debug_;
84   dex_files_ = unwinder->dex_files_;
85   initted_ = unwinder->initted_;
86 }
87 
SendSignalToThread(int signal,pid_t tid)88 ThreadEntry* ThreadUnwinder::SendSignalToThread(int signal, pid_t tid) {
89   static std::mutex action_mutex;
90   std::lock_guard<std::mutex> guard(action_mutex);
91 
92   ThreadEntry* entry = ThreadEntry::Get(tid);
93   entry->Lock();
94   struct sigaction new_action = {.sa_sigaction = SignalHandler,
95                                  .sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK};
96   struct sigaction old_action = {};
97   sigemptyset(&new_action.sa_mask);
98   if (sigaction(signal, &new_action, &old_action) != 0) {
99     Log::AsyncSafe("sigaction failed: %s", strerror(errno));
100     ThreadEntry::Remove(entry);
101     last_error_.code = ERROR_SYSTEM_CALL;
102     return nullptr;
103   }
104 
105   if (tgkill(getpid(), tid, signal) != 0) {
106     // Do not emit an error message, this might be expected. Set the
107     // error and let the caller decide.
108     if (errno == ESRCH) {
109       last_error_.code = ERROR_THREAD_DOES_NOT_EXIST;
110     } else {
111       last_error_.code = ERROR_SYSTEM_CALL;
112     }
113 
114     sigaction(signal, &old_action, nullptr);
115     ThreadEntry::Remove(entry);
116     return nullptr;
117   }
118 
119   // Wait for the thread to get the ucontext. The number indicates
120   // that we are waiting for the first Wake() call made by the thread.
121   bool wait_completed = entry->Wait(WAIT_FOR_UCONTEXT);
122   if (wait_completed) {
123     return entry;
124   }
125 
126   if (old_action.sa_sigaction == nullptr) {
127     // If the wait failed, it could be that the signal could not be delivered
128     // within the timeout. Add a signal handler that's simply going to log
129     // something so that we don't crash if the signal eventually gets
130     // delivered. Only do this if there isn't already an action set up.
131     struct sigaction log_action = {.sa_sigaction = SignalLogOnly,
132                                    .sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK};
133     sigemptyset(&log_action.sa_mask);
134     sigaction(signal, &log_action, nullptr);
135   } else {
136     sigaction(signal, &old_action, nullptr);
137   }
138 
139   // Check to see if the thread has disappeared.
140   if (tgkill(getpid(), tid, 0) == -1 && errno == ESRCH) {
141     last_error_.code = ERROR_THREAD_DOES_NOT_EXIST;
142   } else {
143     last_error_.code = ERROR_THREAD_TIMEOUT;
144     Log::AsyncSafe("Timed out waiting for signal handler to get ucontext data.");
145   }
146 
147   ThreadEntry::Remove(entry);
148 
149   return nullptr;
150 }
151 
UnwindWithSignal(int signal,pid_t tid,std::unique_ptr<Regs> * initial_regs,const std::vector<std::string> * initial_map_names_to_skip,const std::vector<std::string> * map_suffixes_to_ignore)152 void ThreadUnwinder::UnwindWithSignal(int signal, pid_t tid, std::unique_ptr<Regs>* initial_regs,
153                                       const std::vector<std::string>* initial_map_names_to_skip,
154                                       const std::vector<std::string>* map_suffixes_to_ignore) {
155   ClearErrors();
156   if (tid == static_cast<pid_t>(android::base::GetThreadId())) {
157     last_error_.code = ERROR_UNSUPPORTED;
158     return;
159   }
160 
161   if (!Init()) {
162     return;
163   }
164 
165   ThreadEntry* entry = SendSignalToThread(signal, tid);
166   if (entry == nullptr) {
167     return;
168   }
169 
170   std::unique_ptr<Regs> regs(Regs::CreateFromUcontext(Regs::CurrentArch(), entry->GetUcontext()));
171   if (initial_regs != nullptr) {
172     initial_regs->reset(regs->Clone());
173   }
174   SetRegs(regs.get());
175   UnwinderFromPid::Unwind(initial_map_names_to_skip, map_suffixes_to_ignore);
176 
177   // Tell the signal handler to exit and release the entry.
178   entry->Wake();
179 
180   // Wait for the thread to indicate it is done with the ThreadEntry.
181   if (!entry->Wait(WAIT_FOR_THREAD_TO_RESTART)) {
182     // Send a warning, but do not mark as a failure to unwind.
183     Log::AsyncSafe("Timed out waiting for signal handler to indicate it finished.");
184   }
185 
186   ThreadEntry::Remove(entry);
187 }
188 
189 }  // namespace unwindstack
190