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/DexFiles.h>
30 #include <unwindstack/Elf.h>
31 #include <unwindstack/JitDebug.h>
32 #include <unwindstack/Maps.h>
33 #include <unwindstack/Memory.h>
34 #include <unwindstack/Regs.h>
35 #include <unwindstack/Unwinder.h>
36
Attach(pid_t pid)37 static bool Attach(pid_t pid) {
38 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == -1) {
39 return false;
40 }
41
42 if (ptrace(PTRACE_INTERRUPT, pid, 0, 0) == -1) {
43 ptrace(PTRACE_DETACH, pid, 0, 0);
44 return false;
45 }
46
47 // Allow at least 1 second to attach properly.
48 for (size_t i = 0; i < 1000; i++) {
49 siginfo_t si;
50 if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
51 return true;
52 }
53 usleep(1000);
54 }
55 printf("%d: Failed to stop.\n", pid);
56 return false;
57 }
58
DoUnwind(pid_t pid)59 void DoUnwind(pid_t pid) {
60 unwindstack::Regs* regs = unwindstack::Regs::RemoteGet(pid);
61 if (regs == nullptr) {
62 printf("Unable to get remote reg data\n");
63 return;
64 }
65
66 printf("ABI: ");
67 switch (regs->Arch()) {
68 case unwindstack::ARCH_ARM:
69 printf("arm");
70 break;
71 case unwindstack::ARCH_X86:
72 printf("x86");
73 break;
74 case unwindstack::ARCH_ARM64:
75 printf("arm64");
76 break;
77 case unwindstack::ARCH_X86_64:
78 printf("x86_64");
79 break;
80 case unwindstack::ARCH_MIPS:
81 printf("mips");
82 break;
83 case unwindstack::ARCH_MIPS64:
84 printf("mips64");
85 break;
86 default:
87 printf("unknown\n");
88 return;
89 }
90 printf("\n");
91
92 unwindstack::UnwinderFromPid unwinder(1024, pid);
93 unwinder.SetRegs(regs);
94 unwinder.Unwind();
95
96 // Print the frames.
97 for (size_t i = 0; i < unwinder.NumFrames(); i++) {
98 printf("%s\n", unwinder.FormatFrame(i).c_str());
99 }
100 }
101
main(int argc,char ** argv)102 int main(int argc, char** argv) {
103 if (argc != 2) {
104 printf("Usage: unwind <PID>\n");
105 return 1;
106 }
107
108 pid_t pid = atoi(argv[1]);
109 if (!Attach(pid)) {
110 printf("Failed to attach to pid %d: %s\n", pid, strerror(errno));
111 return 1;
112 }
113
114 DoUnwind(pid);
115
116 ptrace(PTRACE_DETACH, pid, 0, 0);
117
118 return 0;
119 }
120