1 /*
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 "read_elf.h"
18 #include "read_apk.h"
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24
25 #include <algorithm>
26 #include <limits>
27
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30
31 #pragma clang diagnostic push
32 #pragma clang diagnostic ignored "-Wunused-parameter"
33
34 #include <llvm/ADT/StringRef.h>
35 #include <llvm/Object/ELFObjectFile.h>
36 #include <llvm/Object/ObjectFile.h>
37
38 #pragma clang diagnostic pop
39
40 #include "JITDebugReader.h"
41 #include "utils.h"
42
43 namespace simpleperf {
44
45 const static char* ELF_NOTE_GNU = "GNU";
46 const static int NT_GNU_BUILD_ID = 3;
47
operator <<(std::ostream & os,const ElfStatus & status)48 std::ostream& operator<<(std::ostream& os, const ElfStatus& status) {
49 switch (status) {
50 case ElfStatus::NO_ERROR:
51 os << "No error";
52 break;
53 case ElfStatus::FILE_NOT_FOUND:
54 os << "File not found";
55 break;
56 case ElfStatus::READ_FAILED:
57 os << "Read failed";
58 break;
59 case ElfStatus::FILE_MALFORMED:
60 os << "Malformed file";
61 break;
62 case ElfStatus::NO_SYMBOL_TABLE:
63 os << "No symbol table";
64 break;
65 case ElfStatus::NO_BUILD_ID:
66 os << "No build id";
67 break;
68 case ElfStatus::BUILD_ID_MISMATCH:
69 os << "Build id mismatch";
70 break;
71 case ElfStatus::SECTION_NOT_FOUND:
72 os << "Section not found";
73 break;
74 }
75 return os;
76 }
77
IsValidElfFileMagic(const char * buf,size_t buf_size)78 bool IsValidElfFileMagic(const char* buf, size_t buf_size) {
79 static const char elf_magic[] = {0x7f, 'E', 'L', 'F'};
80 return (buf_size >= 4u && memcmp(buf, elf_magic, 4) == 0);
81 }
82
IsValidElfFile(int fd,uint64_t file_offset)83 ElfStatus IsValidElfFile(int fd, uint64_t file_offset) {
84 char buf[4];
85 if (!android::base::ReadFullyAtOffset(fd, buf, 4, file_offset)) {
86 return ElfStatus::READ_FAILED;
87 }
88 return IsValidElfFileMagic(buf, 4) ? ElfStatus::NO_ERROR : ElfStatus::FILE_MALFORMED;
89 }
90
GetBuildIdFromNoteSection(const char * section,size_t section_size,BuildId * build_id)91 bool GetBuildIdFromNoteSection(const char* section, size_t section_size, BuildId* build_id) {
92 const char* p = section;
93 const char* end = p + section_size;
94 while (p < end) {
95 if (p + 12 >= end) {
96 return false;
97 }
98 uint32_t namesz;
99 uint32_t descsz;
100 uint32_t type;
101 MoveFromBinaryFormat(namesz, p);
102 MoveFromBinaryFormat(descsz, p);
103 MoveFromBinaryFormat(type, p);
104 namesz = Align(namesz, 4);
105 descsz = Align(descsz, 4);
106 if ((type == NT_GNU_BUILD_ID) && (p < end) && (strcmp(p, ELF_NOTE_GNU) == 0)) {
107 const char* desc_start = p + namesz;
108 const char* desc_end = desc_start + descsz;
109 if (desc_start > p && desc_start < desc_end && desc_end <= end) {
110 *build_id = BuildId(p + namesz, descsz);
111 return true;
112 } else {
113 return false;
114 }
115 }
116 p += namesz + descsz;
117 }
118 return false;
119 }
120
GetBuildIdFromNoteFile(const std::string & filename,BuildId * build_id)121 ElfStatus GetBuildIdFromNoteFile(const std::string& filename, BuildId* build_id) {
122 std::string content;
123 if (!android::base::ReadFileToString(filename, &content)) {
124 return ElfStatus::READ_FAILED;
125 }
126 if (!GetBuildIdFromNoteSection(content.c_str(), content.size(), build_id)) {
127 return ElfStatus::NO_BUILD_ID;
128 }
129 return ElfStatus::NO_ERROR;
130 }
131
IsArmMappingSymbol(const char * name)132 bool IsArmMappingSymbol(const char* name) {
133 // Mapping symbols in arm, which are described in "ELF for ARM Architecture" and
134 // "ELF for ARM 64-bit Architecture". The regular expression to match mapping symbol
135 // is ^\$(a|d|t|x)(\..*)?$
136 return name[0] == '$' && strchr("adtx", name[1]) != nullptr &&
137 (name[2] == '\0' || name[2] == '.');
138 }
139
140 namespace {
141
142 struct BinaryWrapper {
143 std::unique_ptr<llvm::MemoryBuffer> buffer;
144 std::unique_ptr<llvm::object::ObjectFile> obj;
145 };
146
OpenObjectFile(const std::string & filename,uint64_t file_offset,uint64_t file_size,BinaryWrapper * wrapper)147 static ElfStatus OpenObjectFile(const std::string& filename, uint64_t file_offset,
148 uint64_t file_size, BinaryWrapper* wrapper) {
149 if (!IsRegularFile(filename)) {
150 return ElfStatus::FILE_NOT_FOUND;
151 }
152 android::base::unique_fd fd = FileHelper::OpenReadOnly(filename);
153 if (fd == -1) {
154 return ElfStatus::READ_FAILED;
155 }
156 if (file_size == 0) {
157 file_size = GetFileSize(filename);
158 if (file_size == 0) {
159 return ElfStatus::READ_FAILED;
160 }
161 }
162 ElfStatus status = IsValidElfFile(fd, file_offset);
163 if (status != ElfStatus::NO_ERROR) {
164 return status;
165 }
166 auto buffer_or_err = llvm::MemoryBuffer::getFileSlice(filename, file_size, file_offset);
167 if (!buffer_or_err) {
168 return ElfStatus::READ_FAILED;
169 }
170 auto obj_or_err =
171 llvm::object::ObjectFile::createObjectFile(buffer_or_err.get()->getMemBufferRef());
172 if (!obj_or_err) {
173 return ElfStatus::READ_FAILED;
174 }
175 wrapper->buffer = std::move(buffer_or_err.get());
176 wrapper->obj = std::move(obj_or_err.get());
177 return ElfStatus::NO_ERROR;
178 }
179
OpenObjectFileInMemory(const char * data,size_t size,BinaryWrapper * wrapper)180 static ElfStatus OpenObjectFileInMemory(const char* data, size_t size, BinaryWrapper* wrapper) {
181 auto buffer = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(data, size));
182 auto obj_or_err = llvm::object::ObjectFile::createObjectFile(buffer->getMemBufferRef());
183 if (!obj_or_err) {
184 return ElfStatus::FILE_MALFORMED;
185 }
186 wrapper->buffer = std::move(buffer);
187 wrapper->obj = std::move(obj_or_err.get());
188 return ElfStatus::NO_ERROR;
189 }
190
GetSymbolFlags(const llvm::object::ELFSymbolRef & symbol)191 static inline llvm::Expected<uint32_t> GetSymbolFlags(const llvm::object::ELFSymbolRef& symbol) {
192 return symbol.getFlags();
193 }
194
GetSymbolValue(const llvm::object::ELFSymbolRef & symbol)195 static inline llvm::Expected<uint64_t> GetSymbolValue(const llvm::object::ELFSymbolRef& symbol) {
196 return symbol.getValue();
197 }
198
GetSectionName(const llvm::object::SectionRef & section)199 static inline llvm::Expected<llvm::StringRef> GetSectionName(
200 const llvm::object::SectionRef& section) {
201 return section.getName();
202 }
203
GetSectionContents(const llvm::object::SectionRef & section)204 static inline llvm::Expected<llvm::StringRef> GetSectionContents(
205 const llvm::object::SectionRef& section) {
206 return section.getContents();
207 }
208
209 template <typename ELFT>
GetELFFile(const llvm::object::ELFObjectFile<ELFT> * obj)210 static inline const llvm::object::ELFFile<ELFT>* GetELFFile(
211 const llvm::object::ELFObjectFile<ELFT>* obj) {
212 return &obj->getELFFile();
213 }
214
215 template <typename ELFT>
GetELFHeader(const llvm::object::ELFFile<ELFT> * elf)216 static inline const typename ELFT::Ehdr& GetELFHeader(const llvm::object::ELFFile<ELFT>* elf) {
217 return elf->getHeader();
218 }
219
220 template <typename ELFT>
GetELFProgramHeaders(const llvm::object::ELFFile<ELFT> * elf)221 static inline llvm::Expected<typename ELFT::PhdrRange> GetELFProgramHeaders(
222 const llvm::object::ELFFile<ELFT>* elf) {
223 return elf->program_headers();
224 }
225
226 template <typename ELFT>
GetELFSectionName(const llvm::object::ELFFile<ELFT> * elf,const typename ELFT::Shdr & section_header)227 static inline llvm::Expected<llvm::StringRef> GetELFSectionName(
228 const llvm::object::ELFFile<ELFT>* elf, const typename ELFT::Shdr& section_header) {
229 return elf->getSectionName(section_header);
230 }
231
ReadSymbolTable(llvm::object::symbol_iterator sym_begin,llvm::object::symbol_iterator sym_end,const std::function<void (const ElfFileSymbol &)> & callback,bool is_arm,const llvm::object::section_iterator & section_end)232 void ReadSymbolTable(llvm::object::symbol_iterator sym_begin, llvm::object::symbol_iterator sym_end,
233 const std::function<void(const ElfFileSymbol&)>& callback, bool is_arm,
234 const llvm::object::section_iterator& section_end) {
235 for (; sym_begin != sym_end; ++sym_begin) {
236 ElfFileSymbol symbol;
237 auto symbol_ref = static_cast<const llvm::object::ELFSymbolRef*>(&*sym_begin);
238 // Exclude undefined symbols, otherwise we may wrongly use them as labels in functions.
239 if (auto flags = GetSymbolFlags(*symbol_ref);
240 !flags || (flags.get() & symbol_ref->SF_Undefined)) {
241 continue;
242 }
243 llvm::Expected<llvm::object::section_iterator> section_it_or_err = symbol_ref->getSection();
244 if (!section_it_or_err) {
245 continue;
246 }
247 // Symbols in .dynsym section don't have associated section.
248 if (section_it_or_err.get() != section_end) {
249 llvm::Expected<llvm::StringRef> section_name = GetSectionName(*section_it_or_err.get());
250 if (!section_name || section_name.get().empty()) {
251 continue;
252 }
253 if (section_name.get() == ".text") {
254 symbol.is_in_text_section = true;
255 }
256 }
257
258 llvm::Expected<llvm::StringRef> symbol_name_or_err = symbol_ref->getName();
259 if (!symbol_name_or_err || symbol_name_or_err.get().empty()) {
260 continue;
261 }
262
263 symbol.name = symbol_name_or_err.get();
264 llvm::Expected<uint64_t> symbol_value = GetSymbolValue(*symbol_ref);
265 if (!symbol_value) {
266 continue;
267 }
268 symbol.vaddr = symbol_value.get();
269 if ((symbol.vaddr & 1) != 0 && is_arm) {
270 // Arm sets bit 0 to mark it as thumb code, remove the flag.
271 symbol.vaddr &= ~1;
272 }
273 symbol.len = symbol_ref->getSize();
274 llvm::object::SymbolRef::Type symbol_type = *symbol_ref->getType();
275 if (symbol_type == llvm::object::SymbolRef::ST_Function) {
276 symbol.is_func = true;
277 } else if (symbol_type == llvm::object::SymbolRef::ST_Unknown) {
278 if (symbol.is_in_text_section) {
279 symbol.is_label = true;
280 if (is_arm) {
281 // Remove mapping symbols in arm.
282 const char* p = (symbol.name.compare(0, linker_prefix.size(), linker_prefix) == 0)
283 ? symbol.name.c_str() + linker_prefix.size()
284 : symbol.name.c_str();
285 if (IsArmMappingSymbol(p)) {
286 symbol.is_label = false;
287 }
288 }
289 }
290 }
291
292 callback(symbol);
293 }
294 }
295
296 template <class ELFT>
AddSymbolForPltSection(const llvm::object::ELFObjectFile<ELFT> * elf,const std::function<void (const ElfFileSymbol &)> & callback)297 void AddSymbolForPltSection(const llvm::object::ELFObjectFile<ELFT>* elf,
298 const std::function<void(const ElfFileSymbol&)>& callback) {
299 // We may sample instructions in .plt section if the program
300 // calls functions from shared libraries. Different architectures use
301 // different formats to store .plt section, so it needs a lot of work to match
302 // instructions in .plt section to symbols. As samples in .plt section rarely
303 // happen, and .plt section can hardly be a performance bottleneck, we can
304 // just use a symbol @plt to represent instructions in .plt section.
305 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
306 const llvm::object::ELFSectionRef& section_ref = *it;
307 llvm::Expected<llvm::StringRef> section_name = GetSectionName(section_ref);
308 if (!section_name || section_name.get() != ".plt") {
309 continue;
310 }
311 const auto* shdr = elf->getSection(section_ref.getRawDataRefImpl());
312 if (shdr == nullptr) {
313 return;
314 }
315 ElfFileSymbol symbol;
316 symbol.vaddr = shdr->sh_addr;
317 symbol.len = shdr->sh_size;
318 symbol.is_func = true;
319 symbol.is_label = true;
320 symbol.is_in_text_section = true;
321 symbol.name = "@plt";
322 callback(symbol);
323 return;
324 }
325 }
326
327 template <class ELFT>
CheckSymbolSections(const llvm::object::ELFObjectFile<ELFT> * elf,bool * has_symtab,bool * has_dynsym)328 void CheckSymbolSections(const llvm::object::ELFObjectFile<ELFT>* elf, bool* has_symtab,
329 bool* has_dynsym) {
330 *has_symtab = false;
331 *has_dynsym = false;
332 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
333 const llvm::object::ELFSectionRef& section_ref = *it;
334 llvm::Expected<llvm::StringRef> section_name = GetSectionName(section_ref);
335 if (!section_name) {
336 continue;
337 }
338 if (section_name.get() == ".dynsym") {
339 *has_dynsym = true;
340 } else if (section_name.get() == ".symtab") {
341 *has_symtab = true;
342 }
343 }
344 }
345
346 template <typename T>
347 class ElfFileImpl {};
348
349 template <typename ELFT>
350 class ElfFileImpl<llvm::object::ELFObjectFile<ELFT>> : public ElfFile {
351 public:
ElfFileImpl(BinaryWrapper && wrapper,const llvm::object::ELFObjectFile<ELFT> * elf_obj)352 ElfFileImpl(BinaryWrapper&& wrapper, const llvm::object::ELFObjectFile<ELFT>* elf_obj)
353 : wrapper_(std::move(wrapper)), elf_obj_(elf_obj), elf_(GetELFFile(elf_obj_)) {}
354
Is64Bit()355 bool Is64Bit() override { return GetELFHeader(elf_).getFileClass() == llvm::ELF::ELFCLASS64; }
356
GetMemoryBuffer()357 llvm::MemoryBuffer* GetMemoryBuffer() override { return wrapper_.buffer.get(); }
358
GetProgramHeader()359 std::vector<ElfSegment> GetProgramHeader() override {
360 auto program_headers = GetELFProgramHeaders(elf_);
361 if (!program_headers) {
362 return {};
363 }
364 std::vector<ElfSegment> segments(program_headers.get().size());
365 for (size_t i = 0; i < program_headers.get().size(); i++) {
366 const auto& phdr = program_headers.get()[i];
367 segments[i].vaddr = phdr.p_vaddr;
368 segments[i].file_offset = phdr.p_offset;
369 segments[i].file_size = phdr.p_filesz;
370 segments[i].is_executable =
371 (phdr.p_type == llvm::ELF::PT_LOAD) && (phdr.p_flags & llvm::ELF::PF_X);
372 segments[i].is_load = (phdr.p_type == llvm::ELF::PT_LOAD);
373 }
374 return segments;
375 }
376
GetSectionHeader()377 std::vector<ElfSection> GetSectionHeader() override {
378 auto section_headers_or_err = elf_->sections();
379 if (!section_headers_or_err) {
380 return {};
381 }
382 const auto& section_headers = section_headers_or_err.get();
383 std::vector<ElfSection> sections(section_headers.size());
384 for (size_t i = 0; i < section_headers.size(); i++) {
385 const auto& shdr = section_headers[i];
386 if (auto name = GetELFSectionName(elf_, shdr); name) {
387 sections[i].name = name.get();
388 }
389 sections[i].vaddr = shdr.sh_addr;
390 sections[i].file_offset = shdr.sh_offset;
391 sections[i].size = shdr.sh_size;
392 }
393 return sections;
394 }
395
GetBuildId(BuildId * build_id)396 ElfStatus GetBuildId(BuildId* build_id) override {
397 llvm::StringRef data = elf_obj_->getData();
398 const char* binary_start = data.data();
399 const char* binary_end = data.data() + data.size();
400 for (auto it = elf_obj_->section_begin(); it != elf_obj_->section_end(); ++it) {
401 const llvm::object::ELFSectionRef& section_ref = *it;
402 if (section_ref.getType() == llvm::ELF::SHT_NOTE) {
403 llvm::Expected<llvm::StringRef> content = GetSectionContents(section_ref);
404 if (!content) {
405 return ElfStatus::NO_BUILD_ID;
406 }
407 const llvm::StringRef& data = content.get();
408 if (data.data() < binary_start || data.data() + data.size() > binary_end) {
409 return ElfStatus::NO_BUILD_ID;
410 }
411 if (GetBuildIdFromNoteSection(data.data(), data.size(), build_id)) {
412 return ElfStatus::NO_ERROR;
413 }
414 }
415 }
416 return ElfStatus::NO_BUILD_ID;
417 }
418
ParseSymbols(const ParseSymbolCallback & callback)419 ElfStatus ParseSymbols(const ParseSymbolCallback& callback) override {
420 auto machine = GetELFHeader(elf_).e_machine;
421 bool is_arm = (machine == llvm::ELF::EM_ARM || machine == llvm::ELF::EM_AARCH64);
422 AddSymbolForPltSection(elf_obj_, callback);
423 // Some applications deliberately ship elf files with broken section tables.
424 // So check the existence of .symtab section and .dynsym section before reading symbols.
425 bool has_symtab;
426 bool has_dynsym;
427 CheckSymbolSections(elf_obj_, &has_symtab, &has_dynsym);
428 if (has_symtab && elf_obj_->symbol_begin() != elf_obj_->symbol_end()) {
429 ReadSymbolTable(elf_obj_->symbol_begin(), elf_obj_->symbol_end(), callback, is_arm,
430 elf_obj_->section_end());
431 return ElfStatus::NO_ERROR;
432 } else if (has_dynsym && elf_obj_->dynamic_symbol_begin()->getRawDataRefImpl() !=
433 llvm::object::DataRefImpl()) {
434 ReadSymbolTable(elf_obj_->dynamic_symbol_begin(), elf_obj_->dynamic_symbol_end(), callback,
435 is_arm, elf_obj_->section_end());
436 }
437 std::string debugdata;
438 ElfStatus result = ReadSection(".gnu_debugdata", &debugdata);
439 if (result == ElfStatus::SECTION_NOT_FOUND) {
440 return ElfStatus::NO_SYMBOL_TABLE;
441 } else if (result == ElfStatus::NO_ERROR) {
442 std::string decompressed_data;
443 if (XzDecompress(debugdata, &decompressed_data)) {
444 auto debugdata_elf =
445 ElfFile::Open(decompressed_data.data(), decompressed_data.size(), &result);
446 if (debugdata_elf) {
447 return debugdata_elf->ParseSymbols(callback);
448 }
449 }
450 }
451 return result;
452 }
453
ParseDynamicSymbols(const ParseSymbolCallback & callback)454 void ParseDynamicSymbols(const ParseSymbolCallback& callback) override {
455 auto machine = GetELFHeader(elf_).e_machine;
456 bool is_arm = (machine == llvm::ELF::EM_ARM || machine == llvm::ELF::EM_AARCH64);
457 ReadSymbolTable(elf_obj_->dynamic_symbol_begin(), elf_obj_->dynamic_symbol_end(), callback,
458 is_arm, elf_obj_->section_end());
459 }
460
ReadSection(const std::string & section_name,std::string * content)461 ElfStatus ReadSection(const std::string& section_name, std::string* content) override {
462 for (llvm::object::section_iterator it = elf_obj_->section_begin();
463 it != elf_obj_->section_end(); ++it) {
464 llvm::Expected<llvm::StringRef> name = GetSectionName(*it);
465 if (!name || name.get() != section_name) {
466 continue;
467 }
468 llvm::Expected<llvm::StringRef> data = GetSectionContents(*it);
469 if (!data) {
470 return ElfStatus::READ_FAILED;
471 }
472 *content = data.get();
473 return ElfStatus::NO_ERROR;
474 }
475 return ElfStatus::SECTION_NOT_FOUND;
476 }
477
ReadMinExecutableVaddr(uint64_t * file_offset)478 uint64_t ReadMinExecutableVaddr(uint64_t* file_offset) {
479 bool has_vaddr = false;
480 uint64_t min_addr = std::numeric_limits<uint64_t>::max();
481 auto program_headers = GetELFProgramHeaders(elf_);
482 if (program_headers) {
483 for (const auto& ph : program_headers.get()) {
484 if ((ph.p_type == llvm::ELF::PT_LOAD) && (ph.p_flags & llvm::ELF::PF_X) &&
485 (ph.p_vaddr < min_addr)) {
486 min_addr = ph.p_vaddr;
487 *file_offset = ph.p_offset;
488 has_vaddr = true;
489 }
490 }
491 }
492 if (!has_vaddr) {
493 // JIT symfiles don't have program headers.
494 min_addr = 0;
495 *file_offset = 0;
496 }
497 return min_addr;
498 }
499
VaddrToOff(uint64_t vaddr,uint64_t * file_offset)500 bool VaddrToOff(uint64_t vaddr, uint64_t* file_offset) override {
501 auto program_headers = GetELFProgramHeaders(elf_);
502 if (!program_headers) {
503 return false;
504 }
505 for (const auto& ph : program_headers.get()) {
506 if (ph.p_type == llvm::ELF::PT_LOAD && vaddr >= ph.p_vaddr &&
507 vaddr < ph.p_vaddr + ph.p_filesz) {
508 *file_offset = vaddr - ph.p_vaddr + ph.p_offset;
509 return true;
510 }
511 }
512 return false;
513 }
514
515 private:
516 BinaryWrapper wrapper_;
517 const llvm::object::ELFObjectFile<ELFT>* elf_obj_;
518 const llvm::object::ELFFile<ELFT>* elf_;
519 };
520
CreateElfFileImpl(BinaryWrapper && wrapper,ElfStatus * status)521 std::unique_ptr<ElfFile> CreateElfFileImpl(BinaryWrapper&& wrapper, ElfStatus* status) {
522 if (auto obj = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(wrapper.obj.get())) {
523 return std::unique_ptr<ElfFile>(
524 new ElfFileImpl<llvm::object::ELF32LEObjectFile>(std::move(wrapper), obj));
525 }
526 if (auto obj = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(wrapper.obj.get())) {
527 return std::unique_ptr<ElfFile>(
528 new ElfFileImpl<llvm::object::ELF64LEObjectFile>(std::move(wrapper), obj));
529 }
530 *status = ElfStatus::FILE_MALFORMED;
531 return nullptr;
532 }
533
534 } // namespace
535
Open(const std::string & filename)536 std::unique_ptr<ElfFile> ElfFile::Open(const std::string& filename) {
537 ElfStatus status;
538 auto elf = Open(filename, &status);
539 if (!elf) {
540 LOG(ERROR) << "failed to open " << filename << ": " << status;
541 }
542 return elf;
543 }
544
Open(const std::string & filename,const BuildId * expected_build_id,ElfStatus * status)545 std::unique_ptr<ElfFile> ElfFile::Open(const std::string& filename,
546 const BuildId* expected_build_id, ElfStatus* status) {
547 BinaryWrapper wrapper;
548 auto tuple = SplitUrlInApk(filename);
549 if (std::get<0>(tuple)) {
550 EmbeddedElf* elf = ApkInspector::FindElfInApkByName(std::get<1>(tuple), std::get<2>(tuple));
551 if (elf == nullptr) {
552 *status = ElfStatus::FILE_NOT_FOUND;
553 } else {
554 *status = OpenObjectFile(elf->filepath(), elf->entry_offset(), elf->entry_size(), &wrapper);
555 }
556 } else if (JITDebugReader::IsPathInJITSymFile(filename)) {
557 size_t colon_pos = filename.rfind(':');
558 CHECK_NE(colon_pos, std::string::npos);
559 // path generated by JITDebugReader: app_jit_cache:<file_start>-<file_end>
560 uint64_t file_start;
561 uint64_t file_end;
562 if (sscanf(filename.data() + colon_pos, ":%" PRIu64 "-%" PRIu64, &file_start, &file_end) != 2) {
563 *status = ElfStatus::FILE_NOT_FOUND;
564 return nullptr;
565 }
566 *status =
567 OpenObjectFile(filename.substr(0, colon_pos), file_start, file_end - file_start, &wrapper);
568 } else {
569 *status = OpenObjectFile(filename, 0, 0, &wrapper);
570 }
571 if (*status != ElfStatus::NO_ERROR) {
572 return nullptr;
573 }
574 auto elf = CreateElfFileImpl(std::move(wrapper), status);
575 if (elf && expected_build_id != nullptr && !expected_build_id->IsEmpty()) {
576 BuildId real_build_id;
577 *status = elf->GetBuildId(&real_build_id);
578 if (*status != ElfStatus::NO_ERROR) {
579 return nullptr;
580 }
581 if (*expected_build_id != real_build_id) {
582 *status = ElfStatus::BUILD_ID_MISMATCH;
583 return nullptr;
584 }
585 }
586 return elf;
587 }
588
Open(const char * data,size_t size,ElfStatus * status)589 std::unique_ptr<ElfFile> ElfFile::Open(const char* data, size_t size, ElfStatus* status) {
590 BinaryWrapper wrapper;
591 *status = OpenObjectFileInMemory(data, size, &wrapper);
592 if (*status != ElfStatus::NO_ERROR) {
593 return nullptr;
594 }
595 return CreateElfFileImpl(std::move(wrapper), status);
596 }
597
598 } // namespace simpleperf
599
600 // LLVM libraries uses ncurses library, but that isn't needed by simpleperf.
601 // So support a naive implementation to avoid depending on ncurses.
setupterm(char *,int,int *)602 __attribute__((weak)) extern "C" int setupterm(char*, int, int*) {
603 return -1;
604 }
605
set_curterm(struct term *)606 __attribute__((weak)) extern "C" struct term* set_curterm(struct term*) {
607 return nullptr;
608 }
609
del_curterm(struct term *)610 __attribute__((weak)) extern "C" int del_curterm(struct term*) {
611 return -1;
612 }
613
tigetnum(char *)614 __attribute__((weak)) extern "C" int tigetnum(char*) {
615 return -1;
616 }
617