1 /*
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 <elf.h>
18 #include <errno.h>
19 #include <inttypes.h>
20 #include <signal.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/ptrace.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28
29 #include <unwindstack/AndroidUnwinder.h>
30 #include <unwindstack/Regs.h>
31
Attach(pid_t pid)32 static bool Attach(pid_t pid) {
33 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == -1) {
34 return false;
35 }
36
37 if (ptrace(PTRACE_INTERRUPT, pid, 0, 0) == -1) {
38 ptrace(PTRACE_DETACH, pid, 0, 0);
39 return false;
40 }
41
42 // Allow at least 1 second to attach properly.
43 for (size_t i = 0; i < 1000; i++) {
44 siginfo_t si;
45 if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
46 return true;
47 }
48 usleep(1000);
49 }
50 printf("%d: Failed to stop.\n", pid);
51 return false;
52 }
53
DoUnwind(pid_t pid)54 void DoUnwind(pid_t pid) {
55 unwindstack::Regs* regs = unwindstack::Regs::RemoteGet(pid);
56 if (regs == nullptr) {
57 printf("Unable to get remote reg data\n");
58 return;
59 }
60
61 printf("ABI: ");
62 switch (regs->Arch()) {
63 case unwindstack::ARCH_ARM:
64 printf("arm");
65 break;
66 case unwindstack::ARCH_X86:
67 printf("x86");
68 break;
69 case unwindstack::ARCH_ARM64:
70 printf("arm64");
71 break;
72 case unwindstack::ARCH_X86_64:
73 printf("x86_64");
74 break;
75 case unwindstack::ARCH_RISCV64:
76 printf("riscv64");
77 break;
78 default:
79 printf("unknown\n");
80 return;
81 }
82 printf("\n");
83
84 unwindstack::AndroidRemoteUnwinder unwinder(pid);
85 unwindstack::AndroidUnwinderData data;
86 if (!unwinder.Unwind(regs, data)) {
87 printf("Unable to unwind pid %d: %s\n", pid, data.GetErrorString().c_str());
88 return;
89 }
90 data.DemangleFunctionNames();
91
92 // Print the frames.
93 for (const auto& frame : data.frames) {
94 printf("%s\n", unwinder.FormatFrame(frame).c_str());
95 }
96 }
97
main(int argc,char ** argv)98 int main(int argc, char** argv) {
99 if (argc != 2) {
100 printf("Usage: unwind <PID>\n");
101 return 1;
102 }
103
104 pid_t pid = atoi(argv[1]);
105 if (!Attach(pid)) {
106 printf("Failed to attach to pid %d: %s\n", pid, strerror(errno));
107 return 1;
108 }
109
110 DoUnwind(pid);
111
112 ptrace(PTRACE_DETACH, pid, 0, 0);
113
114 return 0;
115 }
116