blob: e953acff2b9e57ed239e259bea063bc33a018e48 [file] [log] [blame]
Yabin Cuiec12ed92015-06-08 10:38:10 -07001/*
2 * Copyright (C) 2015 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 "dso.h"
18
Yabin Cuib3783552015-06-11 11:15:42 -070019#include <stdlib.h>
Yabin Cuicc2e59e2015-08-21 14:23:43 -070020#include <string.h>
Yabin Cuic8485602015-08-20 15:04:39 -070021
Yabin Cuicc2e59e2015-08-21 14:23:43 -070022#include <algorithm>
Yabin Cuic8485602015-08-20 15:04:39 -070023#include <limits>
Yabin Cuidd401b32018-04-11 11:17:06 -070024#include <memory>
Yabin Cui7078c672020-11-10 16:24:12 -080025#include <optional>
Yabin Cui9ba4d942020-09-08 16:12:46 -070026#include <string_view>
Yabin Cuicc2e59e2015-08-21 14:23:43 -070027#include <vector>
Yabin Cuic8485602015-08-20 15:04:39 -070028
Yabin Cuib4212972016-05-25 14:08:05 -070029#include <android-base/file.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080030#include <android-base/logging.h>
Yabin Cui40b70ff2018-04-09 14:06:08 -070031#include <android-base/strings.h>
Yabin Cuic8485602015-08-20 15:04:39 -070032
Yabin Cui075dd182020-08-05 19:51:36 +000033#include "JITDebugReader.h"
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +020034#include "environment.h"
ThiƩbaud Weksteene7e750e2020-11-19 15:07:46 +010035#include "kallsyms.h"
Yabin Cuib1a885b2016-02-14 19:18:02 -080036#include "read_apk.h"
Yabin Cui516a87c2018-03-26 17:34:00 -070037#include "read_dex_file.h"
Yabin Cuiec12ed92015-06-08 10:38:10 -070038#include "read_elf.h"
Yabin Cuib3783552015-06-11 11:15:42 -070039#include "utils.h"
Yabin Cuiec12ed92015-06-08 10:38:10 -070040
Yabin Cuifaa7b922021-01-11 17:35:57 -080041namespace simpleperf {
42
Yabin Cui075dd182020-08-05 19:51:36 +000043using android::base::EndsWith;
Yabin Cui9ba4d942020-09-08 16:12:46 -070044using android::base::StartsWith;
Yabin Cui3a880452020-06-29 16:37:31 -070045
Yabin Cui40b70ff2018-04-09 14:06:08 -070046namespace simpleperf_dso_impl {
47
Yabin Cui1b9b1c12018-10-29 14:23:48 -070048std::string RemovePathSeparatorSuffix(const std::string& path) {
49 // Don't remove path separator suffix for '/'.
Yabin Cui075dd182020-08-05 19:51:36 +000050 if (EndsWith(path, OS_PATH_SEPARATOR) && path.size() > 1u) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -070051 return path.substr(0, path.size() - 1);
52 }
53 return path;
54}
55
Yabin Cui40b70ff2018-04-09 14:06:08 -070056void DebugElfFileFinder::Reset() {
Yabin Cui0bf695b2024-08-22 15:41:29 -070057 allow_mismatched_build_id_ = false;
Yabin Cui40b70ff2018-04-09 14:06:08 -070058 vdso_64bit_.clear();
59 vdso_32bit_.clear();
60 symfs_dir_.clear();
61 build_id_to_file_map_.clear();
62}
63
64bool DebugElfFileFinder::SetSymFsDir(const std::string& symfs_dir) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -070065 symfs_dir_ = RemovePathSeparatorSuffix(symfs_dir);
66 if (!IsDir(symfs_dir_)) {
67 LOG(ERROR) << "Invalid symfs_dir '" << symfs_dir_ << "'";
68 return false;
Yabin Cui40b70ff2018-04-09 14:06:08 -070069 }
Yabin Cui1b9b1c12018-10-29 14:23:48 -070070 std::string build_id_list_file = symfs_dir_ + OS_PATH_SEPARATOR + "build_id_list";
Yabin Cui40b70ff2018-04-09 14:06:08 -070071 std::string build_id_list;
72 if (android::base::ReadFileToString(build_id_list_file, &build_id_list)) {
73 for (auto& line : android::base::Split(build_id_list, "\n")) {
Yabin Cui2969a9e2018-04-19 17:06:24 -070074 std::vector<std::string> items = android::base::Split(line, "=");
Yabin Cui40b70ff2018-04-09 14:06:08 -070075 if (items.size() == 2u) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -070076 build_id_to_file_map_[items[0]] = symfs_dir_ + OS_PATH_SEPARATOR + items[1];
Yabin Cui40b70ff2018-04-09 14:06:08 -070077 }
78 }
79 }
80 return true;
81}
82
Yabin Cui3939b9d2018-07-20 17:12:13 -070083bool DebugElfFileFinder::AddSymbolDir(const std::string& symbol_dir) {
84 if (!IsDir(symbol_dir)) {
85 LOG(ERROR) << "Invalid symbol dir " << symbol_dir;
86 return false;
87 }
Yabin Cui1b9b1c12018-10-29 14:23:48 -070088 std::string dir = RemovePathSeparatorSuffix(symbol_dir);
Yabin Cui3939b9d2018-07-20 17:12:13 -070089 CollectBuildIdInDir(dir);
90 return true;
91}
92
93void DebugElfFileFinder::CollectBuildIdInDir(const std::string& dir) {
94 for (const std::string& entry : GetEntriesInDir(dir)) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -070095 std::string path = dir + OS_PATH_SEPARATOR + entry;
Yabin Cui3939b9d2018-07-20 17:12:13 -070096 if (IsDir(path)) {
97 CollectBuildIdInDir(path);
98 } else {
99 BuildId build_id;
Yabin Cui3a880452020-06-29 16:37:31 -0700100 ElfStatus status;
101 auto elf = ElfFile::Open(path, &status);
Yabin Cuiab9cb232024-09-05 14:45:54 -0700102 if (status == ElfStatus::NO_ERROR) {
103 if (elf->GetBuildId(&build_id) == ElfStatus::NO_ERROR) {
104 build_id_to_file_map_[build_id.ToString()] = path;
105 } else {
106 no_build_id_files_.emplace_back(std::move(path));
107 }
Yabin Cui3939b9d2018-07-20 17:12:13 -0700108 }
109 }
110 }
111}
112
Yabin Cui40b70ff2018-04-09 14:06:08 -0700113void DebugElfFileFinder::SetVdsoFile(const std::string& vdso_file, bool is_64bit) {
114 if (is_64bit) {
115 vdso_64bit_ = vdso_file;
116 } else {
117 vdso_32bit_ = vdso_file;
118 }
119}
120
Yabin Cui0bf695b2024-08-22 15:41:29 -0700121bool DebugElfFileFinder::CheckDebugFilePath(const std::string& path, BuildId& build_id,
122 bool report_build_id_mismatch) {
Yabin Cui991477b2020-07-17 16:12:15 -0700123 ElfStatus status;
124 auto elf = ElfFile::Open(path, &status);
125 if (!elf) {
126 return false;
127 }
128 BuildId debug_build_id;
129 status = elf->GetBuildId(&debug_build_id);
130 if (status != ElfStatus::NO_ERROR && status != ElfStatus::NO_BUILD_ID) {
131 return false;
132 }
133
Yabin Cui0bf695b2024-08-22 15:41:29 -0700134 if (allow_mismatched_build_id_) {
135 return true;
136 }
137
Yabin Cui991477b2020-07-17 16:12:15 -0700138 // Native libraries in apks and kernel modules may not have build ids.
139 // So build_id and debug_build_id can either be empty, or have the same value.
140 bool match = build_id == debug_build_id;
141 if (!match && report_build_id_mismatch) {
142 LOG(WARNING) << path << " isn't used because of build id mismatch: expected " << build_id
143 << ", real " << debug_build_id;
144 }
145 return match;
146}
147
Yabin Cui40b70ff2018-04-09 14:06:08 -0700148std::string DebugElfFileFinder::FindDebugFile(const std::string& dso_path, bool force_64bit,
149 BuildId& build_id) {
150 if (dso_path == "[vdso]") {
151 if (force_64bit && !vdso_64bit_.empty()) {
152 return vdso_64bit_;
153 } else if (!force_64bit && !vdso_32bit_.empty()) {
154 return vdso_32bit_;
155 }
Yabin Cui3939b9d2018-07-20 17:12:13 -0700156 }
Yabin Cuid347bb42019-11-14 15:24:07 -0800157 if (build_id.IsEmpty()) {
158 // Try reading build id from file if we don't already have one.
159 GetBuildIdFromDsoPath(dso_path, &build_id);
160 }
Yabin Cui3939b9d2018-07-20 17:12:13 -0700161
Yabin Cui5d269c72019-05-31 15:30:17 -0700162 // 1. Try build_id_to_file_map.
163 if (!build_id_to_file_map_.empty()) {
Yabin Cui0bf695b2024-08-22 15:41:29 -0700164 if (!build_id.IsEmpty()) {
Yabin Cui5d269c72019-05-31 15:30:17 -0700165 auto it = build_id_to_file_map_.find(build_id.ToString());
Yabin Cui991477b2020-07-17 16:12:15 -0700166 if (it != build_id_to_file_map_.end() && CheckDebugFilePath(it->second, build_id, false)) {
Yabin Cui5d269c72019-05-31 15:30:17 -0700167 return it->second;
168 }
169 }
Yabin Cuiab9cb232024-09-05 14:45:54 -0700170 }
171 if (allow_mismatched_build_id_) {
172 std::optional<std::string> s = SearchFileMapByPath(dso_path);
173 if (s.has_value()) {
174 return s.value();
Yabin Cui0bf695b2024-08-22 15:41:29 -0700175 }
Yabin Cui5d269c72019-05-31 15:30:17 -0700176 }
Yabin Cui1b9b1c12018-10-29 14:23:48 -0700177 if (!symfs_dir_.empty()) {
Yabin Cuia4496ad2019-11-18 16:40:28 -0800178 // 2. Try concatenating symfs_dir and dso_path.
Yabin Cui1b9b1c12018-10-29 14:23:48 -0700179 std::string path = GetPathInSymFsDir(dso_path);
Yabin Cui991477b2020-07-17 16:12:15 -0700180 if (CheckDebugFilePath(path, build_id, true)) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -0700181 return path;
182 }
Christopher Ferris56a3fa12021-10-12 17:23:30 -0700183 if (EndsWith(dso_path, ".apk") && IsRegularFile(path)) {
184 return path;
185 }
Yabin Cuia4496ad2019-11-18 16:40:28 -0800186 // 3. Try concatenating symfs_dir and basename of dso_path.
187 path = symfs_dir_ + OS_PATH_SEPARATOR + android::base::Basename(dso_path);
Yabin Cui991477b2020-07-17 16:12:15 -0700188 if (CheckDebugFilePath(path, build_id, false)) {
Yabin Cuia4496ad2019-11-18 16:40:28 -0800189 return path;
190 }
Yabin Cui3939b9d2018-07-20 17:12:13 -0700191 }
Yabin Cuia4496ad2019-11-18 16:40:28 -0800192 // 4. Try concatenating /usr/lib/debug and dso_path.
Yabin Cui3939b9d2018-07-20 17:12:13 -0700193 // Linux host can store debug shared libraries in /usr/lib/debug.
Yabin Cui991477b2020-07-17 16:12:15 -0700194 if (CheckDebugFilePath("/usr/lib/debug" + dso_path, build_id, false)) {
Yabin Cui3939b9d2018-07-20 17:12:13 -0700195 return "/usr/lib/debug" + dso_path;
196 }
Yabin Cui40b70ff2018-04-09 14:06:08 -0700197 return dso_path;
198}
Yabin Cui1b9b1c12018-10-29 14:23:48 -0700199
200std::string DebugElfFileFinder::GetPathInSymFsDir(const std::string& path) {
201 auto add_symfs_prefix = [&](const std::string& path) {
Yabin Cui9ba4d942020-09-08 16:12:46 -0700202 if (StartsWith(path, OS_PATH_SEPARATOR)) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -0700203 return symfs_dir_ + path;
204 }
205 return symfs_dir_ + OS_PATH_SEPARATOR + path;
206 };
207 if (OS_PATH_SEPARATOR == '/') {
208 return add_symfs_prefix(path);
209 }
210 // Paths in recorded perf.data uses '/' as path separator. When reporting on Windows, it needs
211 // to be converted to '\\'.
212 auto tuple = SplitUrlInApk(path);
213 if (std::get<0>(tuple)) {
214 std::string apk_path = std::get<1>(tuple);
215 std::string entry_path = std::get<2>(tuple);
216 std::replace(apk_path.begin(), apk_path.end(), '/', OS_PATH_SEPARATOR);
217 return GetUrlInApk(add_symfs_prefix(apk_path), entry_path);
218 }
219 std::string elf_path = path;
220 std::replace(elf_path.begin(), elf_path.end(), '/', OS_PATH_SEPARATOR);
221 return add_symfs_prefix(elf_path);
222}
Yabin Cui0bf695b2024-08-22 15:41:29 -0700223
Yabin Cuid8bd4482024-10-01 13:14:55 -0700224std::optional<std::string> DebugElfFileFinder::SearchFileMapByPath(std::string_view path) {
225 if (path == "[kernel.kallsyms]") {
226 path = "vmlinux";
227 }
228 std::string_view filename;
229 if (size_t pos = path.rfind('/'); pos != path.npos) {
Yabin Cui0bf695b2024-08-22 15:41:29 -0700230 filename = path.substr(pos + 1);
231 } else {
232 filename = path;
233 }
234 std::string best_elf_file;
235 size_t best_match_length = 0;
Yabin Cuiab9cb232024-09-05 14:45:54 -0700236 auto check_file = [&](const std::string& elf_file) {
Yabin Cui0bf695b2024-08-22 15:41:29 -0700237 if (EndsWith(elf_file, filename)) {
238 size_t i = elf_file.size();
239 size_t j = path.size();
240 while (i > 0 && j > 0 && elf_file[i - 1] == path[j - 1]) {
241 i--;
242 j--;
243 }
244 size_t match_length = elf_file.size() - i;
245 if (match_length > best_match_length) {
246 best_elf_file = elf_file;
247 best_match_length = match_length;
248 }
249 }
Yabin Cuiab9cb232024-09-05 14:45:54 -0700250 };
251
252 for (const auto& p : build_id_to_file_map_) {
253 check_file(p.second);
254 }
255 for (const auto& elf_file : no_build_id_files_) {
256 check_file(elf_file);
Yabin Cui0bf695b2024-08-22 15:41:29 -0700257 }
258 if (!best_elf_file.empty()) {
259 LOG(INFO) << "Found " << best_elf_file << " for " << path << " by filename";
260 return best_elf_file;
261 }
262 return std::nullopt;
263}
264
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200265} // namespace simpleperf_dso_impl
Yabin Cui40b70ff2018-04-09 14:06:08 -0700266
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700267static OneTimeFreeAllocator symbol_name_allocator;
268
Martin Stjernholm7c27cc22018-11-28 00:46:00 +0000269Symbol::Symbol(std::string_view name, uint64_t addr, uint64_t len)
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700270 : addr(addr),
271 len(len),
272 name_(symbol_name_allocator.AllocateString(name)),
Yabin Cui767dd172016-06-02 21:02:43 -0700273 demangled_name_(nullptr),
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200274 dump_id_(UINT_MAX) {}
Yabin Cuib10a8fb2015-08-18 16:32:18 -0700275
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700276const char* Symbol::DemangledName() const {
277 if (demangled_name_ == nullptr) {
278 const std::string s = Dso::Demangle(name_);
Yabin Cui40eef9e2021-04-13 13:08:31 -0700279 SetDemangledName(s);
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700280 }
281 return demangled_name_;
Yabin Cuiec12ed92015-06-08 10:38:10 -0700282}
283
Yabin Cui40eef9e2021-04-13 13:08:31 -0700284void Symbol::SetDemangledName(std::string_view name) const {
285 if (name == name_) {
286 demangled_name_ = name_;
287 } else {
288 demangled_name_ = symbol_name_allocator.AllocateString(name);
289 }
290}
291
Yabin Cuifef95142021-08-19 10:51:00 -0700292std::string_view Symbol::FunctionName() const {
Yabin Cui1e16b202021-08-16 13:37:35 -0700293 // Name with signature is like "void ctep.v(cteo, ctgc, ctbn)".
294 std::string_view name = DemangledName();
295 auto brace_pos = name.find('(');
296 if (brace_pos != name.npos) {
297 name = name.substr(0, brace_pos);
298 auto space_pos = name.rfind(' ');
299 if (space_pos != name.npos) {
300 name = name.substr(space_pos + 1);
301 }
302 }
303 return name;
304}
305
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800306static bool CompareSymbolToAddr(const Symbol& s, uint64_t addr) {
307 return s.addr < addr;
308}
309
310static bool CompareAddrToSymbol(uint64_t addr, const Symbol& s) {
311 return addr < s.addr;
312}
313
Yabin Cuic8485602015-08-20 15:04:39 -0700314bool Dso::demangle_ = true;
Yabin Cuic8485602015-08-20 15:04:39 -0700315std::string Dso::vmlinux_;
Yabin Cuib4212972016-05-25 14:08:05 -0700316std::string Dso::kallsyms_;
Yabin Cuic8485602015-08-20 15:04:39 -0700317std::unordered_map<std::string, BuildId> Dso::build_id_map_;
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700318size_t Dso::dso_count_;
Yabin Cui16501ff2016-10-19 15:06:29 -0700319uint32_t Dso::g_dump_id_;
Yabin Cui40b70ff2018-04-09 14:06:08 -0700320simpleperf_dso_impl::DebugElfFileFinder Dso::debug_elf_file_finder_;
Yabin Cuiba50c4b2015-07-21 11:24:48 -0700321
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200322void Dso::SetDemangle(bool demangle) {
323 demangle_ = demangle;
324}
Yabin Cuib3783552015-06-11 11:15:42 -0700325
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200326extern "C" char* __cxa_demangle(const char* mangled_name, char* buf, size_t* n, int* status);
Yabin Cui4d8137f2023-02-14 17:00:25 -0800327#if defined(__linux__) || defined(__darwin__)
328extern "C" char* rustc_demangle(const char* mangled, char* out, size_t* len, int* status);
329#endif
Yabin Cuib10a8fb2015-08-18 16:32:18 -0700330
Yabin Cuic8485602015-08-20 15:04:39 -0700331std::string Dso::Demangle(const std::string& name) {
Yabin Cuib10a8fb2015-08-18 16:32:18 -0700332 if (!demangle_) {
333 return name;
334 }
335 int status;
336 bool is_linker_symbol = (name.find(linker_prefix) == 0);
337 const char* mangled_str = name.c_str();
338 if (is_linker_symbol) {
339 mangled_str += linker_prefix.size();
340 }
Yabin Cui4d8137f2023-02-14 17:00:25 -0800341
342 if (mangled_str[0] == '_') {
343 char* demangled_name = nullptr;
344 int status = -2; // -2 means name didn't demangle.
345 if (mangled_str[1] == 'Z') {
346 demangled_name = __cxa_demangle(mangled_str, nullptr, nullptr, &status);
347#if defined(__linux__) || defined(__darwin__)
348 } else if (mangled_str[1] == 'R') {
349 demangled_name = rustc_demangle(mangled_str, nullptr, nullptr, &status);
350#endif
Yabin Cuib10a8fb2015-08-18 16:32:18 -0700351 }
Yabin Cui4d8137f2023-02-14 17:00:25 -0800352 if (status == 0) {
353 // demangled successfully
354 std::string result;
355 if (is_linker_symbol) {
356 result = std::string("[linker]") + demangled_name;
357 } else {
358 result = demangled_name;
359 }
360 free(demangled_name);
361 return result;
362 }
Yabin Cuib10a8fb2015-08-18 16:32:18 -0700363 }
Yabin Cui4d8137f2023-02-14 17:00:25 -0800364
365 // failed to demangle
366 if (is_linker_symbol) {
367 return std::string("[linker]") + mangled_str;
368 }
369 return name;
Yabin Cuib10a8fb2015-08-18 16:32:18 -0700370}
371
Yabin Cuic8485602015-08-20 15:04:39 -0700372bool Dso::SetSymFsDir(const std::string& symfs_dir) {
Yabin Cui40b70ff2018-04-09 14:06:08 -0700373 return debug_elf_file_finder_.SetSymFsDir(symfs_dir);
Yabin Cuic8485602015-08-20 15:04:39 -0700374}
375
Yabin Cui3939b9d2018-07-20 17:12:13 -0700376bool Dso::AddSymbolDir(const std::string& symbol_dir) {
377 return debug_elf_file_finder_.AddSymbolDir(symbol_dir);
378}
379
Yabin Cui0bf695b2024-08-22 15:41:29 -0700380void Dso::AllowMismatchedBuildId() {
381 return debug_elf_file_finder_.AllowMismatchedBuildId();
382}
383
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200384void Dso::SetVmlinux(const std::string& vmlinux) {
385 vmlinux_ = vmlinux;
386}
Yabin Cuic8485602015-08-20 15:04:39 -0700387
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200388void Dso::SetBuildIds(const std::vector<std::pair<std::string, BuildId>>& build_ids) {
Yabin Cuic8485602015-08-20 15:04:39 -0700389 std::unordered_map<std::string, BuildId> map;
390 for (auto& pair : build_ids) {
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200391 LOG(DEBUG) << "build_id_map: " << pair.first << ", " << pair.second.ToString();
Yabin Cuic8485602015-08-20 15:04:39 -0700392 map.insert(pair);
393 }
394 build_id_map_ = std::move(map);
395}
396
Yabin Cuic68e66d2018-03-07 15:47:15 -0800397void Dso::SetVdsoFile(const std::string& vdso_file, bool is_64bit) {
Yabin Cui40b70ff2018-04-09 14:06:08 -0700398 debug_elf_file_finder_.SetVdsoFile(vdso_file, is_64bit);
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700399}
400
Yabin Cui52c63692016-11-28 17:28:08 -0800401BuildId Dso::FindExpectedBuildIdForPath(const std::string& path) {
402 auto it = build_id_map_.find(path);
Yabin Cuic8485602015-08-20 15:04:39 -0700403 if (it != build_id_map_.end()) {
404 return it->second;
405 }
406 return BuildId();
407}
408
Yabin Cui11424c42022-03-10 16:04:04 -0800409BuildId Dso::GetExpectedBuildId() const {
Yabin Cui52c63692016-11-28 17:28:08 -0800410 return FindExpectedBuildIdForPath(path_);
411}
412
Yabin Cui11424c42022-03-10 16:04:04 -0800413Dso::Dso(DsoType type, const std::string& path)
Yabin Cui767dd172016-06-02 21:02:43 -0700414 : type_(type),
Yabin Cui767dd172016-06-02 21:02:43 -0700415 path_(path),
Yabin Cui767dd172016-06-02 21:02:43 -0700416 is_loaded_(false),
Yabin Cui16501ff2016-10-19 15:06:29 -0700417 dump_id_(UINT_MAX),
Yabin Cuie466d4d2017-08-11 17:03:07 -0700418 symbol_dump_id_(0),
419 symbol_warning_loglevel_(android::base::WARNING) {
Yabin Cui15475e62016-07-14 13:26:19 -0700420 size_t pos = path.find_last_of("/\\");
421 if (pos != std::string::npos) {
422 file_name_ = path.substr(pos + 1);
423 } else {
424 file_name_ = path;
425 }
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700426 dso_count_++;
Yabin Cuic8485602015-08-20 15:04:39 -0700427}
428
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700429Dso::~Dso() {
430 if (--dso_count_ == 0) {
Yabin Cuib4212972016-05-25 14:08:05 -0700431 // Clean up global variables when no longer used.
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700432 symbol_name_allocator.Clear();
Yabin Cuib4212972016-05-25 14:08:05 -0700433 demangle_ = true;
Yabin Cuib4212972016-05-25 14:08:05 -0700434 vmlinux_.clear();
435 kallsyms_.clear();
436 build_id_map_.clear();
Yabin Cui16501ff2016-10-19 15:06:29 -0700437 g_dump_id_ = 0;
Yabin Cui40b70ff2018-04-09 14:06:08 -0700438 debug_elf_file_finder_.Reset();
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700439 }
440}
441
Yabin Cui16501ff2016-10-19 15:06:29 -0700442uint32_t Dso::CreateDumpId() {
443 CHECK(!HasDumpId());
444 return dump_id_ = g_dump_id_++;
445}
446
447uint32_t Dso::CreateSymbolDumpId(const Symbol* symbol) {
448 CHECK(!symbol->HasDumpId());
449 symbol->dump_id_ = symbol_dump_id_++;
450 return symbol->dump_id_;
451}
452
Yabin Cui7078c672020-11-10 16:24:12 -0800453std::optional<uint64_t> Dso::IpToFileOffset(uint64_t ip, uint64_t map_start, uint64_t map_pgoff) {
454 return ip - map_start + map_pgoff;
455}
456
Yabin Cui547c60e2015-10-12 16:56:05 -0700457const Symbol* Dso::FindSymbol(uint64_t vaddr_in_dso) {
Yabin Cuic8485602015-08-20 15:04:39 -0700458 if (!is_loaded_) {
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800459 LoadSymbols();
Yabin Cuic5b4a312016-10-24 13:38:38 -0700460 }
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800461 auto it = std::upper_bound(symbols_.begin(), symbols_.end(), vaddr_in_dso, CompareAddrToSymbol);
Yabin Cui516a87c2018-03-26 17:34:00 -0700462 if (it != symbols_.begin()) {
463 --it;
464 if (it->addr <= vaddr_in_dso && (it->addr + it->len > vaddr_in_dso)) {
465 return &*it;
Yabin Cuic8485602015-08-20 15:04:39 -0700466 }
467 }
Yabin Cuic5b4a312016-10-24 13:38:38 -0700468 if (!unknown_symbols_.empty()) {
469 auto it = unknown_symbols_.find(vaddr_in_dso);
470 if (it != unknown_symbols_.end()) {
471 return &it->second;
Yabin Cuic8485602015-08-20 15:04:39 -0700472 }
473 }
474 return nullptr;
475}
476
Yabin Cuic5b4a312016-10-24 13:38:38 -0700477void Dso::SetSymbols(std::vector<Symbol>* symbols) {
478 symbols_ = std::move(*symbols);
479 symbols->clear();
480}
481
482void Dso::AddUnknownSymbol(uint64_t vaddr_in_dso, const std::string& name) {
483 unknown_symbols_.insert(std::make_pair(vaddr_in_dso, Symbol(name, vaddr_in_dso, 1)));
484}
485
Yabin Cuiac4b2492020-12-09 16:27:57 -0800486bool Dso::IsForJavaMethod() const {
Yabin Cui10bbd842018-08-13 17:42:25 -0700487 if (type_ == DSO_DEX_FILE) {
488 return true;
489 }
490 if (type_ == DSO_ELF_FILE) {
Yabin Cui9ba4d942020-09-08 16:12:46 -0700491 if (JITDebugReader::IsPathInJITSymFile(path_)) {
Yabin Cuie32ed2b2020-07-23 15:30:14 -0700492 return true;
493 }
Yabin Cui9ba4d942020-09-08 16:12:46 -0700494 // JITDebugReader in old versions generates symfiles in 'TemporaryFile-XXXXXX'.
495 size_t pos = path_.rfind('/');
496 pos = (pos == std::string::npos) ? 0 : pos + 1;
497 return StartsWith(std::string_view(&path_[pos], path_.size() - pos), "TemporaryFile");
Yabin Cui10bbd842018-08-13 17:42:25 -0700498 }
499 return false;
500}
501
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800502void Dso::LoadSymbols() {
503 if (!is_loaded_) {
504 is_loaded_ = true;
505 std::vector<Symbol> symbols = LoadSymbolsImpl();
506 if (symbols_.empty()) {
507 symbols_ = std::move(symbols);
508 } else {
509 std::vector<Symbol> merged_symbols;
510 std::set_union(symbols_.begin(), symbols_.end(), symbols.begin(), symbols.end(),
511 std::back_inserter(merged_symbols), Symbol::CompareValueByAddr);
512 symbols_ = std::move(merged_symbols);
513 }
Yabin Cuic8485602015-08-20 15:04:39 -0700514 }
Yabin Cuiba50c4b2015-07-21 11:24:48 -0700515}
516
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200517static void ReportReadElfSymbolResult(
518 ElfStatus result, const std::string& path, const std::string& debug_file_path,
Yabin Cui516a87c2018-03-26 17:34:00 -0700519 android::base::LogSeverity warning_loglevel = android::base::WARNING) {
Yabin Cuidec43c12016-07-29 16:40:40 -0700520 if (result == ElfStatus::NO_ERROR) {
Yabin Cui516a87c2018-03-26 17:34:00 -0700521 LOG(VERBOSE) << "Read symbols from " << debug_file_path << " successfully";
Yabin Cuidec43c12016-07-29 16:40:40 -0700522 } else if (result == ElfStatus::NO_SYMBOL_TABLE) {
Yabin Cui516a87c2018-03-26 17:34:00 -0700523 if (path == "[vdso]") {
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700524 // Vdso only contains dynamic symbol table, and we can't change that.
Yabin Cui516a87c2018-03-26 17:34:00 -0700525 return;
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700526 }
Yabin Cuidec43c12016-07-29 16:40:40 -0700527 // Lacking symbol table isn't considered as an error but worth reporting.
Yabin Cui516a87c2018-03-26 17:34:00 -0700528 LOG(warning_loglevel) << debug_file_path << " doesn't contain symbol table";
Yabin Cuidec43c12016-07-29 16:40:40 -0700529 } else {
Yabin Cui516a87c2018-03-26 17:34:00 -0700530 LOG(warning_loglevel) << "failed to read symbols from " << debug_file_path << ": " << result;
Yabin Cuidec43c12016-07-29 16:40:40 -0700531 }
532}
533
Yabin Cui516a87c2018-03-26 17:34:00 -0700534static void SortAndFixSymbols(std::vector<Symbol>& symbols) {
535 std::sort(symbols.begin(), symbols.end(), Symbol::CompareValueByAddr);
Yabin Cuic8485602015-08-20 15:04:39 -0700536 Symbol* prev_symbol = nullptr;
Yabin Cui516a87c2018-03-26 17:34:00 -0700537 for (auto& symbol : symbols) {
Yabin Cuic8485602015-08-20 15:04:39 -0700538 if (prev_symbol != nullptr && prev_symbol->len == 0) {
Yabin Cuicc2e59e2015-08-21 14:23:43 -0700539 prev_symbol->len = symbol.addr - prev_symbol->addr;
Yabin Cuic8485602015-08-20 15:04:39 -0700540 }
Yabin Cui3d4aa262017-11-01 15:58:55 -0700541 prev_symbol = &symbol;
Yabin Cui638c5582015-07-01 16:16:57 -0700542 }
Yabin Cui516a87c2018-03-26 17:34:00 -0700543}
544
Yabin Cuidd401b32018-04-11 11:17:06 -0700545class DexFileDso : public Dso {
546 public:
Yabin Cui11424c42022-03-10 16:04:04 -0800547 DexFileDso(const std::string& path) : Dso(DSO_DEX_FILE, path) {}
Yabin Cuidd401b32018-04-11 11:17:06 -0700548
549 void AddDexFileOffset(uint64_t dex_file_offset) override {
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200550 auto it = std::lower_bound(dex_file_offsets_.begin(), dex_file_offsets_.end(), dex_file_offset);
Yabin Cuic8571d42018-06-06 11:20:39 -0700551 if (it != dex_file_offsets_.end() && *it == dex_file_offset) {
552 return;
553 }
554 dex_file_offsets_.insert(it, dex_file_offset);
Yabin Cuidd401b32018-04-11 11:17:06 -0700555 }
556
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200557 const std::vector<uint64_t>* DexFileOffsets() override { return &dex_file_offsets_; }
Yabin Cuidd401b32018-04-11 11:17:06 -0700558
Yabin Cuidb2c4932019-02-07 15:06:42 -0800559 uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t map_pgoff) override {
560 return ip - map_start + map_pgoff;
561 }
562
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800563 std::vector<Symbol> LoadSymbolsImpl() override {
Yabin Cuidd401b32018-04-11 11:17:06 -0700564 std::vector<Symbol> symbols;
Yabin Cui8b8ed0f2023-10-24 16:18:38 -0700565 if (StartsWith(path_, kDexFileInMemoryPrefix)) {
566 // For dex file in memory, the symbols should already be set via SetSymbols().
567 return symbols;
568 }
569
Yabin Cui11424c42022-03-10 16:04:04 -0800570 const std::string& debug_file_path = GetDebugFilePath();
571 auto tuple = SplitUrlInApk(debug_file_path);
Yabin Cui83b0e122021-11-03 14:10:10 -0700572 // Symbols of dex files are collected on device. If the dex file doesn't exist, probably
573 // we are reporting on host, and there is no need to report warning of missing dex files.
Yabin Cui11424c42022-03-10 16:04:04 -0800574 if (!IsRegularFile(std::get<0>(tuple) ? std::get<1>(tuple) : debug_file_path)) {
575 LOG(DEBUG) << "skip reading symbols from non-exist dex_file " << debug_file_path;
Yabin Cui83b0e122021-11-03 14:10:10 -0700576 return symbols;
577 }
Yabin Cui2a53ff32018-05-21 17:37:00 -0700578 bool status = false;
David Srbecky6a296b62021-04-15 20:52:22 +0100579 auto symbol_callback = [&](DexFileSymbol* symbol) {
580 symbols.emplace_back(symbol->name, symbol->addr, symbol->size);
Yabin Cui710f3722021-03-23 17:45:39 -0700581 };
Yabin Cui2a53ff32018-05-21 17:37:00 -0700582 if (std::get<0>(tuple)) {
583 std::unique_ptr<ArchiveHelper> ahelper = ArchiveHelper::CreateInstance(std::get<1>(tuple));
584 ZipEntry entry;
585 std::vector<uint8_t> data;
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200586 if (ahelper && ahelper->FindEntry(std::get<2>(tuple), &entry) &&
587 ahelper->GetEntryData(entry, &data)) {
Yabin Cui11424c42022-03-10 16:04:04 -0800588 status = ReadSymbolsFromDexFileInMemory(data.data(), data.size(), debug_file_path,
Yabin Cui17769f22021-07-13 16:39:16 -0700589 dex_file_offsets_, symbol_callback);
Yabin Cui2a53ff32018-05-21 17:37:00 -0700590 }
591 } else {
Yabin Cui11424c42022-03-10 16:04:04 -0800592 status = ReadSymbolsFromDexFile(debug_file_path, dex_file_offsets_, symbol_callback);
Yabin Cui2a53ff32018-05-21 17:37:00 -0700593 }
594 if (!status) {
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +0200595 android::base::LogSeverity level =
596 symbols_.empty() ? android::base::WARNING : android::base::DEBUG;
Yabin Cui11424c42022-03-10 16:04:04 -0800597 LOG(level) << "Failed to read symbols from dex_file " << debug_file_path;
Yabin Cuidd401b32018-04-11 11:17:06 -0700598 return symbols;
599 }
Yabin Cui11424c42022-03-10 16:04:04 -0800600 LOG(VERBOSE) << "Read symbols from dex_file " << debug_file_path << " successfully";
Yabin Cuidd401b32018-04-11 11:17:06 -0700601 SortAndFixSymbols(symbols);
602 return symbols;
603 }
604
605 private:
606 std::vector<uint64_t> dex_file_offsets_;
607};
608
Yabin Cui516a87c2018-03-26 17:34:00 -0700609class ElfDso : public Dso {
610 public:
Yabin Cui11424c42022-03-10 16:04:04 -0800611 ElfDso(const std::string& path, bool force_64bit)
612 : Dso(DSO_ELF_FILE, path), force_64bit_(force_64bit) {}
Yabin Cui516a87c2018-03-26 17:34:00 -0700613
Yabin Cuie32ed2b2020-07-23 15:30:14 -0700614 std::string_view GetReportPath() const override {
Yabin Cui9ba4d942020-09-08 16:12:46 -0700615 if (JITDebugReader::IsPathInJITSymFile(path_)) {
616 if (path_.find(kJITAppCacheFile) != path_.npos) {
Yabin Cui075dd182020-08-05 19:51:36 +0000617 return "[JIT app cache]";
618 }
Yabin Cui9ba4d942020-09-08 16:12:46 -0700619 return "[JIT zygote cache]";
Yabin Cuie32ed2b2020-07-23 15:30:14 -0700620 }
621 return path_;
622 }
623
Yabin Cuidb2c4932019-02-07 15:06:42 -0800624 void SetMinExecutableVaddr(uint64_t min_vaddr, uint64_t file_offset) override {
625 min_vaddr_ = min_vaddr;
626 file_offset_of_min_vaddr_ = file_offset;
Yabin Cuic8485602015-08-20 15:04:39 -0700627 }
Yabin Cui516a87c2018-03-26 17:34:00 -0700628
Yabin Cuidb2c4932019-02-07 15:06:42 -0800629 void GetMinExecutableVaddr(uint64_t* min_vaddr, uint64_t* file_offset) override {
630 if (type_ == DSO_DEX_FILE) {
631 return dex_file_dso_->GetMinExecutableVaddr(min_vaddr, file_offset);
632 }
633 if (min_vaddr_ == uninitialized_value) {
634 min_vaddr_ = 0;
635 BuildId build_id = GetExpectedBuildId();
Yabin Cui90c3b302020-07-01 10:09:16 -0700636
637 ElfStatus status;
Yabin Cui11424c42022-03-10 16:04:04 -0800638 auto elf = ElfFile::Open(GetDebugFilePath(), &build_id, &status);
Yabin Cui90c3b302020-07-01 10:09:16 -0700639 if (elf) {
640 min_vaddr_ = elf->ReadMinExecutableVaddr(&file_offset_of_min_vaddr_);
Yabin Cuidb2c4932019-02-07 15:06:42 -0800641 } else {
Yabin Cuif376bf02023-04-18 13:22:49 -0700642 // This is likely to be a file wrongly thought of as an ELF file, due to stack unwinding.
643 // No need to report it by default.
644 LOG(DEBUG) << "failed to read min virtual address of " << GetDebugFilePath() << ": "
645 << status;
Yabin Cuidb2c4932019-02-07 15:06:42 -0800646 }
647 }
648 *min_vaddr = min_vaddr_;
649 *file_offset = file_offset_of_min_vaddr_;
650 }
651
652 uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t map_pgoff) override {
653 if (type_ == DSO_DEX_FILE) {
654 return dex_file_dso_->IpToVaddrInFile(ip, map_start, map_pgoff);
655 }
656 uint64_t min_vaddr;
657 uint64_t file_offset_of_min_vaddr;
658 GetMinExecutableVaddr(&min_vaddr, &file_offset_of_min_vaddr);
659 if (file_offset_of_min_vaddr == uninitialized_value) {
660 return ip - map_start + min_vaddr;
661 }
662 // Apps may make part of the executable segment of a shared library writeable, which can
663 // generate multiple executable segments at runtime. So use map_pgoff to calculate
664 // vaddr_in_file.
665 return ip - map_start + map_pgoff - file_offset_of_min_vaddr + min_vaddr;
Yabin Cui516a87c2018-03-26 17:34:00 -0700666 }
667
Yabin Cuidd401b32018-04-11 11:17:06 -0700668 void AddDexFileOffset(uint64_t dex_file_offset) override {
669 if (type_ == DSO_ELF_FILE) {
670 // When simpleperf does unwinding while recording, it processes mmap records before reading
671 // dex file linked list (via JITDebugReader). To process mmap records, it creates Dso
672 // objects of type ELF_FILE. Then after reading dex file linked list, it realizes some
673 // ELF_FILE Dso objects should actually be DEX_FILE, because they have dex file offsets.
674 // So here converts ELF_FILE Dso into DEX_FILE Dso.
675 type_ = DSO_DEX_FILE;
Yabin Cui11424c42022-03-10 16:04:04 -0800676 dex_file_dso_.reset(new DexFileDso(path_));
Yabin Cuidd401b32018-04-11 11:17:06 -0700677 }
678 dex_file_dso_->AddDexFileOffset(dex_file_offset);
679 }
680
681 const std::vector<uint64_t>* DexFileOffsets() override {
682 return dex_file_dso_ ? dex_file_dso_->DexFileOffsets() : nullptr;
683 }
684
Yabin Cui516a87c2018-03-26 17:34:00 -0700685 protected:
Yabin Cui11424c42022-03-10 16:04:04 -0800686 std::string FindDebugFilePath() const override {
687 BuildId build_id = GetExpectedBuildId();
688 return debug_elf_file_finder_.FindDebugFile(path_, force_64bit_, build_id);
689 }
690
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800691 std::vector<Symbol> LoadSymbolsImpl() override {
Yabin Cuidd401b32018-04-11 11:17:06 -0700692 if (dex_file_dso_) {
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800693 return dex_file_dso_->LoadSymbolsImpl();
Yabin Cuidd401b32018-04-11 11:17:06 -0700694 }
Yabin Cui516a87c2018-03-26 17:34:00 -0700695 std::vector<Symbol> symbols;
696 BuildId build_id = GetExpectedBuildId();
697 auto symbol_callback = [&](const ElfFileSymbol& symbol) {
698 if (symbol.is_func || (symbol.is_label && symbol.is_in_text_section)) {
699 symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
700 }
701 };
702 ElfStatus status;
Yabin Cui11424c42022-03-10 16:04:04 -0800703 auto elf = ElfFile::Open(GetDebugFilePath(), &build_id, &status);
Yabin Cui01947032020-06-30 14:36:46 -0700704 if (elf) {
705 status = elf->ParseSymbols(symbol_callback);
Yabin Cui516a87c2018-03-26 17:34:00 -0700706 }
Yabin Cui2315ff62022-11-14 11:52:18 -0800707 android::base::LogSeverity log_level = android::base::WARNING;
Yabin Cuif376bf02023-04-18 13:22:49 -0700708 if (!symbols_.empty() || !symbols.empty()) {
Yabin Cui2315ff62022-11-14 11:52:18 -0800709 // We already have some symbols when recording.
710 log_level = android::base::DEBUG;
711 }
712 if ((status == ElfStatus::FILE_NOT_FOUND || status == ElfStatus::FILE_MALFORMED) &&
713 build_id.IsEmpty()) {
Yabin Cuif376bf02023-04-18 13:22:49 -0700714 // This is likely to be a file wrongly thought of as an ELF file, due to stack unwinding.
Yabin Cui2315ff62022-11-14 11:52:18 -0800715 log_level = android::base::DEBUG;
716 }
717 ReportReadElfSymbolResult(status, path_, GetDebugFilePath(), log_level);
Yabin Cui516a87c2018-03-26 17:34:00 -0700718 SortAndFixSymbols(symbols);
719 return symbols;
720 }
721
722 private:
Yabin Cuidb2c4932019-02-07 15:06:42 -0800723 static constexpr uint64_t uninitialized_value = std::numeric_limits<uint64_t>::max();
724
Yabin Cui11424c42022-03-10 16:04:04 -0800725 bool force_64bit_;
Yabin Cuidb2c4932019-02-07 15:06:42 -0800726 uint64_t min_vaddr_ = uninitialized_value;
727 uint64_t file_offset_of_min_vaddr_ = uninitialized_value;
Yabin Cuidd401b32018-04-11 11:17:06 -0700728 std::unique_ptr<DexFileDso> dex_file_dso_;
Yabin Cui516a87c2018-03-26 17:34:00 -0700729};
730
731class KernelDso : public Dso {
732 public:
Yabin Cuic5184712023-10-13 14:10:17 -0700733 KernelDso(const std::string& path) : Dso(DSO_KERNEL, path) {}
Yabin Cui516a87c2018-03-26 17:34:00 -0700734
Yabin Cui7078c672020-11-10 16:24:12 -0800735 // IpToVaddrInFile() and LoadSymbols() must be consistent in fixing addresses changed by kernel
736 // address space layout randomization.
737 uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t) override {
738 if (map_start != 0 && GetKernelStartAddr() != 0) {
739 // Fix kernel addresses changed by kernel address randomization.
740 fix_kernel_address_randomization_ = true;
741 return ip - map_start + GetKernelStartAddr();
742 }
743 return ip;
744 }
745
746 std::optional<uint64_t> IpToFileOffset(uint64_t ip, uint64_t map_start, uint64_t) override {
747 if (map_start != 0 && GetKernelStartOffset() != 0) {
748 return ip - map_start + GetKernelStartOffset();
749 }
750 return std::nullopt;
751 }
Yabin Cuidb2c4932019-02-07 15:06:42 -0800752
Yabin Cui516a87c2018-03-26 17:34:00 -0700753 protected:
Yabin Cui11424c42022-03-10 16:04:04 -0800754 std::string FindDebugFilePath() const override {
755 BuildId build_id = GetExpectedBuildId();
Yabin Cuic5184712023-10-13 14:10:17 -0700756 if (!vmlinux_.empty()) {
757 // Use vmlinux as the kernel debug file.
758 ElfStatus status;
759 if (ElfFile::Open(vmlinux_, &build_id, &status)) {
760 return vmlinux_;
761 }
762 }
Yabin Cui11424c42022-03-10 16:04:04 -0800763 return debug_elf_file_finder_.FindDebugFile(path_, false, build_id);
764 }
765
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800766 std::vector<Symbol> LoadSymbolsImpl() override {
Yabin Cui516a87c2018-03-26 17:34:00 -0700767 std::vector<Symbol> symbols;
Yabin Cuic7aed042022-09-09 15:54:45 -0700768 ReadSymbolsFromDebugFile(&symbols);
ThiƩbaud Weksteene7e750e2020-11-19 15:07:46 +0100769
Yabin Cui7078c672020-11-10 16:24:12 -0800770 if (symbols.empty() && !kallsyms_.empty()) {
771 ReadSymbolsFromKallsyms(kallsyms_, &symbols);
772 }
Yabin Cui36b57d92020-12-17 17:06:27 -0800773#if defined(__linux__)
Yabin Cui7078c672020-11-10 16:24:12 -0800774 if (symbols.empty()) {
775 ReadSymbolsFromProc(&symbols);
776 }
ThiƩbaud Weksteene7e750e2020-11-19 15:07:46 +0100777#endif // defined(__linux__)
Yabin Cui7078c672020-11-10 16:24:12 -0800778 SortAndFixSymbols(symbols);
Yabin Cuic5184712023-10-13 14:10:17 -0700779 if (!symbols.empty() && symbols.back().len == 0) {
Yabin Cui7078c672020-11-10 16:24:12 -0800780 symbols.back().len = std::numeric_limits<uint64_t>::max() - symbols.back().addr;
781 }
782 return symbols;
783 }
784
785 private:
786 void ReadSymbolsFromDebugFile(std::vector<Symbol>* symbols) {
Yabin Cuic7aed042022-09-09 15:54:45 -0700787 ElfStatus status;
788 auto elf = ElfFile::Open(GetDebugFilePath(), &status);
789 if (!elf) {
790 return;
791 }
792
Yabin Cui7078c672020-11-10 16:24:12 -0800793 if (!fix_kernel_address_randomization_) {
794 LOG(WARNING) << "Don't know how to fix addresses changed by kernel address randomization. So "
795 "symbols in "
Yabin Cui11424c42022-03-10 16:04:04 -0800796 << GetDebugFilePath() << " are not used";
Yabin Cui7078c672020-11-10 16:24:12 -0800797 return;
798 }
799 // symbols_ are kernel symbols got from /proc/kallsyms while recording. Those symbols are
800 // not fixed for kernel address randomization. So clear them to avoid mixing them with
801 // symbols in debug_file_path.
802 symbols_.clear();
803
804 auto symbol_callback = [&](const ElfFileSymbol& symbol) {
805 if (symbol.is_func) {
806 symbols->emplace_back(symbol.name, symbol.vaddr, symbol.len);
Yabin Cui01947032020-06-30 14:36:46 -0700807 }
Yabin Cui7078c672020-11-10 16:24:12 -0800808 };
Yabin Cuic7aed042022-09-09 15:54:45 -0700809 status = elf->ParseSymbols(symbol_callback);
Yabin Cui11424c42022-03-10 16:04:04 -0800810 ReportReadElfSymbolResult(status, path_, GetDebugFilePath());
Yabin Cui7078c672020-11-10 16:24:12 -0800811 }
812
813 void ReadSymbolsFromKallsyms(std::string& kallsyms, std::vector<Symbol>* symbols) {
814 auto symbol_callback = [&](const KernelSymbol& symbol) {
815 if (strchr("TtWw", symbol.type) && symbol.addr != 0u) {
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800816 if (symbol.module == nullptr) {
817 symbols->emplace_back(symbol.name, symbol.addr, 0);
818 } else {
819 std::string name = std::string(symbol.name) + " [" + symbol.module + "]";
820 symbols->emplace_back(name, symbol.addr, 0);
821 }
Yabin Cui7078c672020-11-10 16:24:12 -0800822 }
823 return false;
824 };
825 ProcessKernelSymbols(kallsyms, symbol_callback);
826 if (symbols->empty()) {
827 LOG(WARNING) << "Symbol addresses in /proc/kallsyms on device are all zero. "
828 "`echo 0 >/proc/sys/kernel/kptr_restrict` if possible.";
829 }
830 }
831
Yabin Cui36b57d92020-12-17 17:06:27 -0800832#if defined(__linux__)
Yabin Cui7078c672020-11-10 16:24:12 -0800833 void ReadSymbolsFromProc(std::vector<Symbol>* symbols) {
834 BuildId build_id = GetExpectedBuildId();
ThiƩbaud Weksteene7e750e2020-11-19 15:07:46 +0100835 if (!build_id.IsEmpty()) {
Yabin Cui516a87c2018-03-26 17:34:00 -0700836 // Try /proc/kallsyms only when asked to do so, or when build id matches.
837 // Otherwise, it is likely to use /proc/kallsyms on host for perf.data recorded on device.
838 bool can_read_kallsyms = true;
839 if (!build_id.IsEmpty()) {
840 BuildId real_build_id;
841 if (!GetKernelBuildId(&real_build_id) || build_id != real_build_id) {
842 LOG(DEBUG) << "failed to read symbols from /proc/kallsyms: Build id mismatch";
843 can_read_kallsyms = false;
844 }
845 }
846 if (can_read_kallsyms) {
847 std::string kallsyms;
ThiƩbaud Weksteene7e750e2020-11-19 15:07:46 +0100848 if (LoadKernelSymbols(&kallsyms)) {
Yabin Cui7078c672020-11-10 16:24:12 -0800849 ReadSymbolsFromKallsyms(kallsyms, symbols);
Yabin Cui516a87c2018-03-26 17:34:00 -0700850 }
851 }
852 }
Yabin Cui516a87c2018-03-26 17:34:00 -0700853 }
ThiƩbaud Weksteene7e750e2020-11-19 15:07:46 +0100854#endif // defined(__linux__)
Yabin Cui516a87c2018-03-26 17:34:00 -0700855
Yabin Cui7078c672020-11-10 16:24:12 -0800856 uint64_t GetKernelStartAddr() {
857 if (!kernel_start_addr_) {
858 ParseKernelStartAddr();
Yabin Cui516a87c2018-03-26 17:34:00 -0700859 }
Yabin Cui7078c672020-11-10 16:24:12 -0800860 return kernel_start_addr_.value();
Yabin Cui516a87c2018-03-26 17:34:00 -0700861 }
Yabin Cui7078c672020-11-10 16:24:12 -0800862
863 uint64_t GetKernelStartOffset() {
864 if (!kernel_start_file_offset_) {
865 ParseKernelStartAddr();
866 }
867 return kernel_start_file_offset_.value();
868 }
869
870 void ParseKernelStartAddr() {
871 kernel_start_addr_ = 0;
872 kernel_start_file_offset_ = 0;
Yabin Cuic7aed042022-09-09 15:54:45 -0700873 ElfStatus status;
874 if (auto elf = ElfFile::Open(GetDebugFilePath(), &status); elf) {
875 for (const auto& section : elf->GetSectionHeader()) {
876 if (section.name == ".text") {
877 kernel_start_addr_ = section.vaddr;
878 kernel_start_file_offset_ = section.file_offset;
879 break;
Yabin Cui7078c672020-11-10 16:24:12 -0800880 }
881 }
882 }
883 }
884
Yabin Cui7078c672020-11-10 16:24:12 -0800885 bool fix_kernel_address_randomization_ = false;
886 std::optional<uint64_t> kernel_start_addr_;
887 std::optional<uint64_t> kernel_start_file_offset_;
Yabin Cui516a87c2018-03-26 17:34:00 -0700888};
889
890class KernelModuleDso : public Dso {
891 public:
Yabin Cui11424c42022-03-10 16:04:04 -0800892 KernelModuleDso(const std::string& path, uint64_t memory_start, uint64_t memory_end,
893 Dso* kernel_dso)
894 : Dso(DSO_KERNEL_MODULE, path),
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800895 memory_start_(memory_start),
896 memory_end_(memory_end),
897 kernel_dso_(kernel_dso) {}
898
899 void SetMinExecutableVaddr(uint64_t min_vaddr, uint64_t memory_offset) override {
900 min_vaddr_ = min_vaddr;
901 memory_offset_of_min_vaddr_ = memory_offset;
902 }
903
904 void GetMinExecutableVaddr(uint64_t* min_vaddr, uint64_t* memory_offset) override {
905 if (!min_vaddr_) {
906 CalculateMinVaddr();
907 }
908 *min_vaddr = min_vaddr_.value();
909 *memory_offset = memory_offset_of_min_vaddr_.value();
910 }
Yabin Cui516a87c2018-03-26 17:34:00 -0700911
Yabin Cuidb2c4932019-02-07 15:06:42 -0800912 uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t) override {
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800913 uint64_t min_vaddr;
914 uint64_t memory_offset;
915 GetMinExecutableVaddr(&min_vaddr, &memory_offset);
916 return ip - map_start - memory_offset + min_vaddr;
Yabin Cuidb2c4932019-02-07 15:06:42 -0800917 }
918
Yabin Cui516a87c2018-03-26 17:34:00 -0700919 protected:
Yabin Cui11424c42022-03-10 16:04:04 -0800920 std::string FindDebugFilePath() const override {
921 BuildId build_id = GetExpectedBuildId();
922 return debug_elf_file_finder_.FindDebugFile(path_, false, build_id);
923 }
924
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800925 std::vector<Symbol> LoadSymbolsImpl() override {
Yabin Cui516a87c2018-03-26 17:34:00 -0700926 std::vector<Symbol> symbols;
927 BuildId build_id = GetExpectedBuildId();
928 auto symbol_callback = [&](const ElfFileSymbol& symbol) {
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800929 // We only know how to map ip addrs to symbols in text section.
930 if (symbol.is_in_text_section && (symbol.is_label || symbol.is_func)) {
Yabin Cui516a87c2018-03-26 17:34:00 -0700931 symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
932 }
933 };
Yabin Cui01947032020-06-30 14:36:46 -0700934 ElfStatus status;
Yabin Cui11424c42022-03-10 16:04:04 -0800935 auto elf = ElfFile::Open(GetDebugFilePath(), &build_id, &status);
Yabin Cui01947032020-06-30 14:36:46 -0700936 if (elf) {
937 status = elf->ParseSymbols(symbol_callback);
938 }
Yabin Cui2c928d62024-04-03 13:46:08 -0700939 // Don't warn when a kernel module is missing. As a backup, we read symbols from /proc/kallsyms.
940 ReportReadElfSymbolResult(status, path_, GetDebugFilePath(), android::base::DEBUG);
Yabin Cui516a87c2018-03-26 17:34:00 -0700941 SortAndFixSymbols(symbols);
942 return symbols;
943 }
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800944
945 private:
946 void CalculateMinVaddr() {
947 min_vaddr_ = 0;
948 memory_offset_of_min_vaddr_ = 0;
949
950 // min_vaddr and memory_offset are used to convert an ip addr of a kernel module to its
951 // vaddr_in_file, as shown in IpToVaddrInFile(). When the kernel loads a kernel module, it
952 // puts ALLOC sections (like .plt, .text.ftrace_trampoline, .text) in memory in order. The
953 // text section may not be at the start of the module memory. To do address conversion, we
954 // need to know its relative position in the module memory. There are two ways:
955 // 1. Read the kernel module file to calculate the relative position of .text section. It
956 // is relatively complex and depends on both PLT entries and the kernel version.
Yabin Cui4d8137f2023-02-14 17:00:25 -0800957 // 2. Find a module symbol in .text section, get its address in memory from /proc/kallsyms,
958 // and its vaddr_in_file from the kernel module file. Then other symbols in .text section can
959 // be mapped in the same way. Below we use the second method.
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800960
Yabin Cui2c928d62024-04-03 13:46:08 -0700961 if (!IsRegularFile(GetDebugFilePath())) {
962 return;
963 }
964
Yabin Cuif3da1ed2020-11-25 15:37:38 -0800965 // 1. Select a module symbol in /proc/kallsyms.
966 kernel_dso_->LoadSymbols();
967 const auto& kernel_symbols = kernel_dso_->GetSymbols();
968 auto it = std::lower_bound(kernel_symbols.begin(), kernel_symbols.end(), memory_start_,
969 CompareSymbolToAddr);
970 const Symbol* kernel_symbol = nullptr;
971 while (it != kernel_symbols.end() && it->addr < memory_end_) {
972 if (strlen(it->Name()) > 0 && it->Name()[0] != '$') {
973 kernel_symbol = &*it;
974 break;
975 }
976 ++it;
977 }
978 if (kernel_symbol == nullptr) {
979 return;
980 }
981
982 // 2. Find the symbol in .ko file.
983 std::string symbol_name = kernel_symbol->Name();
984 if (auto pos = symbol_name.rfind(' '); pos != std::string::npos) {
985 symbol_name.resize(pos);
986 }
987 LoadSymbols();
988 for (const auto& symbol : symbols_) {
989 if (symbol_name == symbol.Name()) {
990 min_vaddr_ = symbol.addr;
991 memory_offset_of_min_vaddr_ = kernel_symbol->addr - memory_start_;
992 return;
993 }
994 }
995 }
996
997 uint64_t memory_start_;
998 uint64_t memory_end_;
999 Dso* kernel_dso_;
1000 std::optional<uint64_t> min_vaddr_;
1001 std::optional<uint64_t> memory_offset_of_min_vaddr_;
Yabin Cui516a87c2018-03-26 17:34:00 -07001002};
1003
Evgeny Eltsin91dbae02020-08-27 15:46:09 +02001004class SymbolMapFileDso : public Dso {
1005 public:
Yabin Cui11424c42022-03-10 16:04:04 -08001006 SymbolMapFileDso(const std::string& path) : Dso(DSO_SYMBOL_MAP_FILE, path) {}
Evgeny Eltsin91dbae02020-08-27 15:46:09 +02001007
1008 uint64_t IpToVaddrInFile(uint64_t ip, uint64_t, uint64_t) override { return ip; }
1009
1010 protected:
Yabin Cuif3da1ed2020-11-25 15:37:38 -08001011 std::vector<Symbol> LoadSymbolsImpl() override { return {}; }
Evgeny Eltsin91dbae02020-08-27 15:46:09 +02001012};
1013
Yabin Cuic36ea8b2018-04-16 18:21:40 -07001014class UnknownDso : public Dso {
1015 public:
Yabin Cui11424c42022-03-10 16:04:04 -08001016 UnknownDso(const std::string& path) : Dso(DSO_UNKNOWN_FILE, path) {}
Yabin Cuic36ea8b2018-04-16 18:21:40 -07001017
ThiƩbaud Weksteen4848ee02020-10-23 16:06:59 +02001018 uint64_t IpToVaddrInFile(uint64_t ip, uint64_t, uint64_t) override { return ip; }
Yabin Cuidb2c4932019-02-07 15:06:42 -08001019
Yabin Cuic36ea8b2018-04-16 18:21:40 -07001020 protected:
Yabin Cuif3da1ed2020-11-25 15:37:38 -08001021 std::vector<Symbol> LoadSymbolsImpl() override { return std::vector<Symbol>(); }
Yabin Cuic36ea8b2018-04-16 18:21:40 -07001022};
1023
Yabin Cui516a87c2018-03-26 17:34:00 -07001024std::unique_ptr<Dso> Dso::CreateDso(DsoType dso_type, const std::string& dso_path,
1025 bool force_64bit) {
Yabin Cui516a87c2018-03-26 17:34:00 -07001026 switch (dso_type) {
Yabin Cui7078c672020-11-10 16:24:12 -08001027 case DSO_ELF_FILE:
Yabin Cui11424c42022-03-10 16:04:04 -08001028 return std::unique_ptr<Dso>(new ElfDso(dso_path, force_64bit));
Yabin Cui516a87c2018-03-26 17:34:00 -07001029 case DSO_KERNEL:
Yabin Cui11424c42022-03-10 16:04:04 -08001030 return std::unique_ptr<Dso>(new KernelDso(dso_path));
Yabin Cui516a87c2018-03-26 17:34:00 -07001031 case DSO_DEX_FILE:
Yabin Cui11424c42022-03-10 16:04:04 -08001032 return std::unique_ptr<Dso>(new DexFileDso(dso_path));
Evgeny Eltsin91dbae02020-08-27 15:46:09 +02001033 case DSO_SYMBOL_MAP_FILE:
1034 return std::unique_ptr<Dso>(new SymbolMapFileDso(dso_path));
Yabin Cuic36ea8b2018-04-16 18:21:40 -07001035 case DSO_UNKNOWN_FILE:
1036 return std::unique_ptr<Dso>(new UnknownDso(dso_path));
Yabin Cui516a87c2018-03-26 17:34:00 -07001037 default:
Yabin Cui90a547e2022-12-07 16:29:13 -08001038 LOG(ERROR) << "Unexpected dso_type " << static_cast<int>(dso_type);
1039 return nullptr;
Yabin Cui516a87c2018-03-26 17:34:00 -07001040 }
Yabin Cui516a87c2018-03-26 17:34:00 -07001041}
1042
Yabin Cui16f41ff2021-03-23 14:58:25 -07001043std::unique_ptr<Dso> Dso::CreateDsoWithBuildId(DsoType dso_type, const std::string& dso_path,
1044 BuildId& build_id) {
Yabin Cui11424c42022-03-10 16:04:04 -08001045 std::unique_ptr<Dso> dso;
Yabin Cui16f41ff2021-03-23 14:58:25 -07001046 switch (dso_type) {
1047 case DSO_ELF_FILE:
Yabin Cui11424c42022-03-10 16:04:04 -08001048 dso.reset(new ElfDso(dso_path, false));
1049 break;
Yabin Cui16f41ff2021-03-23 14:58:25 -07001050 case DSO_KERNEL:
Yabin Cui11424c42022-03-10 16:04:04 -08001051 dso.reset(new KernelDso(dso_path));
1052 break;
Yabin Cui16f41ff2021-03-23 14:58:25 -07001053 case DSO_KERNEL_MODULE:
Yabin Cui11424c42022-03-10 16:04:04 -08001054 dso.reset(new KernelModuleDso(dso_path, 0, 0, nullptr));
1055 break;
Yabin Cui16f41ff2021-03-23 14:58:25 -07001056 default:
Yabin Cui90a547e2022-12-07 16:29:13 -08001057 LOG(ERROR) << "Unexpected dso_type " << static_cast<int>(dso_type);
Yabin Cui11424c42022-03-10 16:04:04 -08001058 return nullptr;
Yabin Cui16f41ff2021-03-23 14:58:25 -07001059 }
Yabin Cui11424c42022-03-10 16:04:04 -08001060 dso->debug_file_path_ = debug_elf_file_finder_.FindDebugFile(dso_path, false, build_id);
1061 return dso;
Yabin Cui4ad10fb2020-04-01 15:45:48 -07001062}
1063
Yabin Cuif3da1ed2020-11-25 15:37:38 -08001064std::unique_ptr<Dso> Dso::CreateKernelModuleDso(const std::string& dso_path, uint64_t memory_start,
1065 uint64_t memory_end, Dso* kernel_dso) {
Yabin Cui11424c42022-03-10 16:04:04 -08001066 return std::unique_ptr<Dso>(new KernelModuleDso(dso_path, memory_start, memory_end, kernel_dso));
Yabin Cuif3da1ed2020-11-25 15:37:38 -08001067}
1068
Yabin Cui767dd172016-06-02 21:02:43 -07001069const char* DsoTypeToString(DsoType dso_type) {
1070 switch (dso_type) {
1071 case DSO_KERNEL:
1072 return "dso_kernel";
1073 case DSO_KERNEL_MODULE:
1074 return "dso_kernel_module";
1075 case DSO_ELF_FILE:
1076 return "dso_elf_file";
Yabin Cui516a87c2018-03-26 17:34:00 -07001077 case DSO_DEX_FILE:
1078 return "dso_dex_file";
Evgeny Eltsin91dbae02020-08-27 15:46:09 +02001079 case DSO_SYMBOL_MAP_FILE:
1080 return "dso_symbol_map_file";
Yabin Cui767dd172016-06-02 21:02:43 -07001081 default:
1082 return "unknown";
1083 }
1084}
Yabin Cui40b70ff2018-04-09 14:06:08 -07001085
1086bool GetBuildIdFromDsoPath(const std::string& dso_path, BuildId* build_id) {
Yabin Cui3a880452020-06-29 16:37:31 -07001087 ElfStatus status;
1088 auto elf = ElfFile::Open(dso_path, &status);
1089 if (status == ElfStatus::NO_ERROR && elf->GetBuildId(build_id) == ElfStatus::NO_ERROR) {
1090 return true;
Yabin Cui40b70ff2018-04-09 14:06:08 -07001091 }
Yabin Cui3a880452020-06-29 16:37:31 -07001092 return false;
Yabin Cui40b70ff2018-04-09 14:06:08 -07001093}
Yabin Cuifaa7b922021-01-11 17:35:57 -08001094
Yabin Cui290e9c42023-05-01 15:09:30 -07001095bool GetBuildId(const Dso& dso, BuildId& build_id) {
1096 if (dso.type() == DSO_KERNEL) {
1097 if (GetKernelBuildId(&build_id)) {
1098 return true;
1099 }
1100 } else if (dso.type() == DSO_KERNEL_MODULE) {
1101 bool has_build_id = false;
1102 if (android::base::EndsWith(dso.Path(), ".ko")) {
1103 return GetBuildIdFromDsoPath(dso.Path(), &build_id);
1104 }
1105 if (const std::string& path = dso.Path();
1106 path.size() > 2 && path[0] == '[' && path.back() == ']') {
1107 // For kernel modules that we can't find the corresponding file, read build id from /sysfs.
1108 return GetModuleBuildId(path.substr(1, path.size() - 2), &build_id);
1109 }
1110 } else if (dso.type() == DSO_ELF_FILE) {
1111 if (dso.Path() == DEFAULT_EXECNAME_FOR_THREAD_MMAP || dso.IsForJavaMethod()) {
1112 return false;
1113 }
1114 if (GetBuildIdFromDsoPath(dso.Path(), &build_id)) {
1115 return true;
1116 }
1117 }
1118 return false;
1119}
1120
Yabin Cuifaa7b922021-01-11 17:35:57 -08001121} // namespace simpleperf