1 /*
2 * Copyright (C) 2018 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 <stdint.h>
18 #include <sys/mman.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22
23 #include <memory>
24
25 #define LOG_TAG "unwind"
26 #include <log/log.h>
27
28 #include <android-base/unique_fd.h>
29 #include <art_api/dex_file_support.h>
30
31 #include <unwindstack/MapInfo.h>
32 #include <unwindstack/Memory.h>
33
34 #include "DexFile.h"
35 #include "MemoryBuffer.h"
36
37 namespace unwindstack {
38
39 std::map<DexFile::MappedFileKey, std::weak_ptr<DexFile::DexFileApi>> DexFile::g_mapped_dex_files;
40 std::mutex DexFile::g_lock;
41
CheckDexSupport()42 static bool CheckDexSupport() {
43 if (std::string err_msg; !art_api::dex::TryLoadLibdexfile(&err_msg)) {
44 ALOGW("Failed to initialize DEX file support: %s", err_msg.c_str());
45 return false;
46 }
47 return true;
48 }
49
CreateFromDisk(uint64_t addr,uint64_t size,MapInfo * map)50 std::shared_ptr<DexFile> DexFile::CreateFromDisk(uint64_t addr, uint64_t size, MapInfo* map) {
51 if (map == nullptr || map->name().empty()) {
52 return nullptr; // MapInfo not backed by file.
53 }
54 if (!(map->start() <= addr && addr < map->end())) {
55 return nullptr; // addr is not in MapInfo range.
56 }
57 if (size > (map->end() - addr)) {
58 return nullptr; // size is past the MapInfo end.
59 }
60 uint64_t offset_in_file = (addr - map->start()) + map->offset();
61
62 // Fast-path: Check if the dex file was already mapped from disk.
63 std::lock_guard<std::mutex> guard(g_lock);
64 MappedFileKey cache_key(map->name(), offset_in_file, size);
65 std::weak_ptr<DexFileApi>& cache_entry = g_mapped_dex_files[cache_key];
66 std::shared_ptr<DexFileApi> dex_api = cache_entry.lock();
67 if (dex_api != nullptr) {
68 return std::shared_ptr<DexFile>(new DexFile(addr, size, std::move(dex_api)));
69 }
70
71 // Load the file from disk and cache it.
72 std::unique_ptr<Memory> memory = Memory::CreateFileMemory(map->name(), offset_in_file, size);
73 if (memory == nullptr) {
74 return nullptr; // failed to map the file.
75 }
76 std::unique_ptr<art_api::dex::DexFile> dex;
77 art_api::dex::DexFile::Create(memory->GetPtr(), size, nullptr, map->name().c_str(), &dex);
78 if (dex == nullptr) {
79 return nullptr; // invalid DEX file.
80 }
81 dex_api.reset(new DexFileApi{std::move(dex), std::move(memory), std::mutex()});
82 cache_entry = dex_api;
83 return std::shared_ptr<DexFile>(new DexFile(addr, size, std::move(dex_api)));
84 }
85
Create(uint64_t base_addr,uint64_t file_size,Memory * memory,MapInfo * info)86 std::shared_ptr<DexFile> DexFile::Create(uint64_t base_addr, uint64_t file_size, Memory* memory,
87 MapInfo* info) {
88 static bool has_dex_support = CheckDexSupport();
89 if (!has_dex_support || file_size == 0) {
90 return nullptr;
91 }
92
93 // Do not try to open the DEX file if the file name ends with "(deleted)". It does not exist.
94 // This happens when an app is background-optimized by ART and all of its files are replaced.
95 // Furthermore, do NOT try to fallback to in-memory copy. It would work, but all apps tend to
96 // be background-optimized at the same time, so it would lead to excessive memory use during
97 // system-wide profiling (essentially copying all dex files for all apps: hundreds of MBs).
98 // This will cause missing symbols in the backtrace, however, that outcome is inevitable
99 // anyway, since we can not obtain mini-debug-info for the deleted .oat files.
100 const std::string_view filename(info != nullptr ? info->name() : "");
101 const std::string_view kDeleted("(deleted)");
102 if (filename.size() >= kDeleted.size() &&
103 filename.substr(filename.size() - kDeleted.size()) == kDeleted) {
104 return nullptr;
105 }
106
107 std::shared_ptr<DexFile> dex_file = CreateFromDisk(base_addr, file_size, info);
108 if (dex_file != nullptr) {
109 return dex_file;
110 }
111
112 // Fallback: make copy in local buffer.
113 std::unique_ptr<MemoryBuffer> copy(new MemoryBuffer);
114 if (!copy->Resize(file_size)) {
115 return nullptr;
116 }
117 if (!memory->ReadFully(base_addr, copy->GetPtr(0), file_size)) {
118 return nullptr;
119 }
120 std::unique_ptr<art_api::dex::DexFile> dex;
121 art_api::dex::DexFile::Create(copy->GetPtr(0), file_size, nullptr, "", &dex);
122 if (dex == nullptr) {
123 return nullptr;
124 }
125 std::shared_ptr<DexFileApi> api(new DexFileApi{std::move(dex), std::move(copy), std::mutex()});
126 return std::shared_ptr<DexFile>(new DexFile(base_addr, file_size, std::move(api)));
127 }
128
GetFunctionName(uint64_t dex_pc,SharedString * method_name,uint64_t * method_offset)129 bool DexFile::GetFunctionName(uint64_t dex_pc, SharedString* method_name, uint64_t* method_offset) {
130 uint64_t dex_offset = dex_pc - base_addr_; // Convert absolute PC to file-relative offset.
131
132 // Lookup the function in the cache.
133 std::lock_guard<std::mutex> guard(dex_api_->lock_); // Protect both the symbols and the C API.
134 auto it = symbols_.upper_bound(dex_offset);
135 if (it == symbols_.end() || dex_offset < it->second.offset) {
136 // Lookup the function in the underlying dex file.
137 size_t found = dex_api_->dex_->FindMethodAtOffset(dex_offset, [&](const auto& method) {
138 size_t code_size, name_size;
139 uint32_t offset = method.GetCodeOffset(&code_size);
140 const char* name = method.GetQualifiedName(/*with_params=*/false, &name_size);
141 it = symbols_.emplace(offset + code_size, Info{offset, std::string(name, name_size)}).first;
142 });
143 if (found == 0) {
144 return false;
145 }
146 }
147
148 // Return the found function.
149 *method_offset = dex_offset - it->second.offset;
150 *method_name = it->second.name;
151 return true;
152 }
153
154 } // namespace unwindstack
155