summaryrefslogtreecommitdiff
path: root/libunwindstack/utils/OfflineUnwindUtils.cpp
blob: 8bc4bafca6a0962b559f2275221556fc80f20594 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <err.h>
#include <errno.h>
#include <inttypes.h>
#include <string.h>

#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <regex>
#include <sstream>
#include <string>
#include <tuple>

#include <android-base/file.h>
#include <zlib.h>

#include <unwindstack/Arch.h>
#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Maps.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include <unwindstack/Unwinder.h>

#include "Check.h"
#include "MemoryOffline.h"
#include "utils/MemoryFake.h"

#include "OfflineUnwindUtils.h"

namespace unwindstack {

void DecompressFiles(const std::string& directory) {
  namespace fs = std::filesystem;
  for (const auto& file : fs::recursive_directory_iterator(directory)) {
    fs::path src_path = file.path();
    if (src_path.extension() == ".gz") {
      fs::path dst_path = fs::path(src_path).replace_extension();  // Remove .gz extension.
      if (!fs::exists(dst_path) || fs::last_write_time(src_path) > fs::last_write_time(dst_path)) {
        gzFile src = gzopen(src_path.c_str(), "rb");
        CHECK(src != nullptr);
        fs::path tmp_path = fs::path(src_path).replace_extension("." + std::to_string(getpid()));
        std::ofstream tmp(tmp_path);  // Temporary file to avoid races between unit tests.
        char buffer[1024];
        int size;
        while ((size = gzread(src, buffer, sizeof(buffer))) > 0) {
          tmp.write(buffer, size);
        }
        tmp.close();
        gzclose(src);
        fs::rename(tmp_path, dst_path);
      }
    }
  }
}

std::string GetOfflineFilesDirectory() {
  std::string path = android::base::GetExecutableDirectory() + "/offline_files/";
  DecompressFiles(path);
  return path;
}

std::string DumpFrames(const Unwinder& unwinder) {
  std::string str;
  for (size_t i = 0; i < unwinder.NumFrames(); i++) {
    str += unwinder.FormatFrame(i) + "\n";
  }
  return str;
}

bool AddMemory(std::string file_name, MemoryOfflineParts* parts, std::string& error_msg) {
  MemoryOffline* memory = new MemoryOffline;
  if (!memory->Init(file_name.c_str(), 0)) {
    std::stringstream err_stream;
    err_stream << "Failed to add stack '" << file_name << "' to stack memory.";
    error_msg = err_stream.str();
    return false;
  }
  parts->Add(memory);

  return true;
}

bool OfflineUnwindUtils::Init(const std::string& offline_files_dir, ArchEnum arch,
                              std::string& error_msg, bool add_stack, bool set_maps) {
  // Change to offline files directory so we can read the ELF files
  cwd_ = std::filesystem::current_path();
  offline_dir_ = GetOfflineFilesDirectory() + offline_files_dir;
  std::filesystem::current_path(std::filesystem::path(offline_dir_));

  if (!android::base::ReadFileToString((offline_dir_ + "maps.txt"), &map_buffer_)) {
    std::stringstream err_stream;
    err_stream << "Failed to read from '" << offline_dir_ << "maps.txt' into memory.";
    error_msg = err_stream.str();
    return false;
  }
  if (set_maps) {
    if (!ResetMaps(error_msg)) return false;
  }

  if (!SetRegs(arch, error_msg)) return false;

  if (add_stack) {
    if (!SetProcessMemory(error_msg)) return false;
  }
  if (process_memory_ == nullptr) {
    process_memory_.reset(new MemoryFake);
  }
  return true;
}

bool OfflineUnwindUtils::ResetMaps(std::string& error_msg) {
  maps_.reset(new BufferMaps(map_buffer_.c_str()));
  if (!maps_->Parse()) {
    error_msg = "Failed to parse offline maps.";
    return false;
  }
  return true;
}

bool OfflineUnwindUtils::SetProcessMemory(std::string& error_msg) {
  std::string stack_name(offline_dir_ + "stack.data");
  struct stat st;
  if (stat(stack_name.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
    auto stack_memory = std::make_unique<MemoryOffline>();
    if (!stack_memory->Init((offline_dir_ + "stack.data").c_str(), 0)) {
      std::stringstream err_stream;
      err_stream << "Failed to initialize stack memory from " << offline_dir_ << "stack.data.";
      error_msg = err_stream.str();
      return false;
    }
    process_memory_.reset(stack_memory.release());
  } else {
    std::unique_ptr<MemoryOfflineParts> stack_memory(new MemoryOfflineParts);
    for (size_t i = 0;; i++) {
      stack_name = offline_dir_ + "stack" + std::to_string(i) + ".data";
      if (stat(stack_name.c_str(), &st) == -1 || !S_ISREG(st.st_mode)) {
        if (i == 0) {
          error_msg = "No stack data files found.";
          return false;
        }
        break;
      }
      if (!AddMemory(stack_name, stack_memory.get(), error_msg)) return false;
    }
    process_memory_.reset(stack_memory.release());
  }
  return true;
}

bool OfflineUnwindUtils::SetJitProcessMemory(std::string& error_msg) {
  MemoryOfflineParts* memory = new MemoryOfflineParts;

  // Construct process memory from all descriptor, stack, entry, and jit files
  for (const auto& file : std::filesystem::directory_iterator(offline_dir_)) {
    std::string filename = file.path().string();
    if (std::regex_match(filename,
                         std::regex("^(.+)\\/(descriptor|stack|entry|jit)(\\d*)\\.data$"))) {
      if (!AddMemory(filename, memory, error_msg)) return false;
    }
  }

  process_memory_.reset(memory);
  return true;
}

bool OfflineUnwindUtils::SetRegs(ArchEnum arch, std::string& error_msg) {
  switch (arch) {
    case ARCH_ARM: {
      RegsArm* regs = new RegsArm;
      regs_.reset(regs);
      if (!ReadRegs<uint32_t>(regs, arm_regs_, error_msg)) return false;
      break;
    }
    case ARCH_ARM64: {
      RegsArm64* regs = new RegsArm64;
      regs_.reset(regs);
      if (!ReadRegs<uint64_t>(regs, arm64_regs_, error_msg)) return false;
      break;
    }
    case ARCH_X86: {
      RegsX86* regs = new RegsX86;
      regs_.reset(regs);
      if (!ReadRegs<uint32_t>(regs, x86_regs_, error_msg)) return false;
      break;
    }
    case ARCH_X86_64: {
      RegsX86_64* regs = new RegsX86_64;
      regs_.reset(regs);
      if (!ReadRegs<uint64_t>(regs, x86_64_regs_, error_msg)) return false;
      break;
    }
    default:
      error_msg = "Unknown architechture " + std::to_string(arch);
      return false;
  }

  return true;
}

template <typename AddressType>
bool OfflineUnwindUtils::ReadRegs(RegsImpl<AddressType>* regs,
                                  const std::unordered_map<std::string, uint32_t>& name_to_reg,
                                  std::string& error_msg) {
  std::stringstream err_stream;
  FILE* fp = fopen((offline_dir_ + "regs.txt").c_str(), "r");
  if (fp == nullptr) {
    err_stream << "Error opening file '" << offline_dir_ << "regs.txt': " << strerror(errno);
    error_msg = err_stream.str();
    return false;
  }

  while (!feof(fp)) {
    uint64_t value;
    char reg_name[100];
    if (fscanf(fp, "%s %" SCNx64 "\n", reg_name, &value) != 2) {
      err_stream << "Failed to read in register name/values from '" << offline_dir_ << "regs.txt'.";
      error_msg = err_stream.str();
      return false;
    }
    std::string name(reg_name);
    if (!name.empty()) {
      // Remove the : from the end.
      name.resize(name.size() - 1);
    }
    auto entry = name_to_reg.find(name);
    if (entry == name_to_reg.end()) {
      err_stream << "Unknown register named " << reg_name;
      error_msg = err_stream.str();
      return false;
    }
    (*regs)[entry->second] = value;
  }
  fclose(fp);
  return true;
}

std::unordered_map<std::string, uint32_t> OfflineUnwindUtils::arm_regs_ = {
    {"r0", ARM_REG_R0},  {"r1", ARM_REG_R1}, {"r2", ARM_REG_R2},   {"r3", ARM_REG_R3},
    {"r4", ARM_REG_R4},  {"r5", ARM_REG_R5}, {"r6", ARM_REG_R6},   {"r7", ARM_REG_R7},
    {"r8", ARM_REG_R8},  {"r9", ARM_REG_R9}, {"r10", ARM_REG_R10}, {"r11", ARM_REG_R11},
    {"ip", ARM_REG_R12}, {"sp", ARM_REG_SP}, {"lr", ARM_REG_LR},   {"pc", ARM_REG_PC},
};

std::unordered_map<std::string, uint32_t> OfflineUnwindUtils::arm64_regs_ = {
    {"x0", ARM64_REG_R0},      {"x1", ARM64_REG_R1},   {"x2", ARM64_REG_R2},
    {"x3", ARM64_REG_R3},      {"x4", ARM64_REG_R4},   {"x5", ARM64_REG_R5},
    {"x6", ARM64_REG_R6},      {"x7", ARM64_REG_R7},   {"x8", ARM64_REG_R8},
    {"x9", ARM64_REG_R9},      {"x10", ARM64_REG_R10}, {"x11", ARM64_REG_R11},
    {"x12", ARM64_REG_R12},    {"x13", ARM64_REG_R13}, {"x14", ARM64_REG_R14},
    {"x15", ARM64_REG_R15},    {"x16", ARM64_REG_R16}, {"x17", ARM64_REG_R17},
    {"x18", ARM64_REG_R18},    {"x19", ARM64_REG_R19}, {"x20", ARM64_REG_R20},
    {"x21", ARM64_REG_R21},    {"x22", ARM64_REG_R22}, {"x23", ARM64_REG_R23},
    {"x24", ARM64_REG_R24},    {"x25", ARM64_REG_R25}, {"x26", ARM64_REG_R26},
    {"x27", ARM64_REG_R27},    {"x28", ARM64_REG_R28}, {"x29", ARM64_REG_R29},
    {"sp", ARM64_REG_SP},      {"lr", ARM64_REG_LR},   {"pc", ARM64_REG_PC},
    {"pst", ARM64_REG_PSTATE},
};

std::unordered_map<std::string, uint32_t> OfflineUnwindUtils::x86_regs_ = {
    {"eax", X86_REG_EAX}, {"ebx", X86_REG_EBX}, {"ecx", X86_REG_ECX},
    {"edx", X86_REG_EDX}, {"ebp", X86_REG_EBP}, {"edi", X86_REG_EDI},
    {"esi", X86_REG_ESI}, {"esp", X86_REG_ESP}, {"eip", X86_REG_EIP},
};

std::unordered_map<std::string, uint32_t> OfflineUnwindUtils::x86_64_regs_ = {
    {"rax", X86_64_REG_RAX}, {"rbx", X86_64_REG_RBX}, {"rcx", X86_64_REG_RCX},
    {"rdx", X86_64_REG_RDX}, {"r8", X86_64_REG_R8},   {"r9", X86_64_REG_R9},
    {"r10", X86_64_REG_R10}, {"r11", X86_64_REG_R11}, {"r12", X86_64_REG_R12},
    {"r13", X86_64_REG_R13}, {"r14", X86_64_REG_R14}, {"r15", X86_64_REG_R15},
    {"rdi", X86_64_REG_RDI}, {"rsi", X86_64_REG_RSI}, {"rbp", X86_64_REG_RBP},
    {"rsp", X86_64_REG_RSP}, {"rip", X86_64_REG_RIP},
};

}  // namespace unwindstack