summaryrefslogtreecommitdiff
path: root/simpleperf/dso.cpp
blob: f3e9b2ce74afa03079eecfc3f088f0ba75134b1d (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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
 * Copyright (C) 2015 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 "dso.h"

#include <stdlib.h>
#include <string.h>

#include <algorithm>
#include <limits>
#include <vector>

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

#include "environment.h"
#include "read_apk.h"
#include "read_dex_file.h"
#include "read_elf.h"
#include "utils.h"

static OneTimeFreeAllocator symbol_name_allocator;

Symbol::Symbol(const std::string& name, uint64_t addr, uint64_t len)
    : addr(addr),
      len(len),
      name_(symbol_name_allocator.AllocateString(name)),
      demangled_name_(nullptr),
      dump_id_(UINT_MAX) {
}

const char* Symbol::DemangledName() const {
  if (demangled_name_ == nullptr) {
    const std::string s = Dso::Demangle(name_);
    if (s == name_) {
      demangled_name_ = name_;
    } else {
      demangled_name_ = symbol_name_allocator.AllocateString(s);
    }
  }
  return demangled_name_;
}

bool Dso::demangle_ = true;
std::string Dso::symfs_dir_;
std::string Dso::vmlinux_;
std::string Dso::kallsyms_;
bool Dso::read_kernel_symbols_from_proc_;
std::unordered_map<std::string, BuildId> Dso::build_id_map_;
size_t Dso::dso_count_;
uint32_t Dso::g_dump_id_;
std::string Dso::vdso_64bit_;
std::string Dso::vdso_32bit_;

void Dso::SetDemangle(bool demangle) { demangle_ = demangle; }

extern "C" char* __cxa_demangle(const char* mangled_name, char* buf, size_t* n,
                                int* status);

std::string Dso::Demangle(const std::string& name) {
  if (!demangle_) {
    return name;
  }
  int status;
  bool is_linker_symbol = (name.find(linker_prefix) == 0);
  const char* mangled_str = name.c_str();
  if (is_linker_symbol) {
    mangled_str += linker_prefix.size();
  }
  std::string result = name;
  char* demangled_name = __cxa_demangle(mangled_str, nullptr, nullptr, &status);
  if (status == 0) {
    if (is_linker_symbol) {
      result = std::string("[linker]") + demangled_name;
    } else {
      result = demangled_name;
    }
    free(demangled_name);
  } else if (is_linker_symbol) {
    result = std::string("[linker]") + mangled_str;
  }
  return result;
}

bool Dso::SetSymFsDir(const std::string& symfs_dir) {
  std::string dirname = symfs_dir;
  if (!dirname.empty()) {
    if (dirname.back() != '/') {
      dirname.push_back('/');
    }
    if (!IsDir(symfs_dir)) {
      LOG(ERROR) << "Invalid symfs_dir '" << symfs_dir << "'";
      return false;
    }
  }
  symfs_dir_ = dirname;
  return true;
}

void Dso::SetVmlinux(const std::string& vmlinux) { vmlinux_ = vmlinux; }

void Dso::SetBuildIds(
    const std::vector<std::pair<std::string, BuildId>>& build_ids) {
  std::unordered_map<std::string, BuildId> map;
  for (auto& pair : build_ids) {
    LOG(DEBUG) << "build_id_map: " << pair.first << ", "
               << pair.second.ToString();
    map.insert(pair);
  }
  build_id_map_ = std::move(map);
}

void Dso::SetVdsoFile(const std::string& vdso_file, bool is_64bit) {
  if (is_64bit) {
    vdso_64bit_ = vdso_file;
  } else {
    vdso_32bit_ = vdso_file;
  }
}

BuildId Dso::FindExpectedBuildIdForPath(const std::string& path) {
  auto it = build_id_map_.find(path);
  if (it != build_id_map_.end()) {
    return it->second;
  }
  return BuildId();
}

BuildId Dso::GetExpectedBuildId() {
  return FindExpectedBuildIdForPath(path_);
}

Dso::Dso(DsoType type, const std::string& path, const std::string& debug_file_path)
    : type_(type),
      path_(path),
      debug_file_path_(debug_file_path),
      is_loaded_(false),
      dump_id_(UINT_MAX),
      symbol_dump_id_(0),
      symbol_warning_loglevel_(android::base::WARNING) {
  size_t pos = path.find_last_of("/\\");
  if (pos != std::string::npos) {
    file_name_ = path.substr(pos + 1);
  } else {
    file_name_ = path;
  }
  dso_count_++;
}

Dso::~Dso() {
  if (--dso_count_ == 0) {
    // Clean up global variables when no longer used.
    symbol_name_allocator.Clear();
    demangle_ = true;
    symfs_dir_.clear();
    vmlinux_.clear();
    kallsyms_.clear();
    read_kernel_symbols_from_proc_ = false;
    build_id_map_.clear();
    g_dump_id_ = 0;
  }
}

uint32_t Dso::CreateDumpId() {
  CHECK(!HasDumpId());
  return dump_id_ = g_dump_id_++;
}

uint32_t Dso::CreateSymbolDumpId(const Symbol* symbol) {
  CHECK(!symbol->HasDumpId());
  symbol->dump_id_ = symbol_dump_id_++;
  return symbol->dump_id_;
}

const Symbol* Dso::FindSymbol(uint64_t vaddr_in_dso) {
  if (!is_loaded_) {
    Load();
  }
  auto it = std::upper_bound(symbols_.begin(), symbols_.end(),
                             Symbol("", vaddr_in_dso, 0),
                             Symbol::CompareValueByAddr);
  if (it != symbols_.begin()) {
    --it;
    if (it->addr <= vaddr_in_dso && (it->addr + it->len > vaddr_in_dso)) {
      return &*it;
    }
  }
  if (!unknown_symbols_.empty()) {
    auto it = unknown_symbols_.find(vaddr_in_dso);
    if (it != unknown_symbols_.end()) {
      return &it->second;
    }
  }
  return nullptr;
}

void Dso::SetSymbols(std::vector<Symbol>* symbols) {
  symbols_ = std::move(*symbols);
  symbols->clear();
}

void Dso::AddUnknownSymbol(uint64_t vaddr_in_dso, const std::string& name) {
  unknown_symbols_.insert(std::make_pair(vaddr_in_dso, Symbol(name, vaddr_in_dso, 1)));
}

void Dso::Load() {
  is_loaded_ = true;
  std::vector<Symbol> symbols = LoadSymbols();
  if (symbols_.empty()) {
    symbols_ = std::move(symbols);
  } else {
    std::vector<Symbol> merged_symbols;
    std::set_union(symbols_.begin(), symbols_.end(), symbols.begin(), symbols.end(),
                   std::back_inserter(merged_symbols), Symbol::CompareValueByAddr);
    symbols_ = std::move(merged_symbols);
  }
}

static void ReportReadElfSymbolResult(ElfStatus result, const std::string& path,
    const std::string& debug_file_path,
    android::base::LogSeverity warning_loglevel = android::base::WARNING) {
  if (result == ElfStatus::NO_ERROR) {
    LOG(VERBOSE) << "Read symbols from " << debug_file_path << " successfully";
  } else if (result == ElfStatus::NO_SYMBOL_TABLE) {
    if (path == "[vdso]") {
      // Vdso only contains dynamic symbol table, and we can't change that.
      return;
    }
    // Lacking symbol table isn't considered as an error but worth reporting.
    LOG(warning_loglevel) << debug_file_path << " doesn't contain symbol table";
  } else {
    LOG(warning_loglevel) << "failed to read symbols from " << debug_file_path << ": " << result;
  }
}

static void SortAndFixSymbols(std::vector<Symbol>& symbols) {
  std::sort(symbols.begin(), symbols.end(), Symbol::CompareValueByAddr);
  Symbol* prev_symbol = nullptr;
  for (auto& symbol : symbols) {
    if (prev_symbol != nullptr && prev_symbol->len == 0) {
      prev_symbol->len = symbol.addr - prev_symbol->addr;
    }
    prev_symbol = &symbol;
  }
}

class ElfDso : public Dso {
 public:
  ElfDso(const std::string& path, const std::string& debug_file_path)
      : Dso(DSO_ELF_FILE, path, debug_file_path),
        min_vaddr_(std::numeric_limits<uint64_t>::max()) {}

  uint64_t MinVirtualAddress() override {
    if (min_vaddr_ == std::numeric_limits<uint64_t>::max()) {
      min_vaddr_ = 0;
      if (type_ == DSO_ELF_FILE) {
        BuildId build_id = GetExpectedBuildId();

        uint64_t addr;
        ElfStatus result = ReadMinExecutableVirtualAddressFromElfFile(
            GetDebugFilePath(), build_id, &addr);
        if (result != ElfStatus::NO_ERROR) {
          LOG(WARNING) << "failed to read min virtual address of "
                       << GetDebugFilePath() << ": " << result;
        } else {
          min_vaddr_ = addr;
        }
      }
    }
    return min_vaddr_;
  }

  void SetMinVirtualAddress(uint64_t min_vaddr) override {
    min_vaddr_ = min_vaddr;
  }

 protected:
  std::vector<Symbol> LoadSymbols() override {
    std::vector<Symbol> symbols;
    BuildId build_id = GetExpectedBuildId();
    auto symbol_callback = [&](const ElfFileSymbol& symbol) {
      if (symbol.is_func || (symbol.is_label && symbol.is_in_text_section)) {
        symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
      }
    };
    ElfStatus status;
    std::tuple<bool, std::string, std::string> tuple = SplitUrlInApk(debug_file_path_);
    if (std::get<0>(tuple)) {
      status = ParseSymbolsFromApkFile(std::get<1>(tuple), std::get<2>(tuple), build_id,
                                       symbol_callback);
    } else {
      status = ParseSymbolsFromElfFile(debug_file_path_, build_id, symbol_callback);
    }
    ReportReadElfSymbolResult(status, path_, debug_file_path_,
                              symbols_.empty() ? android::base::WARNING : android::base::DEBUG);
    SortAndFixSymbols(symbols);
    return symbols;
  }

 private:
  uint64_t min_vaddr_;
};

class KernelDso : public Dso {
 public:
  KernelDso(const std::string& path, const std::string& debug_file_path)
      : Dso(DSO_KERNEL, path, debug_file_path) {}

 protected:
  std::vector<Symbol> LoadSymbols() override {
    std::vector<Symbol> symbols;
    BuildId build_id = GetExpectedBuildId();
    if (!vmlinux_.empty()) {
      auto symbol_callback = [&](const ElfFileSymbol& symbol) {
        if (symbol.is_func) {
          symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
        }
      };
      ElfStatus status = ParseSymbolsFromElfFile(vmlinux_, build_id, symbol_callback);
      ReportReadElfSymbolResult(status, path_, vmlinux_);
    } else if (!kallsyms_.empty()) {
      symbols = ReadSymbolsFromKallsyms(kallsyms_);
    } else if (read_kernel_symbols_from_proc_ || !build_id.IsEmpty()) {
      // Try /proc/kallsyms only when asked to do so, or when build id matches.
      // Otherwise, it is likely to use /proc/kallsyms on host for perf.data recorded on device.
      bool can_read_kallsyms = true;
      if (!build_id.IsEmpty()) {
        BuildId real_build_id;
        if (!GetKernelBuildId(&real_build_id) || build_id != real_build_id) {
          LOG(DEBUG) << "failed to read symbols from /proc/kallsyms: Build id mismatch";
          can_read_kallsyms = false;
        }
      }
      if (can_read_kallsyms) {
        std::string kallsyms;
        if (!android::base::ReadFileToString("/proc/kallsyms", &kallsyms)) {
          LOG(DEBUG) << "failed to read /proc/kallsyms";
        } else {
          symbols = ReadSymbolsFromKallsyms(kallsyms);
        }
      }
    }
    SortAndFixSymbols(symbols);
    if (!symbols.empty()) {
      symbols.back().len = std::numeric_limits<uint64_t>::max() - symbols.back().addr;
    }
    return symbols;
  }

 private:
  std::vector<Symbol> ReadSymbolsFromKallsyms(std::string& kallsyms) {
    std::vector<Symbol> symbols;
    auto symbol_callback = [&](const KernelSymbol& symbol) {
      if (strchr("TtWw", symbol.type) && symbol.addr != 0u) {
        symbols.emplace_back(symbol.name, symbol.addr, 0);
      }
      return false;
    };
    ProcessKernelSymbols(kallsyms, symbol_callback);
    if (symbols.empty()) {
      LOG(WARNING) << "Symbol addresses in /proc/kallsyms on device are all zero. "
                      "`echo 0 >/proc/sys/kernel/kptr_restrict` if possible.";
    }
    return symbols;
  }
};

class KernelModuleDso : public Dso {
 public:
  KernelModuleDso(const std::string& path, const std::string& debug_file_path)
      : Dso(DSO_KERNEL_MODULE, path, debug_file_path) {}

 protected:
  std::vector<Symbol> LoadSymbols() override {
    std::vector<Symbol> symbols;
    BuildId build_id = GetExpectedBuildId();
    auto symbol_callback = [&](const ElfFileSymbol& symbol) {
      if (symbol.is_func || symbol.is_in_text_section) {
        symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
      }
    };
    ElfStatus status = ParseSymbolsFromElfFile(debug_file_path_, build_id, symbol_callback);
    ReportReadElfSymbolResult(status, path_, debug_file_path_,
                              symbols_.empty() ? android::base::WARNING : android::base::DEBUG);
    SortAndFixSymbols(symbols);
    return symbols;
  }
};

std::unique_ptr<Dso> Dso::CreateDso(DsoType dso_type, const std::string& dso_path,
                                    bool force_64bit) {
  auto find_debug_file = [&]() {
    // Check if file matching path_ exists in symfs directory before using it as
    // debug_file_path_.
    if (!symfs_dir_.empty()) {
      std::string path_in_symfs = symfs_dir_ + dso_path;
      std::tuple<bool, std::string, std::string> tuple = SplitUrlInApk(path_in_symfs);
      std::string file_path = std::get<0>(tuple) ? std::get<1>(tuple) : path_in_symfs;
      if (IsRegularFile(file_path)) {
        return path_in_symfs;
      }
    } else if (dso_path == "[vdso]") {
      if (force_64bit && !vdso_64bit_.empty()) {
        return vdso_64bit_;
      } else if (!force_64bit && !vdso_32bit_.empty()) {
        return vdso_32bit_;
      }
    } else if (dso_type == DSO_ELF_FILE) {
      // Linux host can store debug shared libraries in /usr/lib/debug.
      std::string path = "/usr/lib/debug" + dso_path;
      if (IsRegularFile(path)) {
        return path;
      }
    }
    return dso_path;
  };

  switch (dso_type) {
    case DSO_ELF_FILE:
      return std::unique_ptr<Dso>(new ElfDso(dso_path, find_debug_file()));
    case DSO_KERNEL:
      return std::unique_ptr<Dso>(new KernelDso(dso_path, dso_path));
    case DSO_KERNEL_MODULE:
      return std::unique_ptr<Dso>(new KernelModuleDso(dso_path, find_debug_file()));
    case DSO_DEX_FILE:
      return std::unique_ptr<Dso>(new DexFileDso(dso_path, find_debug_file()));
    default:
      LOG(FATAL) << "Unexpected dso_type " << static_cast<int>(dso_type);
  }
  return nullptr;
}

std::vector<Symbol> DexFileDso::LoadSymbols() {
  std::vector<Symbol> symbols;
  std::vector<DexFileSymbol> dex_file_symbols;
  if (!ReadSymbolsFromDexFile(debug_file_path_, dex_file_offsets_, &dex_file_symbols)) {
    android::base::LogSeverity level = symbols_.empty() ? android::base::WARNING
                                                        : android::base::DEBUG;
    LOG(level) << "Failed to read symbols from " << debug_file_path_;
    return symbols;
  }
  LOG(VERBOSE) << "Read symbols from " << debug_file_path_ << " successfully";
  for (auto& symbol : dex_file_symbols) {
    symbols.emplace_back(symbol.name, symbol.offset, symbol.len);
  }
  SortAndFixSymbols(symbols);
  return symbols;
}

const char* DsoTypeToString(DsoType dso_type) {
  switch (dso_type) {
    case DSO_KERNEL:
      return "dso_kernel";
    case DSO_KERNEL_MODULE:
      return "dso_kernel_module";
    case DSO_ELF_FILE:
      return "dso_elf_file";
    case DSO_DEX_FILE:
      return "dso_dex_file";
    default:
      return "unknown";
  }
}