blob: 3891f2d3d90a58e76c66edc243d640242abf269f [file] [log] [blame]
Colin Crossbcb4ed32016-01-14 15:35:40 -08001/*
2 * Copyright (C) 2016 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 "ThreadCapture.h"
18
19#include <elf.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <limits.h>
23#include <stdlib.h>
24#include <unistd.h>
25#include <sys/ptrace.h>
26#include <sys/stat.h>
27#include <sys/syscall.h>
28#include <sys/types.h>
29#include <sys/uio.h>
30#include <sys/wait.h>
31
32#include <map>
33#include <memory>
34#include <set>
35#include <vector>
36
37#include <android-base/unique_fd.h>
38
39#include "Allocator.h"
40#include "log.h"
41
42// bionic interfaces used:
43// atoi
44// strlcat
45// writev
46
47// bionic interfaces reimplemented to avoid allocation:
48// getdents64
49
50// Convert a pid > 0 to a string. sprintf might allocate, so we can't use it.
51// Returns a pointer somewhere in buf to a null terminated string, or NULL
52// on error.
53static char *pid_to_str(char *buf, size_t len, pid_t pid) {
54 if (pid <= 0) {
55 return nullptr;
56 }
57
58 char *ptr = buf + len - 1;
59 *ptr = 0;
60 while (pid > 0) {
61 ptr--;
62 if (ptr < buf) {
63 return nullptr;
64 }
65 *ptr = '0' + (pid % 10);
66 pid /= 10;
67 }
68
69 return ptr;
70}
71
72class ThreadCaptureImpl {
73 public:
74 ThreadCaptureImpl(pid_t pid, Allocator<ThreadCaptureImpl>& allocator);
75 ~ThreadCaptureImpl() {}
76 bool ListThreads(TidList& tids);
77 bool CaptureThreads();
78 bool ReleaseThreads();
79 bool ReleaseThread(pid_t tid);
80 bool CapturedThreadInfo(ThreadInfoList& threads);
81 void InjectTestFunc(std::function<void(pid_t)>&& f) { inject_test_func_ = f; }
82 private:
83 int CaptureThread(pid_t tid);
84 bool ReleaseThread(pid_t tid, unsigned int signal);
85 int PtraceAttach(pid_t tid);
86 void PtraceDetach(pid_t tid, unsigned int signal);
87 bool PtraceThreadInfo(pid_t tid, ThreadInfo& thread_info);
88
Colin Crosse4cbe0e2016-03-04 16:34:42 -080089 allocator::map<pid_t, unsigned int> captured_threads_;
Colin Crossbcb4ed32016-01-14 15:35:40 -080090 Allocator<ThreadCaptureImpl> allocator_;
91 pid_t pid_;
92 std::function<void(pid_t)> inject_test_func_;
93};
94
95ThreadCaptureImpl::ThreadCaptureImpl(pid_t pid, Allocator<ThreadCaptureImpl>& allocator) :
96 captured_threads_(allocator), allocator_(allocator), pid_(pid) {
97}
98
99bool ThreadCaptureImpl::ListThreads(TidList& tids) {
100 tids.clear();
101
102 char pid_buf[11];
103 char path[256] = "/proc/";
104 char* pid_str = pid_to_str(pid_buf, sizeof(pid_buf), pid_);
105 if (!pid_str) {
106 return false;
107 }
108 strlcat(path, pid_str, sizeof(path));
109 strlcat(path, "/task", sizeof(path));
110
Elliott Hughes2c5d1d72016-03-28 12:15:36 -0700111 android::base::unique_fd fd(open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
112 if (fd == -1) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700113 MEM_ALOGE("failed to open %s: %s", path, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800114 return false;
115 }
Colin Crossbcb4ed32016-01-14 15:35:40 -0800116
117 struct linux_dirent64 {
118 uint64_t d_ino;
119 int64_t d_off;
120 uint16_t d_reclen;
121 char d_type;
122 char d_name[];
123 } __attribute((packed));
124 char dirent_buf[4096];
125 ssize_t nread;
126 do {
Elliott Hughes2c5d1d72016-03-28 12:15:36 -0700127 nread = syscall(SYS_getdents64, fd.get(), dirent_buf, sizeof(dirent_buf));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800128 if (nread < 0) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700129 MEM_ALOGE("failed to get directory entries from %s: %s", path, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800130 return false;
131 } else if (nread > 0) {
132 ssize_t off = 0;
133 while (off < nread) {
134 linux_dirent64* dirent = reinterpret_cast<linux_dirent64*>(dirent_buf + off);
135 off += dirent->d_reclen;
136 pid_t tid = atoi(dirent->d_name);
137 if (tid <= 0) {
138 continue;
139 }
140 tids.push_back(tid);
141 }
142 }
143
144 } while (nread != 0);
145
146 return true;
147}
148
149bool ThreadCaptureImpl::CaptureThreads() {
150 TidList tids{allocator_};
151
152 bool found_new_thread;
153 do {
154 if (!ListThreads(tids)) {
155 ReleaseThreads();
156 return false;
157 }
158
159 found_new_thread = false;
160
161 for (auto it = tids.begin(); it != tids.end(); it++) {
162 auto captured = captured_threads_.find(*it);
163 if (captured == captured_threads_.end()) {
164 if (CaptureThread(*it) < 0) {
165 ReleaseThreads();
166 return false;
167 }
168 found_new_thread = true;
169 }
170 }
171 } while (found_new_thread);
172
173 return true;
174}
175
176// Detatches from a thread, delivering signal if nonzero, logs on error
177void ThreadCaptureImpl::PtraceDetach(pid_t tid, unsigned int signal) {
178 void* sig_ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(signal));
179 if (ptrace(PTRACE_DETACH, tid, NULL, sig_ptr) < 0 && errno != ESRCH) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700180 MEM_ALOGE("failed to detach from thread %d of process %d: %s", tid, pid_, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800181 }
182}
183
184// Attaches to and pauses thread.
185// Returns 1 on attach, 0 on tid not found, -1 and logs on error
186int ThreadCaptureImpl::PtraceAttach(pid_t tid) {
187 int ret = ptrace(PTRACE_SEIZE, tid, NULL, NULL);
188 if (ret < 0) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700189 MEM_ALOGE("failed to attach to thread %d of process %d: %s", tid, pid_, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800190 return -1;
191 }
192
193 if (inject_test_func_) {
194 inject_test_func_(tid);
195 }
196
197 if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) < 0) {
198 if (errno == ESRCH) {
199 return 0;
200 } else {
Christopher Ferris47dea712017-05-03 17:34:29 -0700201 MEM_ALOGE("failed to interrupt thread %d of process %d: %s", tid, pid_, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800202 PtraceDetach(tid, 0);
203 return -1;
204 }
205 }
206 return 1;
207}
208
209bool ThreadCaptureImpl::PtraceThreadInfo(pid_t tid, ThreadInfo& thread_info) {
210 thread_info.tid = tid;
211
212 const unsigned int max_num_regs = 128; // larger than number of registers on any device
213 uintptr_t regs[max_num_regs];
214 struct iovec iovec;
215 iovec.iov_base = &regs;
216 iovec.iov_len = sizeof(regs);
217
218 if (ptrace(PTRACE_GETREGSET, tid, reinterpret_cast<void*>(NT_PRSTATUS), &iovec)) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700219 MEM_ALOGE("ptrace getregset for thread %d of process %d failed: %s", tid, pid_, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800220 return false;
221 }
222
223 unsigned int num_regs = iovec.iov_len / sizeof(uintptr_t);
224 thread_info.regs.assign(&regs[0], &regs[num_regs]);
225
226 const int sp =
227#if defined(__x86_64__)
228 offsetof(struct pt_regs, rsp) / sizeof(uintptr_t)
229#elif defined(__i386__)
230 offsetof(struct pt_regs, esp) / sizeof(uintptr_t)
231#elif defined(__arm__)
232 offsetof(struct pt_regs, ARM_sp) / sizeof(uintptr_t)
233#elif defined(__aarch64__)
234 offsetof(struct user_pt_regs, sp) / sizeof(uintptr_t)
235#elif defined(__mips__) || defined(__mips64__)
236 offsetof(struct pt_regs, regs[29]) / sizeof(uintptr_t)
237#else
238#error Unrecognized architecture
239#endif
240 ;
241
242 // TODO(ccross): use /proc/tid/status or /proc/pid/maps to get start_stack
243
244 thread_info.stack = std::pair<uintptr_t, uintptr_t>(regs[sp], 0);
245
246 return true;
247}
248
249int ThreadCaptureImpl::CaptureThread(pid_t tid) {
250 int ret = PtraceAttach(tid);
251 if (ret <= 0) {
252 return ret;
253 }
254
255 int status = 0;
256 if (TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL)) < 0) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700257 MEM_ALOGE("failed to wait for pause of thread %d of process %d: %s", tid, pid_, strerror(errno));
Colin Crossbcb4ed32016-01-14 15:35:40 -0800258 PtraceDetach(tid, 0);
259 return -1;
260 }
261
262 if (!WIFSTOPPED(status)) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700263 MEM_ALOGE("thread %d of process %d was not paused after waitpid, killed?", tid, pid_);
Colin Crossbcb4ed32016-01-14 15:35:40 -0800264 return 0;
265 }
266
267 unsigned int resume_signal = 0;
268
269 unsigned int signal = WSTOPSIG(status);
270 if ((status >> 16) == PTRACE_EVENT_STOP) {
271 switch (signal) {
272 case SIGSTOP:
273 case SIGTSTP:
274 case SIGTTIN:
275 case SIGTTOU:
276 // group-stop signals
277 break;
278 case SIGTRAP:
279 // normal ptrace interrupt stop
280 break;
281 default:
Christopher Ferris47dea712017-05-03 17:34:29 -0700282 MEM_ALOGE("unexpected signal %d with PTRACE_EVENT_STOP for thread %d of process %d", signal,
283 tid, pid_);
Colin Crossbcb4ed32016-01-14 15:35:40 -0800284 return -1;
285 }
286 } else {
287 // signal-delivery-stop
288 resume_signal = signal;
289 }
290
291 captured_threads_[tid] = resume_signal;
292 return 1;
293}
294
295bool ThreadCaptureImpl::ReleaseThread(pid_t tid) {
296 auto it = captured_threads_.find(tid);
297 if (it == captured_threads_.end()) {
298 return false;
299 }
300 return ReleaseThread(it->first, it->second);
301}
302
303bool ThreadCaptureImpl::ReleaseThread(pid_t tid, unsigned int signal) {
304 PtraceDetach(tid, signal);
305 return true;
306}
307
308bool ThreadCaptureImpl::ReleaseThreads() {
309 bool ret = true;
310 for (auto it = captured_threads_.begin(); it != captured_threads_.end(); ) {
311 if (ReleaseThread(it->first, it->second)) {
312 it = captured_threads_.erase(it);
313 } else {
314 it++;
315 ret = false;
316 }
317 }
318 return ret;
319}
320
321bool ThreadCaptureImpl::CapturedThreadInfo(ThreadInfoList& threads) {
322 threads.clear();
323
324 for (auto it = captured_threads_.begin(); it != captured_threads_.end(); it++) {
325 ThreadInfo t{0, allocator::vector<uintptr_t>(allocator_), std::pair<uintptr_t, uintptr_t>(0, 0)};
326 if (!PtraceThreadInfo(it->first, t)) {
327 return false;
328 }
329 threads.push_back(t);
330 }
331 return true;
332}
333
334ThreadCapture::ThreadCapture(pid_t pid, Allocator<ThreadCapture> allocator) {
335 Allocator<ThreadCaptureImpl> impl_allocator = allocator;
336 impl_ = impl_allocator.make_unique(pid, impl_allocator);
337}
338
339ThreadCapture::~ThreadCapture() {}
340
341bool ThreadCapture::ListThreads(TidList& tids) {
342 return impl_->ListThreads(tids);
343}
344
345bool ThreadCapture::CaptureThreads() {
346 return impl_->CaptureThreads();
347}
348
349bool ThreadCapture::ReleaseThreads() {
350 return impl_->ReleaseThreads();
351}
352
353bool ThreadCapture::ReleaseThread(pid_t tid) {
354 return impl_->ReleaseThread(tid);
355}
356
357bool ThreadCapture::CapturedThreadInfo(ThreadInfoList& threads) {
358 return impl_->CapturedThreadInfo(threads);
359}
360
361void ThreadCapture::InjectTestFunc(std::function<void(pid_t)>&& f) {
362 impl_->InjectTestFunc(std::forward<std::function<void(pid_t)>>(f));
363}