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