1 /*
2 * Copyright (C) 2016 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 <elf.h>
18 #include <inttypes.h>
19 #include <string.h>
20 #include <sys/mman.h>
21
22 #include <memory>
23 #include <mutex>
24 #include <string>
25 #include <utility>
26
27 #include <android-base/stringprintf.h>
28
29 #include <unwindstack/Elf.h>
30 #include <unwindstack/ElfInterface.h>
31 #include <unwindstack/Log.h>
32 #include <unwindstack/MapInfo.h>
33 #include <unwindstack/Memory.h>
34 #include <unwindstack/Regs.h>
35 #include <unwindstack/SharedString.h>
36
37 #include <android-base/stringprintf.h>
38
39 #include "ElfInterfaceArm.h"
40 #include "Symbols.h"
41
42 namespace unwindstack {
43
44 bool Elf::cache_enabled_;
45 std::unordered_map<std::string, std::unordered_map<uint64_t, std::shared_ptr<Elf>>>* Elf::cache_;
46 std::mutex* Elf::cache_lock_;
47
Init()48 bool Elf::Init() {
49 load_bias_ = 0;
50 if (!memory_) {
51 return false;
52 }
53
54 interface_.reset(CreateInterfaceFromMemory(memory_.get()));
55 if (!interface_) {
56 return false;
57 }
58
59 valid_ = interface_->Init(&load_bias_);
60 if (valid_) {
61 interface_->InitHeaders();
62 InitGnuDebugdata();
63 } else {
64 interface_.reset(nullptr);
65 }
66 return valid_;
67 }
68
69 // It is expensive to initialize the .gnu_debugdata section. Provide a method
70 // to initialize this data separately.
InitGnuDebugdata()71 void Elf::InitGnuDebugdata() {
72 if (!valid_ || interface_->gnu_debugdata_offset() == 0) {
73 return;
74 }
75
76 gnu_debugdata_memory_ = interface_->CreateGnuDebugdataMemory();
77 gnu_debugdata_interface_.reset(CreateInterfaceFromMemory(gnu_debugdata_memory_.get()));
78 ElfInterface* gnu = gnu_debugdata_interface_.get();
79 if (gnu == nullptr) {
80 return;
81 }
82
83 // Ignore the load_bias from the compressed section, the correct load bias
84 // is in the uncompressed data.
85 int64_t load_bias;
86 if (gnu->Init(&load_bias)) {
87 gnu->InitHeaders();
88 interface_->SetGnuDebugdataInterface(gnu);
89 } else {
90 // Free all of the memory associated with the gnu_debugdata section.
91 gnu_debugdata_memory_.reset(nullptr);
92 gnu_debugdata_interface_.reset(nullptr);
93 }
94 }
95
Invalidate()96 void Elf::Invalidate() {
97 interface_.reset(nullptr);
98 valid_ = false;
99 }
100
GetSoname()101 std::string Elf::GetSoname() {
102 std::lock_guard<std::mutex> guard(lock_);
103 if (!valid_) {
104 return "";
105 }
106 return interface_->GetSoname();
107 }
108
GetRelPc(uint64_t pc,MapInfo * map_info)109 uint64_t Elf::GetRelPc(uint64_t pc, MapInfo* map_info) {
110 return pc - map_info->start() + load_bias_ + map_info->elf_offset();
111 }
112
GetFunctionName(uint64_t addr,SharedString * name,uint64_t * func_offset)113 bool Elf::GetFunctionName(uint64_t addr, SharedString* name, uint64_t* func_offset) {
114 std::lock_guard<std::mutex> guard(lock_);
115 return valid_ && (interface_->GetFunctionName(addr, name, func_offset) ||
116 (gnu_debugdata_interface_ &&
117 gnu_debugdata_interface_->GetFunctionName(addr, name, func_offset)));
118 }
119
GetGlobalVariableOffset(const std::string & name,uint64_t * memory_offset)120 bool Elf::GetGlobalVariableOffset(const std::string& name, uint64_t* memory_offset) {
121 if (!valid_) {
122 return false;
123 }
124
125 uint64_t vaddr;
126 if (!interface_->GetGlobalVariable(name, &vaddr) &&
127 (gnu_debugdata_interface_ == nullptr ||
128 !gnu_debugdata_interface_->GetGlobalVariable(name, &vaddr))) {
129 return false;
130 }
131
132 if (arch() == ARCH_ARM64) {
133 // Tagged pointer after Android R would lead top byte to have random values
134 // https://source.android.com/devices/tech/debug/tagged-pointers
135 vaddr &= (1ULL << 56) - 1;
136 }
137
138 // Check the .data section.
139 uint64_t vaddr_start = interface_->data_vaddr_start();
140 if (vaddr >= vaddr_start && vaddr < interface_->data_vaddr_end()) {
141 *memory_offset = vaddr - vaddr_start + interface_->data_offset();
142 return true;
143 }
144
145 // Check the .dynamic section.
146 vaddr_start = interface_->dynamic_vaddr_start();
147 if (vaddr >= vaddr_start && vaddr < interface_->dynamic_vaddr_end()) {
148 *memory_offset = vaddr - vaddr_start + interface_->dynamic_offset();
149 return true;
150 }
151
152 return false;
153 }
154
GetBuildID()155 std::string Elf::GetBuildID() {
156 if (!valid_) {
157 return "";
158 }
159 return interface_->GetBuildID();
160 }
161
GetLastError(ErrorData * data)162 void Elf::GetLastError(ErrorData* data) {
163 if (valid_) {
164 *data = interface_->last_error();
165 } else {
166 data->code = ERROR_INVALID_ELF;
167 data->address = 0;
168 }
169 }
170
GetLastErrorCode()171 ErrorCode Elf::GetLastErrorCode() {
172 if (valid_) {
173 return interface_->LastErrorCode();
174 }
175 return ERROR_INVALID_ELF;
176 }
177
GetLastErrorAddress()178 uint64_t Elf::GetLastErrorAddress() {
179 if (valid_) {
180 return interface_->LastErrorAddress();
181 }
182 return 0;
183 }
184
185 // The relative pc expectd by this function is relative to the start of the elf.
StepIfSignalHandler(uint64_t rel_pc,Regs * regs,Memory * process_memory)186 bool Elf::StepIfSignalHandler(uint64_t rel_pc, Regs* regs, Memory* process_memory) {
187 if (!valid_) {
188 return false;
189 }
190
191 // Convert the rel_pc to an elf_offset.
192 if (rel_pc < static_cast<uint64_t>(load_bias_)) {
193 return false;
194 }
195 return regs->StepIfSignalHandler(rel_pc - load_bias_, this, process_memory);
196 }
197
198 // The relative pc is always relative to the start of the map from which it comes.
Step(uint64_t rel_pc,Regs * regs,Memory * process_memory,bool * finished,bool * is_signal_frame)199 bool Elf::Step(uint64_t rel_pc, Regs* regs, Memory* process_memory, bool* finished,
200 bool* is_signal_frame) {
201 if (!valid_) {
202 return false;
203 }
204
205 // Lock during the step which can update information in the object.
206 std::lock_guard<std::mutex> guard(lock_);
207 return interface_->Step(rel_pc, regs, process_memory, finished, is_signal_frame);
208 }
209
IsValidElf(Memory * memory)210 bool Elf::IsValidElf(Memory* memory) {
211 if (memory == nullptr) {
212 return false;
213 }
214
215 // Verify that this is a valid elf file.
216 uint8_t e_ident[SELFMAG + 1];
217 if (!memory->ReadFully(0, e_ident, SELFMAG)) {
218 return false;
219 }
220
221 if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
222 return false;
223 }
224 return true;
225 }
226
GetInfo(Memory * memory,uint64_t * size)227 bool Elf::GetInfo(Memory* memory, uint64_t* size) {
228 if (!IsValidElf(memory)) {
229 return false;
230 }
231 *size = 0;
232
233 uint8_t class_type;
234 if (!memory->ReadFully(EI_CLASS, &class_type, 1)) {
235 return false;
236 }
237
238 // Get the maximum size of the elf data from the header.
239 if (class_type == ELFCLASS32) {
240 ElfInterface32::GetMaxSize(memory, size);
241 } else if (class_type == ELFCLASS64) {
242 ElfInterface64::GetMaxSize(memory, size);
243 } else {
244 return false;
245 }
246 return true;
247 }
248
IsValidPc(uint64_t pc)249 bool Elf::IsValidPc(uint64_t pc) {
250 if (!valid_ || (load_bias_ > 0 && pc < static_cast<uint64_t>(load_bias_))) {
251 return false;
252 }
253
254 if (interface_->IsValidPc(pc)) {
255 return true;
256 }
257
258 if (gnu_debugdata_interface_ != nullptr && gnu_debugdata_interface_->IsValidPc(pc)) {
259 return true;
260 }
261
262 return false;
263 }
264
GetTextRange(uint64_t * addr,uint64_t * size)265 bool Elf::GetTextRange(uint64_t* addr, uint64_t* size) {
266 if (!valid_) {
267 return false;
268 }
269
270 if (interface_->GetTextRange(addr, size)) {
271 *addr += load_bias_;
272 return true;
273 }
274
275 if (gnu_debugdata_interface_ != nullptr && gnu_debugdata_interface_->GetTextRange(addr, size)) {
276 *addr += load_bias_;
277 return true;
278 }
279
280 return false;
281 }
282
CreateInterfaceFromMemory(Memory * memory)283 ElfInterface* Elf::CreateInterfaceFromMemory(Memory* memory) {
284 if (!IsValidElf(memory)) {
285 return nullptr;
286 }
287
288 std::unique_ptr<ElfInterface> interface;
289 if (!memory->ReadFully(EI_CLASS, &class_type_, 1)) {
290 return nullptr;
291 }
292 if (class_type_ == ELFCLASS32) {
293 Elf32_Half e_machine;
294 if (!memory->ReadFully(EI_NIDENT + sizeof(Elf32_Half), &e_machine, sizeof(e_machine))) {
295 return nullptr;
296 }
297
298 machine_type_ = e_machine;
299 if (e_machine == EM_ARM) {
300 arch_ = ARCH_ARM;
301 interface.reset(new ElfInterfaceArm(memory));
302 } else if (e_machine == EM_386) {
303 arch_ = ARCH_X86;
304 interface.reset(new ElfInterface32(memory));
305 } else if (e_machine == EM_MIPS) {
306 arch_ = ARCH_MIPS;
307 interface.reset(new ElfInterface32(memory));
308 } else {
309 // Unsupported.
310 return nullptr;
311 }
312 } else if (class_type_ == ELFCLASS64) {
313 Elf64_Half e_machine;
314 if (!memory->ReadFully(EI_NIDENT + sizeof(Elf64_Half), &e_machine, sizeof(e_machine))) {
315 return nullptr;
316 }
317
318 machine_type_ = e_machine;
319 if (e_machine == EM_AARCH64) {
320 arch_ = ARCH_ARM64;
321 } else if (e_machine == EM_X86_64) {
322 arch_ = ARCH_X86_64;
323 } else if (e_machine == EM_MIPS) {
324 arch_ = ARCH_MIPS64;
325 } else if (e_machine == EM_RISCV) {
326 arch_ = ARCH_RISCV64;
327 } else {
328 // Unsupported.
329 return nullptr;
330 }
331 interface.reset(new ElfInterface64(memory));
332 }
333
334 return interface.release();
335 }
336
GetLoadBias(Memory * memory)337 int64_t Elf::GetLoadBias(Memory* memory) {
338 if (!IsValidElf(memory)) {
339 return 0;
340 }
341
342 uint8_t class_type;
343 if (!memory->Read(EI_CLASS, &class_type, 1)) {
344 return 0;
345 }
346
347 if (class_type == ELFCLASS32) {
348 return ElfInterface::GetLoadBias<Elf32_Ehdr, Elf32_Phdr>(memory);
349 } else if (class_type == ELFCLASS64) {
350 return ElfInterface::GetLoadBias<Elf64_Ehdr, Elf64_Phdr>(memory);
351 }
352 return 0;
353 }
354
SetCachingEnabled(bool enable)355 void Elf::SetCachingEnabled(bool enable) {
356 if (!cache_enabled_ && enable) {
357 cache_enabled_ = true;
358 cache_ =
359 new std::unordered_map<std::string, std::unordered_map<uint64_t, std::shared_ptr<Elf>>>;
360 cache_lock_ = new std::mutex;
361 } else if (cache_enabled_ && !enable) {
362 cache_enabled_ = false;
363 delete cache_;
364 delete cache_lock_;
365 }
366 }
367
CacheLock()368 void Elf::CacheLock() {
369 cache_lock_->lock();
370 }
371
CacheUnlock()372 void Elf::CacheUnlock() {
373 cache_lock_->unlock();
374 }
375
CacheAdd(MapInfo * info)376 void Elf::CacheAdd(MapInfo* info) {
377 if (!info->elf()->valid()) {
378 return;
379 }
380 (*cache_)[std::string(info->name())].emplace(info->elf_start_offset(), info->elf());
381 }
382
CacheGet(MapInfo * info)383 bool Elf::CacheGet(MapInfo* info) {
384 auto name_entry = cache_->find(std::string(info->name()));
385 if (name_entry == cache_->end()) {
386 return false;
387 }
388 // First look to see if there is a zero offset entry, this indicates
389 // the whole elf is the file.
390 auto& offset_cache = name_entry->second;
391 uint64_t elf_start_offset = 0;
392 auto entry = offset_cache.find(elf_start_offset);
393 if (entry == offset_cache.end()) {
394 // Try and find using the current offset.
395 elf_start_offset = info->offset();
396 entry = offset_cache.find(elf_start_offset);
397 if (entry == offset_cache.end()) {
398 // If this is an execute map, then see if the previous read-only
399 // map is the start of the elf.
400 if (!(info->flags() & PROT_EXEC)) {
401 return false;
402 }
403 auto prev_map = info->GetPrevRealMap();
404 if (prev_map == nullptr || info->offset() <= prev_map->offset() ||
405 (prev_map->flags() != PROT_READ)) {
406 return false;
407 }
408 elf_start_offset = prev_map->offset();
409 entry = offset_cache.find(elf_start_offset);
410 if (entry == offset_cache.end()) {
411 return false;
412 }
413 }
414 }
415
416 info->set_elf(entry->second);
417 info->set_elf_start_offset(elf_start_offset);
418 info->set_elf_offset(info->offset() - elf_start_offset);
419 return true;
420 }
421
GetBuildID(Memory * memory)422 std::string Elf::GetBuildID(Memory* memory) {
423 if (!IsValidElf(memory)) {
424 return "";
425 }
426
427 uint8_t class_type;
428 if (!memory->Read(EI_CLASS, &class_type, 1)) {
429 return "";
430 }
431
432 if (class_type == ELFCLASS32) {
433 return ElfInterface::ReadBuildIDFromMemory<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr>(memory);
434 } else if (class_type == ELFCLASS64) {
435 return ElfInterface::ReadBuildIDFromMemory<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr>(memory);
436 }
437 return "";
438 }
439
GetPrintableBuildID(std::string & build_id)440 std::string Elf::GetPrintableBuildID(std::string& build_id) {
441 if (build_id.empty()) {
442 return "";
443 }
444 std::string printable_build_id;
445 for (const char& c : build_id) {
446 // Use %hhx to avoid sign extension on abis that have signed chars.
447 printable_build_id += android::base::StringPrintf("%02hhx", c);
448 }
449 return printable_build_id;
450 }
451
GetPrintableBuildID()452 std::string Elf::GetPrintableBuildID() {
453 std::string build_id = GetBuildID();
454 return Elf::GetPrintableBuildID(build_id);
455 }
456
457 } // namespace unwindstack
458