• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <cstdio>
18 #define _GNU_SOURCE 1
19 #include <inttypes.h>
20 #include <stdio.h>
21 #include <sys/mman.h>
22 
23 #include <cstdlib>
24 #include <filesystem>
25 #include <memory>
26 #include <string>
27 #include <unordered_map>
28 #include <utility>
29 #include <vector>
30 
31 #include <unwindstack/Elf.h>
32 #include <unwindstack/JitDebug.h>
33 #include <unwindstack/MapInfo.h>
34 #include <unwindstack/Maps.h>
35 #include <unwindstack/Memory.h>
36 #include <unwindstack/Regs.h>
37 #include <unwindstack/Unwinder.h>
38 #include "utils/ProcessTracer.h"
39 
40 #include <android-base/file.h>
41 #include <android-base/parseint.h>
42 #include <android-base/stringprintf.h>
43 
44 namespace {
45 constexpr pid_t kMinPid = 1;
46 constexpr int kAllCmdOptionsParsed = -1;
47 
48 struct map_info_t {
49   uint64_t start;
50   uint64_t end;
51   uint64_t offset;
52   uint64_t flags;
53   std::string name;
54 };
55 
usage(int exit_code)56 int usage(int exit_code) {
57   fprintf(stderr, "USAGE: unwind_for_offline [-t] [-e FILE] [-f[FILE]] <PID>\n\n");
58   fprintf(stderr, "OPTIONS:\n");
59   fprintf(stderr, "-t\n");
60   fprintf(stderr, "       Dump offline snapshot for all threads of <PID>.\n");
61   fprintf(stderr, "-e FILE\n");
62   fprintf(stderr, "       If FILE is a valid ELF file included in /proc/<PID>/maps,\n");
63   fprintf(stderr, "       unwind_for_offline will wait until the current frame (PC)\n");
64   fprintf(stderr, "       lies within the .so file given by FILE. FILE should be\n");
65   fprintf(stderr, "       base name of the path (the component following the final\n");
66   fprintf(stderr, "       '/') rather than the fully qualified path.\n");
67   fprintf(stderr, "-f [FILE]\n");
68   fprintf(stderr, "       Write info (e.g. frames and stack range) logs to a file\n");
69   fprintf(stderr, "       rather than to the stdout/stderr. If FILE is not\n");
70   fprintf(stderr, "       specified, the output file will be named 'output.txt'.\n");
71   return exit_code;
72 }
73 
EnsureProcInDesiredElf(const std::string & elf_name,unwindstack::ProcessTracer & proc)74 bool EnsureProcInDesiredElf(const std::string& elf_name, unwindstack::ProcessTracer& proc) {
75   if (proc.UsesSharedLibrary(proc.pid(), elf_name)) {
76     printf("Confirmed pid %d does use %s. Waiting for PC to lie within %s...\n", proc.pid(),
77            elf_name.c_str(), elf_name.c_str());
78     if (!proc.StopInDesiredElf(elf_name)) return false;
79   } else {
80     fprintf(stderr, "Process %d does not use library %s.\n", proc.pid(), elf_name.c_str());
81     return false;
82   }
83   return true;
84 }
85 
CreateAndChangeDumpDir(std::filesystem::path thread_dir,pid_t tid,bool is_main_thread)86 bool CreateAndChangeDumpDir(std::filesystem::path thread_dir, pid_t tid, bool is_main_thread) {
87   std::string dir_name = std::to_string(tid);
88   if (is_main_thread) dir_name += "_main-thread";
89   thread_dir /= dir_name;
90   if (!std::filesystem::create_directory(thread_dir)) {
91     fprintf(stderr, "Failed to create directory for tid %d\n", tid);
92     return false;
93   }
94   std::filesystem::current_path(thread_dir);
95   return true;
96 }
97 
SaveRegs(unwindstack::Regs * regs)98 bool SaveRegs(unwindstack::Regs* regs) {
99   std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("regs.txt", "w+"), &fclose);
100   if (fp == nullptr) {
101     perror("Failed to create file regs.txt");
102     return false;
103   }
104   regs->IterateRegisters([&fp](const char* name, uint64_t value) {
105     fprintf(fp.get(), "%s: %" PRIx64 "\n", name, value);
106   });
107 
108   return true;
109 }
110 
SaveStack(pid_t pid,const std::vector<std::pair<uint64_t,uint64_t>> & stacks,FILE * output_fp)111 bool SaveStack(pid_t pid, const std::vector<std::pair<uint64_t, uint64_t>>& stacks,
112                FILE* output_fp) {
113   for (size_t i = 0; i < stacks.size(); i++) {
114     std::string file_name;
115     if (stacks.size() != 1) {
116       file_name = "stack" + std::to_string(i) + ".data";
117     } else {
118       file_name = "stack.data";
119     }
120 
121     // Do this first, so if it fails, we don't create the file.
122     uint64_t sp_start = stacks[i].first;
123     uint64_t sp_end = stacks[i].second;
124     std::vector<uint8_t> buffer(sp_end - sp_start);
125     auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
126     if (!process_memory->Read(sp_start, buffer.data(), buffer.size())) {
127       fprintf(stderr, "Unable to read stack data.\n");
128       return false;
129     }
130 
131     fprintf(output_fp, "\nSaving the stack 0x%" PRIx64 "-0x%" PRIx64 "\n", sp_start, sp_end);
132 
133     std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file_name.c_str(), "w+"), &fclose);
134     if (fp == nullptr) {
135       perror("Failed to create stack.data");
136       return false;
137     }
138 
139     size_t bytes = fwrite(&sp_start, 1, sizeof(sp_start), fp.get());
140     if (bytes != sizeof(sp_start)) {
141       fprintf(stderr, "Failed to write sp_start data: sizeof(sp_start) %zu, written %zu\n",
142               sizeof(sp_start), bytes);
143       return false;
144     }
145 
146     bytes = fwrite(buffer.data(), 1, buffer.size(), fp.get());
147     if (bytes != buffer.size()) {
148       fprintf(stderr, "Failed to write all stack data: stack size %zu, written %zu\n",
149               buffer.size(), bytes);
150       return false;
151     }
152   }
153 
154   return true;
155 }
156 
CreateElfFromMemory(std::shared_ptr<unwindstack::Memory> & memory,map_info_t * info)157 bool CreateElfFromMemory(std::shared_ptr<unwindstack::Memory>& memory, map_info_t* info) {
158   std::string cur_name;
159   if (info->name.empty()) {
160     cur_name = android::base::StringPrintf("anonymous_%" PRIx64, info->start);
161   } else {
162     cur_name = android::base::StringPrintf(
163         "%s_%" PRIx64, android::base::Basename(info->name).c_str(), info->start);
164   }
165 
166   std::vector<uint8_t> buffer(info->end - info->start);
167   // If this is a mapped in file, it might not be possible to read the entire
168   // map, so read all that is readable.
169   size_t bytes = memory->Read(info->start, buffer.data(), buffer.size());
170   if (bytes == 0) {
171     fprintf(stderr, "Cannot read data from address %" PRIx64 " length %zu\n", info->start,
172             buffer.size());
173     return false;
174   }
175 
176   std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
177   if (output == nullptr) {
178     perror((std::string("Cannot create ") + cur_name).c_str());
179     return false;
180   }
181 
182   size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
183   if (bytes_written != bytes) {
184     fprintf(stderr, "Failed to write all data to file: bytes read %zu, written %zu\n", bytes,
185             bytes_written);
186     return false;
187   }
188 
189   // Replace the name with the new name.
190   info->name = cur_name;
191 
192   return true;
193 }
194 
CopyElfFromFile(map_info_t * info,bool * file_copied)195 bool CopyElfFromFile(map_info_t* info, bool* file_copied) {
196   std::string cur_name = android::base::Basename(info->name);
197   if (*file_copied) {
198     info->name = cur_name;
199     return true;
200   }
201 
202   std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(info->name.c_str(), "r"), &fclose);
203   if (fp == nullptr) {
204     perror((std::string("Cannot open ") + info->name).c_str());
205     return false;
206   }
207 
208   std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
209   if (output == nullptr) {
210     perror((std::string("Cannot create file " + cur_name)).c_str());
211     return false;
212   }
213   std::vector<uint8_t> buffer(10000);
214   size_t bytes;
215   while ((bytes = fread(buffer.data(), 1, buffer.size(), fp.get())) > 0) {
216     size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
217     if (bytes_written != bytes) {
218       fprintf(stderr, "Bytes written doesn't match bytes read: read %zu, written %zu\n", bytes,
219               bytes_written);
220       return false;
221     }
222   }
223 
224   // Replace the name with the new name.
225   info->name = cur_name;
226 
227   return true;
228 }
229 
FillInAndGetMapInfo(std::unordered_map<uint64_t,map_info_t> & maps_by_start,unwindstack::MapInfo * map_info)230 map_info_t* FillInAndGetMapInfo(std::unordered_map<uint64_t, map_info_t>& maps_by_start,
231                                 unwindstack::MapInfo* map_info) {
232   auto info = &maps_by_start[map_info->start()];
233   info->start = map_info->start();
234   info->end = map_info->end();
235   info->offset = map_info->offset();
236   info->name = map_info->name();
237   info->flags = map_info->flags();
238 
239   return info;
240 }
241 
SaveMapInformation(std::shared_ptr<unwindstack::Memory> & process_memory,map_info_t * info,bool * file_copied)242 void SaveMapInformation(std::shared_ptr<unwindstack::Memory>& process_memory, map_info_t* info,
243                         bool* file_copied) {
244   if (CopyElfFromFile(info, file_copied)) {
245     return;
246   }
247   *file_copied = false;
248 
249   // Try to create the elf from memory, this will handle cases where
250   // the data only exists in memory such as vdso data on x86.
251   if (CreateElfFromMemory(process_memory, info)) {
252     return;
253   }
254 
255   fprintf(stderr, "Cannot save memory or file for map ");
256   if (!info->name.empty()) {
257     fprintf(stderr, "%s\n", info->name.c_str());
258   } else {
259     fprintf(stderr, "anonymous:%" PRIx64 "\n", info->start);
260   }
261 }
262 
SaveData(pid_t tid,const std::filesystem::path & cwd,bool is_main_thread,FILE * output_fp)263 bool SaveData(pid_t tid, const std::filesystem::path& cwd, bool is_main_thread, FILE* output_fp) {
264   fprintf(output_fp, "-------------------- tid = %d %s--------------------\n", tid,
265           is_main_thread ? "(main thread) " : "--------------");
266   unwindstack::Regs* regs = unwindstack::Regs::RemoteGet(tid);
267   if (regs == nullptr) {
268     fprintf(stderr, "Unable to get remote reg data.\n");
269     return false;
270   }
271 
272   if (!CreateAndChangeDumpDir(cwd, tid, is_main_thread)) return false;
273 
274   // Save the current state of the registers.
275   if (!SaveRegs(regs)) {
276     return false;
277   }
278 
279   // Do an unwind so we know how much of the stack to save, and what
280   // elf files are involved.
281   unwindstack::UnwinderFromPid unwinder(1024, tid);
282   unwinder.SetRegs(regs);
283   uint64_t sp = regs->sp();
284   unwinder.Unwind();
285 
286   std::unordered_map<uint64_t, map_info_t> maps_by_start;
287   std::vector<std::pair<uint64_t, uint64_t>> stacks;
288   unwindstack::Maps* maps = unwinder.GetMaps();
289   uint64_t sp_map_start = 0;
290   auto map_info = maps->Find(sp);
291   if (map_info != nullptr) {
292     stacks.emplace_back(std::make_pair(sp, map_info->end()));
293     sp_map_start = map_info->start();
294   }
295 
296   for (const auto& frame : unwinder.frames()) {
297     map_info = maps->Find(frame.sp);
298     if (map_info != nullptr && sp_map_start != map_info->start()) {
299       stacks.emplace_back(std::make_pair(frame.sp, map_info->end()));
300       sp_map_start = map_info->start();
301     }
302 
303     if (maps_by_start.count(frame.map_info->start()) == 0) {
304       if (map_info == nullptr) {
305         continue;
306       }
307 
308       auto info = FillInAndGetMapInfo(maps_by_start, map_info.get());
309       bool file_copied = false;
310       SaveMapInformation(unwinder.GetProcessMemory(), info, &file_copied);
311 
312       // If you are using a a linker that creates two maps (one read-only, one
313       // read-executable), it's necessary to capture the previous map
314       // information if needed.
315       auto prev_map = map_info->prev_map();
316       if (prev_map != nullptr && map_info->offset() != 0 && prev_map->offset() == 0 &&
317           prev_map->flags() == PROT_READ && map_info->name() == prev_map->name() &&
318           maps_by_start.count(prev_map->start()) == 0) {
319         info = FillInAndGetMapInfo(maps_by_start, prev_map.get());
320         SaveMapInformation(unwinder.GetProcessMemory(), info, &file_copied);
321       }
322     }
323   }
324 
325   for (size_t i = 0; i < unwinder.NumFrames(); i++) {
326     fprintf(output_fp, "%s\n", unwinder.FormatFrame(i).c_str());
327   }
328 
329   if (!SaveStack(tid, stacks, output_fp)) {
330     return false;
331   }
332 
333   std::vector<std::pair<uint64_t, map_info_t>> sorted_maps(maps_by_start.begin(),
334                                                            maps_by_start.end());
335   std::sort(sorted_maps.begin(), sorted_maps.end(),
336             [](auto& a, auto& b) { return a.first < b.first; });
337 
338   std::unique_ptr<FILE, decltype(&fclose)> map_fp(fopen("maps.txt", "w+"), &fclose);
339   if (map_fp == nullptr) {
340     perror("Failed to create maps.txt");
341     return false;
342   }
343 
344   for (auto& element : sorted_maps) {
345     char perms[5] = {"---p"};
346     map_info_t& map = element.second;
347     if (map.flags & PROT_READ) {
348       perms[0] = 'r';
349     }
350     if (map.flags & PROT_WRITE) {
351       perms[1] = 'w';
352     }
353     if (map.flags & PROT_EXEC) {
354       perms[2] = 'x';
355     }
356     fprintf(map_fp.get(), "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " 00:00 0", map.start, map.end,
357             perms, map.offset);
358     if (!map.name.empty()) {
359       fprintf(map_fp.get(), "   %s", map.name.c_str());
360     }
361     fprintf(map_fp.get(), "\n");
362   }
363 
364   fprintf(output_fp, "------------------------------------------------------------------\n");
365   return true;
366 }
367 }  // namespace
368 
main(int argc,char ** argv)369 int main(int argc, char** argv) {
370   if (argc < 2) return usage(EXIT_FAILURE);
371 
372   bool dump_threads = false;
373   std::string elf_name;
374   std::unique_ptr<FILE, decltype(&fclose)> output_fp(nullptr, &fclose);
375   int opt;
376   while ((opt = getopt(argc, argv, ":te:f::")) != kAllCmdOptionsParsed) {
377     switch (opt) {
378       case 't': {
379         dump_threads = true;
380         break;
381       }
382       case 'e': {
383         elf_name = optarg;
384         if (elf_name == "-f") {
385           fprintf(stderr, "Missing argument for option e.\n");
386           return usage(EXIT_FAILURE);
387         }
388         break;
389       }
390       case 'f': {
391         const std::string& output_filename = optarg != nullptr ? optarg : "output.txt";
392         if (optind == argc - 2) {
393           fprintf(stderr, "Ensure there is no space between '-f' and the filename provided.\n");
394           return usage(EXIT_FAILURE);
395         }
396         output_fp.reset(fopen(output_filename.c_str(), "a"));
397         break;
398       }
399       case '?': {
400         if (isprint(optopt))
401           fprintf(stderr, "Unknown option `-%c'.\n", optopt);
402         else
403           fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
404         return usage(EXIT_FAILURE);
405       }
406       case ':': {
407         fprintf(stderr, "Missing arg for option %c.\n", optopt);
408         return usage(EXIT_FAILURE);
409       }
410       default: {
411         return usage(EXIT_FAILURE);
412       }
413     }
414   }
415   if (optind != argc - 1) return usage(EXIT_FAILURE);
416 
417   pid_t pid;
418   if (!android::base::ParseInt(argv[optind], &pid, kMinPid, std::numeric_limits<pid_t>::max()))
419     return usage(EXIT_FAILURE);
420 
421   unwindstack::ProcessTracer proc(pid, dump_threads);
422   if (!proc.Stop()) return EXIT_FAILURE;
423   if (!elf_name.empty()) {
424     if (!EnsureProcInDesiredElf(elf_name, proc)) return EXIT_FAILURE;
425   }
426   if (!output_fp) output_fp.reset(stdout);
427   std::filesystem::path cwd = std::filesystem::current_path();
428 
429   if (!proc.Attach(proc.pid())) return EXIT_FAILURE;
430   if (!SaveData(proc.pid(), cwd, /*is_main_thread=*/proc.IsTracingThreads(), output_fp.get()))
431     return EXIT_FAILURE;
432   if (!proc.Detach(proc.pid())) return EXIT_FAILURE;
433   for (const pid_t& tid : proc.tids()) {
434     if (!proc.Attach(tid)) return EXIT_FAILURE;
435     if (!SaveData(tid, cwd, /*is_main_thread=*/false, output_fp.get())) return EXIT_FAILURE;
436     if (!proc.Detach(tid)) return EXIT_FAILURE;
437   }
438 
439   printf("\nSuccess!\n");
440   return EXIT_SUCCESS;
441 }
442