1 /*
2  * Copyright (C) 2017 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 <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/mman.h>
26 #include <sys/ptrace.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 #include <algorithm>
31 #include <memory>
32 #include <string>
33 #include <unordered_map>
34 #include <utility>
35 #include <vector>
36 
37 #include <unwindstack/Elf.h>
38 #include <unwindstack/JitDebug.h>
39 #include <unwindstack/Maps.h>
40 #include <unwindstack/Memory.h>
41 #include <unwindstack/Regs.h>
42 #include <unwindstack/Unwinder.h>
43 
44 #include <android-base/stringprintf.h>
45 
46 struct map_info_t {
47   uint64_t start;
48   uint64_t end;
49   uint64_t offset;
50   uint64_t flags;
51   std::string name;
52 };
53 
Attach(pid_t pid)54 static bool Attach(pid_t pid) {
55   if (ptrace(PTRACE_SEIZE, pid, 0, 0) == -1) {
56     return false;
57   }
58 
59   if (ptrace(PTRACE_INTERRUPT, pid, 0, 0) == -1) {
60     ptrace(PTRACE_DETACH, pid, 0, 0);
61     return false;
62   }
63 
64   // Allow at least 1 second to attach properly.
65   for (size_t i = 0; i < 1000; i++) {
66     siginfo_t si;
67     if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
68       return true;
69     }
70     usleep(1000);
71   }
72   printf("%d: Failed to stop.\n", pid);
73   return false;
74 }
75 
SaveRegs(unwindstack::Regs * regs)76 bool SaveRegs(unwindstack::Regs* regs) {
77   std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("regs.txt", "w+"), &fclose);
78   if (fp == nullptr) {
79     perror("Failed to create file regs.txt");
80     return false;
81   }
82   regs->IterateRegisters([&fp](const char* name, uint64_t value) {
83     fprintf(fp.get(), "%s: %" PRIx64 "\n", name, value);
84   });
85 
86   return true;
87 }
88 
SaveStack(pid_t pid,const std::vector<std::pair<uint64_t,uint64_t>> & stacks)89 bool SaveStack(pid_t pid, const std::vector<std::pair<uint64_t, uint64_t>>& stacks) {
90   for (size_t i = 0; i < stacks.size(); i++) {
91     std::string file_name;
92     if (stacks.size() != 1) {
93       file_name = "stack" + std::to_string(i) + ".data";
94     } else {
95       file_name = "stack.data";
96     }
97 
98     // Do this first, so if it fails, we don't create the file.
99     uint64_t sp_start = stacks[i].first;
100     uint64_t sp_end = stacks[i].second;
101     std::vector<uint8_t> buffer(sp_end - sp_start);
102     auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
103     if (!process_memory->Read(sp_start, buffer.data(), buffer.size())) {
104       printf("Unable to read stack data.\n");
105       return false;
106     }
107 
108     printf("Saving the stack 0x%" PRIx64 "-0x%" PRIx64 "\n", sp_start, sp_end);
109 
110     std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file_name.c_str(), "w+"), &fclose);
111     if (fp == nullptr) {
112       perror("Failed to create stack.data");
113       return false;
114     }
115 
116     size_t bytes = fwrite(&sp_start, 1, sizeof(sp_start), fp.get());
117     if (bytes != sizeof(sp_start)) {
118       printf("Failed to write sp_start data: sizeof(sp_start) %zu, written %zu\n", sizeof(sp_start),
119              bytes);
120       return false;
121     }
122 
123     bytes = fwrite(buffer.data(), 1, buffer.size(), fp.get());
124     if (bytes != buffer.size()) {
125       printf("Failed to write all stack data: stack size %zu, written %zu\n", buffer.size(), bytes);
126       return false;
127     }
128   }
129 
130   return true;
131 }
132 
CreateElfFromMemory(std::shared_ptr<unwindstack::Memory> & memory,map_info_t * info)133 bool CreateElfFromMemory(std::shared_ptr<unwindstack::Memory>& memory, map_info_t* info) {
134   std::string cur_name;
135   if (info->name.empty()) {
136     cur_name = android::base::StringPrintf("anonymous_%" PRIx64, info->start);
137   } else {
138     cur_name = android::base::StringPrintf("%s_%" PRIx64, basename(info->name.c_str()), info->start);
139   }
140 
141   std::vector<uint8_t> buffer(info->end - info->start);
142   // If this is a mapped in file, it might not be possible to read the entire
143   // map, so read all that is readable.
144   size_t bytes = memory->Read(info->start, buffer.data(), buffer.size());
145   if (bytes == 0) {
146     printf("Cannot read data from address %" PRIx64 " length %zu\n", info->start, buffer.size());
147     return false;
148   }
149 
150   std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
151   if (output == nullptr) {
152     perror((std::string("Cannot create ") + cur_name).c_str());
153     return false;
154   }
155 
156   size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
157   if (bytes_written != bytes) {
158     printf("Failed to write all data to file: bytes read %zu, written %zu\n", bytes, bytes_written);
159     return false;
160   }
161 
162   // Replace the name with the new name.
163   info->name = cur_name;
164 
165   return true;
166 }
167 
CopyElfFromFile(map_info_t * info,bool * file_copied)168 bool CopyElfFromFile(map_info_t* info, bool* file_copied) {
169   std::string cur_name = basename(info->name.c_str());
170   if (*file_copied) {
171     info->name = cur_name;
172     return true;
173   }
174 
175   std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(info->name.c_str(), "r"), &fclose);
176   if (fp == nullptr) {
177     perror((std::string("Cannot open ") + info->name).c_str());
178     return false;
179   }
180 
181   std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
182   if (output == nullptr) {
183     perror((std::string("Cannot create file " + cur_name)).c_str());
184     return false;
185   }
186   std::vector<uint8_t> buffer(10000);
187   size_t bytes;
188   while ((bytes = fread(buffer.data(), 1, buffer.size(), fp.get())) > 0) {
189     size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
190     if (bytes_written != bytes) {
191       printf("Bytes written doesn't match bytes read: read %zu, written %zu\n", bytes,
192              bytes_written);
193       return false;
194     }
195   }
196 
197   // Replace the name with the new name.
198   info->name = cur_name;
199 
200   return true;
201 }
202 
FillInAndGetMapInfo(std::unordered_map<uint64_t,map_info_t> & maps_by_start,unwindstack::MapInfo * map_info)203 map_info_t* FillInAndGetMapInfo(std::unordered_map<uint64_t, map_info_t>& maps_by_start,
204                                 unwindstack::MapInfo* map_info) {
205   auto info = &maps_by_start[map_info->start()];
206   info->start = map_info->start();
207   info->end = map_info->end();
208   info->offset = map_info->offset();
209   info->name = map_info->name();
210   info->flags = map_info->flags();
211 
212   return info;
213 }
214 
SaveMapInformation(std::shared_ptr<unwindstack::Memory> & process_memory,map_info_t * info,bool * file_copied)215 void SaveMapInformation(std::shared_ptr<unwindstack::Memory>& process_memory, map_info_t* info,
216                         bool* file_copied) {
217   if (CopyElfFromFile(info, file_copied)) {
218     return;
219   }
220   *file_copied = false;
221 
222   // Try to create the elf from memory, this will handle cases where
223   // the data only exists in memory such as vdso data on x86.
224   if (CreateElfFromMemory(process_memory, info)) {
225     return;
226   }
227 
228   printf("Cannot save memory or file for map ");
229   if (!info->name.empty()) {
230     printf("%s\n", info->name.c_str());
231   } else {
232     printf("anonymous:%" PRIx64 "\n", info->start);
233   }
234 }
235 
SaveData(pid_t pid)236 int SaveData(pid_t pid) {
237   unwindstack::Regs* regs = unwindstack::Regs::RemoteGet(pid);
238   if (regs == nullptr) {
239     printf("Unable to get remote reg data.\n");
240     return 1;
241   }
242 
243   // Save the current state of the registers.
244   if (!SaveRegs(regs)) {
245     return 1;
246   }
247 
248   // Do an unwind so we know how much of the stack to save, and what
249   // elf files are involved.
250   unwindstack::UnwinderFromPid unwinder(1024, pid);
251   unwinder.SetRegs(regs);
252   uint64_t sp = regs->sp();
253   unwinder.Unwind();
254 
255   std::unordered_map<uint64_t, map_info_t> maps_by_start;
256   std::vector<std::pair<uint64_t, uint64_t>> stacks;
257   unwindstack::Maps* maps = unwinder.GetMaps();
258   uint64_t sp_map_start = 0;
259   unwindstack::MapInfo* map_info = maps->Find(sp);
260   if (map_info != nullptr) {
261     stacks.emplace_back(std::make_pair(sp, map_info->end()));
262     sp_map_start = map_info->start();
263   }
264 
265   for (const auto& frame : unwinder.frames()) {
266     map_info = maps->Find(frame.sp);
267     if (map_info != nullptr && sp_map_start != map_info->start()) {
268       stacks.emplace_back(std::make_pair(frame.sp, map_info->end()));
269       sp_map_start = map_info->start();
270     }
271 
272     if (maps_by_start.count(frame.map_start) == 0) {
273       map_info = maps->Find(frame.map_start);
274       if (map_info == nullptr) {
275         continue;
276       }
277 
278       auto info = FillInAndGetMapInfo(maps_by_start, map_info);
279       bool file_copied = false;
280       SaveMapInformation(unwinder.GetProcessMemory(), info, &file_copied);
281 
282       // If you are using a a linker that creates two maps (one read-only, one
283       // read-executable), it's necessary to capture the previous map
284       // information if needed.
285       unwindstack::MapInfo* prev_map = map_info->prev_map();
286       if (prev_map != nullptr && map_info->offset() != 0 && prev_map->offset() == 0 &&
287           prev_map->flags() == PROT_READ && map_info->name() == prev_map->name() &&
288           maps_by_start.count(prev_map->start()) == 0) {
289         info = FillInAndGetMapInfo(maps_by_start, prev_map);
290         SaveMapInformation(unwinder.GetProcessMemory(), info, &file_copied);
291       }
292     }
293   }
294 
295   for (size_t i = 0; i < unwinder.NumFrames(); i++) {
296     printf("%s\n", unwinder.FormatFrame(i).c_str());
297   }
298 
299   if (!SaveStack(pid, stacks)) {
300     return 1;
301   }
302 
303   std::vector<std::pair<uint64_t, map_info_t>> sorted_maps(maps_by_start.begin(),
304                                                            maps_by_start.end());
305   std::sort(sorted_maps.begin(), sorted_maps.end(),
306             [](auto& a, auto& b) { return a.first < b.first; });
307 
308   std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("maps.txt", "w+"), &fclose);
309   if (fp == nullptr) {
310     perror("Failed to create maps.txt");
311     return false;
312   }
313 
314   for (auto& element : sorted_maps) {
315     char perms[5] = {"---p"};
316     map_info_t& map = element.second;
317     if (map.flags & PROT_READ) {
318       perms[0] = 'r';
319     }
320     if (map.flags & PROT_WRITE) {
321       perms[1] = 'w';
322     }
323     if (map.flags & PROT_EXEC) {
324       perms[2] = 'x';
325     }
326     fprintf(fp.get(), "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " 00:00 0", map.start, map.end, perms,
327             map.offset);
328     if (!map.name.empty()) {
329       fprintf(fp.get(), "   %s", map.name.c_str());
330     }
331     fprintf(fp.get(), "\n");
332   }
333 
334   return 0;
335 }
336 
main(int argc,char ** argv)337 int main(int argc, char** argv) {
338   if (argc != 2) {
339     printf("Usage: unwind_for_offline <PID>\n");
340     return 1;
341   }
342 
343   pid_t pid = atoi(argv[1]);
344   if (!Attach(pid)) {
345     printf("Failed to attach to pid %d: %s\n", pid, strerror(errno));
346     return 1;
347   }
348 
349   int return_code = SaveData(pid);
350 
351   ptrace(PTRACE_DETACH, pid, 0, 0);
352 
353   return return_code;
354 }
355