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 <string.h>
19
20 #include <memory>
21 #include <mutex>
22 #include <string>
23 #include <utility>
24
25 #define LOG_TAG "unwind"
26 #include <log/log.h>
27
28 #include <unwindstack/Elf.h>
29 #include <unwindstack/ElfInterface.h>
30 #include <unwindstack/MapInfo.h>
31 #include <unwindstack/Memory.h>
32 #include <unwindstack/Regs.h>
33
34 #include "ElfInterfaceArm.h"
35 #include "Symbols.h"
36
37 namespace unwindstack {
38
39 bool Elf::cache_enabled_;
40 std::unordered_map<std::string, std::pair<std::shared_ptr<Elf>, bool>>* Elf::cache_;
41 std::mutex* Elf::cache_lock_;
42
Init()43 bool Elf::Init() {
44 load_bias_ = 0;
45 if (!memory_) {
46 return false;
47 }
48
49 interface_.reset(CreateInterfaceFromMemory(memory_.get()));
50 if (!interface_) {
51 return false;
52 }
53
54 valid_ = interface_->Init(&load_bias_);
55 if (valid_) {
56 interface_->InitHeaders(load_bias_);
57 InitGnuDebugdata();
58 } else {
59 interface_.reset(nullptr);
60 }
61 return valid_;
62 }
63
64 // It is expensive to initialize the .gnu_debugdata section. Provide a method
65 // to initialize this data separately.
InitGnuDebugdata()66 void Elf::InitGnuDebugdata() {
67 if (!valid_ || interface_->gnu_debugdata_offset() == 0) {
68 return;
69 }
70
71 gnu_debugdata_memory_.reset(interface_->CreateGnuDebugdataMemory());
72 gnu_debugdata_interface_.reset(CreateInterfaceFromMemory(gnu_debugdata_memory_.get()));
73 ElfInterface* gnu = gnu_debugdata_interface_.get();
74 if (gnu == nullptr) {
75 return;
76 }
77
78 // Ignore the load_bias from the compressed section, the correct load bias
79 // is in the uncompressed data.
80 uint64_t load_bias;
81 if (gnu->Init(&load_bias)) {
82 gnu->InitHeaders(load_bias);
83 interface_->SetGnuDebugdataInterface(gnu);
84 } else {
85 // Free all of the memory associated with the gnu_debugdata section.
86 gnu_debugdata_memory_.reset(nullptr);
87 gnu_debugdata_interface_.reset(nullptr);
88 }
89 }
90
Invalidate()91 void Elf::Invalidate() {
92 interface_.reset(nullptr);
93 valid_ = false;
94 }
95
GetSoname()96 std::string Elf::GetSoname() {
97 std::lock_guard<std::mutex> guard(lock_);
98 if (!valid_) {
99 return "";
100 }
101 return interface_->GetSoname();
102 }
103
GetRelPc(uint64_t pc,const MapInfo * map_info)104 uint64_t Elf::GetRelPc(uint64_t pc, const MapInfo* map_info) {
105 return pc - map_info->start + load_bias_ + map_info->elf_offset;
106 }
107
GetFunctionName(uint64_t addr,std::string * name,uint64_t * func_offset)108 bool Elf::GetFunctionName(uint64_t addr, std::string* name, uint64_t* func_offset) {
109 std::lock_guard<std::mutex> guard(lock_);
110 return valid_ && (interface_->GetFunctionName(addr, name, func_offset) ||
111 (gnu_debugdata_interface_ &&
112 gnu_debugdata_interface_->GetFunctionName(addr, name, func_offset)));
113 }
114
GetGlobalVariable(const std::string & name,uint64_t * memory_address)115 bool Elf::GetGlobalVariable(const std::string& name, uint64_t* memory_address) {
116 if (!valid_) {
117 return false;
118 }
119
120 if (!interface_->GetGlobalVariable(name, memory_address) &&
121 (gnu_debugdata_interface_ == nullptr ||
122 !gnu_debugdata_interface_->GetGlobalVariable(name, memory_address))) {
123 return false;
124 }
125
126 // Adjust by the load bias.
127 if (*memory_address < load_bias_) {
128 return false;
129 }
130
131 *memory_address -= load_bias_;
132
133 // If this winds up in the dynamic section, then we might need to adjust
134 // the address.
135 uint64_t dynamic_end = interface_->dynamic_vaddr() + interface_->dynamic_size();
136 if (*memory_address >= interface_->dynamic_vaddr() && *memory_address < dynamic_end) {
137 if (interface_->dynamic_vaddr() > interface_->dynamic_offset()) {
138 *memory_address -= interface_->dynamic_vaddr() - interface_->dynamic_offset();
139 } else {
140 *memory_address += interface_->dynamic_offset() - interface_->dynamic_vaddr();
141 }
142 }
143 return true;
144 }
145
GetBuildID()146 std::string Elf::GetBuildID() {
147 if (!valid_) {
148 return "";
149 }
150 return interface_->GetBuildID();
151 }
152
GetLastError(ErrorData * data)153 void Elf::GetLastError(ErrorData* data) {
154 if (valid_) {
155 *data = interface_->last_error();
156 }
157 }
158
GetLastErrorCode()159 ErrorCode Elf::GetLastErrorCode() {
160 if (valid_) {
161 return interface_->LastErrorCode();
162 }
163 return ERROR_INVALID_ELF;
164 }
165
GetLastErrorAddress()166 uint64_t Elf::GetLastErrorAddress() {
167 if (valid_) {
168 return interface_->LastErrorAddress();
169 }
170 return 0;
171 }
172
173 // 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)174 bool Elf::StepIfSignalHandler(uint64_t rel_pc, Regs* regs, Memory* process_memory) {
175 if (!valid_) {
176 return false;
177 }
178 return regs->StepIfSignalHandler(rel_pc, this, process_memory);
179 }
180
181 // 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)182 bool Elf::Step(uint64_t rel_pc, Regs* regs, Memory* process_memory, bool* finished) {
183 if (!valid_) {
184 return false;
185 }
186
187 // Lock during the step which can update information in the object.
188 std::lock_guard<std::mutex> guard(lock_);
189 return interface_->Step(rel_pc, regs, process_memory, finished);
190 }
191
IsValidElf(Memory * memory)192 bool Elf::IsValidElf(Memory* memory) {
193 if (memory == nullptr) {
194 return false;
195 }
196
197 // Verify that this is a valid elf file.
198 uint8_t e_ident[SELFMAG + 1];
199 if (!memory->ReadFully(0, e_ident, SELFMAG)) {
200 return false;
201 }
202
203 if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
204 return false;
205 }
206 return true;
207 }
208
GetInfo(Memory * memory,uint64_t * size)209 bool Elf::GetInfo(Memory* memory, uint64_t* size) {
210 if (!IsValidElf(memory)) {
211 return false;
212 }
213 *size = 0;
214
215 uint8_t class_type;
216 if (!memory->ReadFully(EI_CLASS, &class_type, 1)) {
217 return false;
218 }
219
220 // Get the maximum size of the elf data from the header.
221 if (class_type == ELFCLASS32) {
222 ElfInterface32::GetMaxSize(memory, size);
223 } else if (class_type == ELFCLASS64) {
224 ElfInterface64::GetMaxSize(memory, size);
225 } else {
226 return false;
227 }
228 return true;
229 }
230
IsValidPc(uint64_t pc)231 bool Elf::IsValidPc(uint64_t pc) {
232 if (!valid_ || pc < load_bias_) {
233 return false;
234 }
235
236 if (interface_->IsValidPc(pc)) {
237 return true;
238 }
239
240 if (gnu_debugdata_interface_ != nullptr && gnu_debugdata_interface_->IsValidPc(pc)) {
241 return true;
242 }
243
244 return false;
245 }
246
CreateInterfaceFromMemory(Memory * memory)247 ElfInterface* Elf::CreateInterfaceFromMemory(Memory* memory) {
248 if (!IsValidElf(memory)) {
249 return nullptr;
250 }
251
252 std::unique_ptr<ElfInterface> interface;
253 if (!memory->ReadFully(EI_CLASS, &class_type_, 1)) {
254 return nullptr;
255 }
256 if (class_type_ == ELFCLASS32) {
257 Elf32_Half e_machine;
258 if (!memory->ReadFully(EI_NIDENT + sizeof(Elf32_Half), &e_machine, sizeof(e_machine))) {
259 return nullptr;
260 }
261
262 machine_type_ = e_machine;
263 if (e_machine == EM_ARM) {
264 arch_ = ARCH_ARM;
265 interface.reset(new ElfInterfaceArm(memory));
266 } else if (e_machine == EM_386) {
267 arch_ = ARCH_X86;
268 interface.reset(new ElfInterface32(memory));
269 } else if (e_machine == EM_MIPS) {
270 arch_ = ARCH_MIPS;
271 interface.reset(new ElfInterface32(memory));
272 } else {
273 // Unsupported.
274 ALOGI("32 bit elf that is neither arm nor x86 nor mips: e_machine = %d\n", e_machine);
275 return nullptr;
276 }
277 } else if (class_type_ == ELFCLASS64) {
278 Elf64_Half e_machine;
279 if (!memory->ReadFully(EI_NIDENT + sizeof(Elf64_Half), &e_machine, sizeof(e_machine))) {
280 return nullptr;
281 }
282
283 machine_type_ = e_machine;
284 if (e_machine == EM_AARCH64) {
285 arch_ = ARCH_ARM64;
286 } else if (e_machine == EM_X86_64) {
287 arch_ = ARCH_X86_64;
288 } else if (e_machine == EM_MIPS) {
289 arch_ = ARCH_MIPS64;
290 } else {
291 // Unsupported.
292 ALOGI("64 bit elf that is neither aarch64 nor x86_64 nor mips64: e_machine = %d\n",
293 e_machine);
294 return nullptr;
295 }
296 interface.reset(new ElfInterface64(memory));
297 }
298
299 return interface.release();
300 }
301
GetLoadBias(Memory * memory)302 uint64_t Elf::GetLoadBias(Memory* memory) {
303 if (!IsValidElf(memory)) {
304 return 0;
305 }
306
307 uint8_t class_type;
308 if (!memory->Read(EI_CLASS, &class_type, 1)) {
309 return 0;
310 }
311
312 if (class_type == ELFCLASS32) {
313 return ElfInterface::GetLoadBias<Elf32_Ehdr, Elf32_Phdr>(memory);
314 } else if (class_type == ELFCLASS64) {
315 return ElfInterface::GetLoadBias<Elf64_Ehdr, Elf64_Phdr>(memory);
316 }
317 return 0;
318 }
319
SetCachingEnabled(bool enable)320 void Elf::SetCachingEnabled(bool enable) {
321 if (!cache_enabled_ && enable) {
322 cache_enabled_ = true;
323 cache_ = new std::unordered_map<std::string, std::pair<std::shared_ptr<Elf>, bool>>;
324 cache_lock_ = new std::mutex;
325 } else if (cache_enabled_ && !enable) {
326 cache_enabled_ = false;
327 delete cache_;
328 delete cache_lock_;
329 }
330 }
331
CacheLock()332 void Elf::CacheLock() {
333 cache_lock_->lock();
334 }
335
CacheUnlock()336 void Elf::CacheUnlock() {
337 cache_lock_->unlock();
338 }
339
CacheAdd(MapInfo * info)340 void Elf::CacheAdd(MapInfo* info) {
341 // If elf_offset != 0, then cache both name:offset and name.
342 // The cached name is used to do lookups if multiple maps for the same
343 // named elf file exist.
344 // For example, if there are two maps boot.odex:1000 and boot.odex:2000
345 // where each reference the entire boot.odex, the cache will properly
346 // use the same cached elf object.
347
348 if (info->offset == 0 || info->elf_offset != 0) {
349 (*cache_)[info->name] = std::make_pair(info->elf, true);
350 }
351
352 if (info->offset != 0) {
353 // The second element in the pair indicates whether elf_offset should
354 // be set to offset when getting out of the cache.
355 (*cache_)[info->name + ':' + std::to_string(info->offset)] =
356 std::make_pair(info->elf, info->elf_offset != 0);
357 }
358 }
359
CacheAfterCreateMemory(MapInfo * info)360 bool Elf::CacheAfterCreateMemory(MapInfo* info) {
361 if (info->name.empty() || info->offset == 0 || info->elf_offset == 0) {
362 return false;
363 }
364
365 auto entry = cache_->find(info->name);
366 if (entry == cache_->end()) {
367 return false;
368 }
369
370 // In this case, the whole file is the elf, and the name has already
371 // been cached. Add an entry at name:offset to get this directly out
372 // of the cache next time.
373 info->elf = entry->second.first;
374 (*cache_)[info->name + ':' + std::to_string(info->offset)] = std::make_pair(info->elf, true);
375 return true;
376 }
377
CacheGet(MapInfo * info)378 bool Elf::CacheGet(MapInfo* info) {
379 std::string name(info->name);
380 if (info->offset != 0) {
381 name += ':' + std::to_string(info->offset);
382 }
383 auto entry = cache_->find(name);
384 if (entry != cache_->end()) {
385 info->elf = entry->second.first;
386 if (entry->second.second) {
387 info->elf_offset = info->offset;
388 }
389 return true;
390 }
391 return false;
392 }
393
GetBuildID(Memory * memory)394 std::string Elf::GetBuildID(Memory* memory) {
395 if (!IsValidElf(memory)) {
396 return "";
397 }
398
399 uint8_t class_type;
400 if (!memory->Read(EI_CLASS, &class_type, 1)) {
401 return "";
402 }
403
404 if (class_type == ELFCLASS32) {
405 return ElfInterface::ReadBuildIDFromMemory<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr>(memory);
406 } else if (class_type == ELFCLASS64) {
407 return ElfInterface::ReadBuildIDFromMemory<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr>(memory);
408 }
409 return "";
410 }
411
412 } // namespace unwindstack
413