2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <sys/types.h>
23 #include "arch/instruction_set.h"
24 #include "base/logging.h"
25 #include "base/stringprintf.h"
26 #include "base/stl_util.h"
27 #include "base/unix_file/fd_file.h"
28 #include "elf_file_impl.h"
29 #include "elf_utils.h"
35 template <typename ElfTypes>
36 ElfFileImpl<ElfTypes>::ElfFileImpl(File* file, bool writable,
37 bool program_header_only,
38 uint8_t* requested_base)
39 : writable_(writable),
40 program_header_only_(program_header_only),
42 base_address_(nullptr),
43 program_headers_start_(nullptr),
44 section_headers_start_(nullptr),
45 dynamic_program_header_(nullptr),
46 dynamic_section_start_(nullptr),
47 symtab_section_start_(nullptr),
48 dynsym_section_start_(nullptr),
49 strtab_section_start_(nullptr),
50 dynstr_section_start_(nullptr),
51 hash_section_start_(nullptr),
52 symtab_symbol_table_(nullptr),
53 dynsym_symbol_table_(nullptr),
54 requested_base_(requested_base) {
55 CHECK(file != nullptr);
58 template <typename ElfTypes>
59 ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(File* file,
61 bool program_header_only,
63 std::string* error_msg,
64 uint8_t* requested_base) {
65 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
66 (file, writable, program_header_only, requested_base));
70 prot = PROT_READ | PROT_WRITE;
76 if (!elf_file->Setup(file, prot, flags, low_4gb, error_msg)) {
79 return elf_file.release();
82 template <typename ElfTypes>
83 ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(File* file,
87 std::string* error_msg) {
88 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
89 (file, (prot & PROT_WRITE) == PROT_WRITE, /*program_header_only*/false,
90 /*requested_base*/nullptr));
91 if (!elf_file->Setup(file, prot, flags, low_4gb, error_msg)) {
94 return elf_file.release();
97 template <typename ElfTypes>
98 bool ElfFileImpl<ElfTypes>::Setup(File* file,
102 std::string* error_msg) {
103 int64_t temp_file_length = file->GetLength();
104 if (temp_file_length < 0) {
105 errno = -temp_file_length;
106 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
107 file->GetPath().c_str(), file->Fd(), strerror(errno));
110 size_t file_length = static_cast<size_t>(temp_file_length);
111 if (file_length < sizeof(Elf_Ehdr)) {
112 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
113 "%zd bytes: '%s'", file_length, sizeof(Elf_Ehdr),
114 file->GetPath().c_str());
118 if (program_header_only_) {
119 // first just map ELF header to get program header size information
120 size_t elf_header_size = sizeof(Elf_Ehdr);
122 MemMap::MapFile(elf_header_size,
128 file->GetPath().c_str(),
133 // then remap to cover program header
134 size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
135 if (file_length < program_header_size) {
136 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
137 "header of %zd bytes: '%s'", file_length,
138 sizeof(Elf_Ehdr), file->GetPath().c_str());
142 MemMap::MapFile(program_header_size,
148 file->GetPath().c_str(),
151 *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
155 // otherwise map entire file
157 MemMap::MapFile(file->GetLength(),
163 file->GetPath().c_str(),
166 *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
171 if (program_header_only_) {
172 program_headers_start_ = Begin() + GetHeader().e_phoff;
174 if (!CheckAndSet(GetHeader().e_phoff, "program headers", &program_headers_start_, error_msg)) {
178 // Setup section headers.
179 if (!CheckAndSet(GetHeader().e_shoff, "section headers", §ion_headers_start_, error_msg)) {
184 Elf_Shdr* shstrtab_section_header = GetSectionNameStringSection();
185 if (shstrtab_section_header == nullptr) {
186 *error_msg = StringPrintf("Failed to find shstrtab section header in ELF file: '%s'",
187 file->GetPath().c_str());
191 // Find .dynamic section info from program header
192 dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
193 if (dynamic_program_header_ == nullptr) {
194 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
195 file->GetPath().c_str());
199 if (!CheckAndSet(GetDynamicProgramHeader().p_offset, "dynamic section",
200 reinterpret_cast<uint8_t**>(&dynamic_section_start_), error_msg)) {
204 // Find other sections from section headers
205 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
206 Elf_Shdr* section_header = GetSectionHeader(i);
207 if (section_header == nullptr) {
208 *error_msg = StringPrintf("Failed to find section header for section %d in ELF file: '%s'",
209 i, file->GetPath().c_str());
212 switch (section_header->sh_type) {
214 if (!CheckAndSet(section_header->sh_offset, "symtab",
215 reinterpret_cast<uint8_t**>(&symtab_section_start_), error_msg)) {
221 if (!CheckAndSet(section_header->sh_offset, "dynsym",
222 reinterpret_cast<uint8_t**>(&dynsym_section_start_), error_msg)) {
228 // TODO: base these off of sh_link from .symtab and .dynsym above
229 if ((section_header->sh_flags & SHF_ALLOC) != 0) {
230 // Check that this is named ".dynstr" and ignore otherwise.
231 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
232 if (strncmp(".dynstr", header_name, 8) == 0) {
233 if (!CheckAndSet(section_header->sh_offset, "dynstr",
234 reinterpret_cast<uint8_t**>(&dynstr_section_start_), error_msg)) {
239 // Check that this is named ".strtab" and ignore otherwise.
240 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
241 if (strncmp(".strtab", header_name, 8) == 0) {
242 if (!CheckAndSet(section_header->sh_offset, "strtab",
243 reinterpret_cast<uint8_t**>(&strtab_section_start_), error_msg)) {
251 if (reinterpret_cast<uint8_t*>(dynamic_section_start_) !=
252 Begin() + section_header->sh_offset) {
253 LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
254 << file->GetPath() << ": " << std::hex
255 << reinterpret_cast<void*>(dynamic_section_start_)
256 << " != " << reinterpret_cast<void*>(Begin() + section_header->sh_offset);
262 if (!CheckAndSet(section_header->sh_offset, "hash section",
263 reinterpret_cast<uint8_t**>(&hash_section_start_), error_msg)) {
271 // Check for the existence of some sections.
272 if (!CheckSectionsExist(file, error_msg)) {
280 template <typename ElfTypes>
281 ElfFileImpl<ElfTypes>::~ElfFileImpl() {
282 STLDeleteElements(&segments_);
283 delete symtab_symbol_table_;
284 delete dynsym_symbol_table_;
287 template <typename ElfTypes>
288 bool ElfFileImpl<ElfTypes>::CheckAndSet(Elf32_Off offset, const char* label,
289 uint8_t** target, std::string* error_msg) {
290 if (Begin() + offset >= End()) {
291 *error_msg = StringPrintf("Offset %d is out of range for %s in ELF file: '%s'", offset, label,
295 *target = Begin() + offset;
299 template <typename ElfTypes>
300 bool ElfFileImpl<ElfTypes>::CheckSectionsLinked(const uint8_t* source,
301 const uint8_t* target) const {
302 // Only works in whole-program mode, as we need to iterate over the sections.
303 // Note that we normally can't search by type, as duplicates are allowed for most section types.
304 if (program_header_only_) {
308 Elf_Shdr* source_section = nullptr;
309 Elf_Word target_index = 0;
310 bool target_found = false;
311 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
312 Elf_Shdr* section_header = GetSectionHeader(i);
314 if (Begin() + section_header->sh_offset == source) {
316 source_section = section_header;
320 } else if (Begin() + section_header->sh_offset == target) {
323 if (source_section != nullptr) {
329 return target_found && source_section != nullptr && source_section->sh_link == target_index;
332 template <typename ElfTypes>
333 bool ElfFileImpl<ElfTypes>::CheckSectionsExist(File* file, std::string* error_msg) const {
334 if (!program_header_only_) {
335 // If in full mode, need section headers.
336 if (section_headers_start_ == nullptr) {
337 *error_msg = StringPrintf("No section headers in ELF file: '%s'", file->GetPath().c_str());
342 // This is redundant, but defensive.
343 if (dynamic_program_header_ == nullptr) {
344 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
345 file->GetPath().c_str());
349 // Need a dynamic section. This is redundant, but defensive.
350 if (dynamic_section_start_ == nullptr) {
351 *error_msg = StringPrintf("Failed to find dynamic section in ELF file: '%s'",
352 file->GetPath().c_str());
356 // Symtab validation. These is not really a hard failure, as we are currently not using the
357 // symtab internally, but it's nice to be defensive.
358 if (symtab_section_start_ != nullptr) {
359 // When there's a symtab, there should be a strtab.
360 if (strtab_section_start_ == nullptr) {
361 *error_msg = StringPrintf("No strtab for symtab in ELF file: '%s'", file->GetPath().c_str());
365 // The symtab should link to the strtab.
366 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(symtab_section_start_),
367 reinterpret_cast<const uint8_t*>(strtab_section_start_))) {
368 *error_msg = StringPrintf("Symtab is not linked to the strtab in ELF file: '%s'",
369 file->GetPath().c_str());
374 // We always need a dynstr & dynsym.
375 if (dynstr_section_start_ == nullptr) {
376 *error_msg = StringPrintf("No dynstr in ELF file: '%s'", file->GetPath().c_str());
379 if (dynsym_section_start_ == nullptr) {
380 *error_msg = StringPrintf("No dynsym in ELF file: '%s'", file->GetPath().c_str());
384 // Need a hash section for dynamic symbol lookup.
385 if (hash_section_start_ == nullptr) {
386 *error_msg = StringPrintf("Failed to find hash section in ELF file: '%s'",
387 file->GetPath().c_str());
391 // And the hash section should be linking to the dynsym.
392 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(hash_section_start_),
393 reinterpret_cast<const uint8_t*>(dynsym_section_start_))) {
394 *error_msg = StringPrintf("Hash section is not linked to the dynstr in ELF file: '%s'",
395 file->GetPath().c_str());
399 // We'd also like to confirm a shstrtab in program_header_only_ mode (else Open() does this for
400 // us). This is usually the last in an oat file, and a good indicator of whether writing was
401 // successful (or the process crashed and left garbage).
402 if (program_header_only_) {
403 // It might not be mapped, but we can compare against the file size.
404 int64_t offset = static_cast<int64_t>(GetHeader().e_shoff +
405 (GetHeader().e_shstrndx * GetHeader().e_shentsize));
406 if (offset >= file->GetLength()) {
407 *error_msg = StringPrintf("Shstrtab is not in the mapped ELF file: '%s'",
408 file->GetPath().c_str());
416 template <typename ElfTypes>
417 bool ElfFileImpl<ElfTypes>::SetMap(File* file, MemMap* map, std::string* error_msg) {
418 if (map == nullptr) {
419 // MemMap::Open should have already set an error.
420 DCHECK(!error_msg->empty());
424 CHECK(map_.get() != nullptr) << file->GetPath();
425 CHECK(map_->Begin() != nullptr) << file->GetPath();
427 header_ = reinterpret_cast<Elf_Ehdr*>(map_->Begin());
428 if ((ELFMAG0 != header_->e_ident[EI_MAG0])
429 || (ELFMAG1 != header_->e_ident[EI_MAG1])
430 || (ELFMAG2 != header_->e_ident[EI_MAG2])
431 || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
432 *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
433 ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
434 file->GetPath().c_str(),
435 header_->e_ident[EI_MAG0],
436 header_->e_ident[EI_MAG1],
437 header_->e_ident[EI_MAG2],
438 header_->e_ident[EI_MAG3]);
441 uint8_t elf_class = (sizeof(Elf_Addr) == sizeof(Elf64_Addr)) ? ELFCLASS64 : ELFCLASS32;
442 if (elf_class != header_->e_ident[EI_CLASS]) {
443 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
445 file->GetPath().c_str(),
446 header_->e_ident[EI_CLASS]);
449 if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
450 *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
452 file->GetPath().c_str(),
453 header_->e_ident[EI_CLASS]);
456 if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
457 *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
459 file->GetPath().c_str(),
460 header_->e_ident[EI_CLASS]);
463 if (ET_DYN != header_->e_type) {
464 *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
466 file->GetPath().c_str(),
470 if (EV_CURRENT != header_->e_version) {
471 *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
473 file->GetPath().c_str(),
477 if (0 != header_->e_entry) {
478 *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
480 file->GetPath().c_str(),
481 static_cast<int32_t>(header_->e_entry));
484 if (0 == header_->e_phoff) {
485 *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
486 file->GetPath().c_str());
489 if (0 == header_->e_shoff) {
490 *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
491 file->GetPath().c_str());
494 if (0 == header_->e_ehsize) {
495 *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
496 file->GetPath().c_str());
499 if (0 == header_->e_phentsize) {
500 *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
501 file->GetPath().c_str());
504 if (0 == header_->e_phnum) {
505 *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
506 file->GetPath().c_str());
509 if (0 == header_->e_shentsize) {
510 *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
511 file->GetPath().c_str());
514 if (0 == header_->e_shnum) {
515 *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
516 file->GetPath().c_str());
519 if (0 == header_->e_shstrndx) {
520 *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
521 file->GetPath().c_str());
524 if (header_->e_shstrndx >= header_->e_shnum) {
525 *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
528 file->GetPath().c_str());
532 if (!program_header_only_) {
533 if (header_->e_phoff >= Size()) {
534 *error_msg = StringPrintf("Failed to find e_phoff value %" PRIu64 " less than %zd in %s",
535 static_cast<uint64_t>(header_->e_phoff),
537 file->GetPath().c_str());
540 if (header_->e_shoff >= Size()) {
541 *error_msg = StringPrintf("Failed to find e_shoff value %" PRIu64 " less than %zd in %s",
542 static_cast<uint64_t>(header_->e_shoff),
544 file->GetPath().c_str());
551 template <typename ElfTypes>
552 typename ElfTypes::Ehdr& ElfFileImpl<ElfTypes>::GetHeader() const {
553 CHECK(header_ != nullptr); // Header has been checked in SetMap. This is a sanity check.
557 template <typename ElfTypes>
558 uint8_t* ElfFileImpl<ElfTypes>::GetProgramHeadersStart() const {
559 CHECK(program_headers_start_ != nullptr); // Header has been set in Setup. This is a sanity
561 return program_headers_start_;
564 template <typename ElfTypes>
565 uint8_t* ElfFileImpl<ElfTypes>::GetSectionHeadersStart() const {
566 CHECK(!program_header_only_); // Only used in "full" mode.
567 CHECK(section_headers_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
568 return section_headers_start_;
571 template <typename ElfTypes>
572 typename ElfTypes::Phdr& ElfFileImpl<ElfTypes>::GetDynamicProgramHeader() const {
573 CHECK(dynamic_program_header_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
574 return *dynamic_program_header_;
577 template <typename ElfTypes>
578 typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::GetDynamicSectionStart() const {
579 CHECK(dynamic_section_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
580 return dynamic_section_start_;
583 template <typename ElfTypes>
584 typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbolSectionStart(
585 Elf_Word section_type) const {
586 CHECK(IsSymbolSectionType(section_type)) << file_path_ << " " << section_type;
587 switch (section_type) {
589 return symtab_section_start_;
593 return dynsym_section_start_;
597 LOG(FATAL) << section_type;
603 template <typename ElfTypes>
604 const char* ElfFileImpl<ElfTypes>::GetStringSectionStart(
605 Elf_Word section_type) const {
606 CHECK(IsSymbolSectionType(section_type)) << file_path_ << " " << section_type;
607 switch (section_type) {
609 return strtab_section_start_;
612 return dynstr_section_start_;
615 LOG(FATAL) << section_type;
621 template <typename ElfTypes>
622 const char* ElfFileImpl<ElfTypes>::GetString(Elf_Word section_type,
624 CHECK(IsSymbolSectionType(section_type)) << file_path_ << " " << section_type;
628 const char* string_section_start = GetStringSectionStart(section_type);
629 if (string_section_start == nullptr) {
632 return string_section_start + i;
635 // WARNING: The following methods do not check for an error condition (non-existent hash section).
636 // It is the caller's job to do this.
638 template <typename ElfTypes>
639 typename ElfTypes::Word* ElfFileImpl<ElfTypes>::GetHashSectionStart() const {
640 return hash_section_start_;
643 template <typename ElfTypes>
644 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucketNum() const {
645 return GetHashSectionStart()[0];
648 template <typename ElfTypes>
649 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChainNum() const {
650 return GetHashSectionStart()[1];
653 template <typename ElfTypes>
654 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucket(size_t i, bool* ok) const {
655 if (i >= GetHashBucketNum()) {
660 // 0 is nbucket, 1 is nchain
661 return GetHashSectionStart()[2 + i];
664 template <typename ElfTypes>
665 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChain(size_t i, bool* ok) const {
666 if (i >= GetHashChainNum()) {
671 // 0 is nbucket, 1 is nchain, & chains are after buckets
672 return GetHashSectionStart()[2 + GetHashBucketNum() + i];
675 template <typename ElfTypes>
676 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetProgramHeaderNum() const {
677 return GetHeader().e_phnum;
680 template <typename ElfTypes>
681 typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::GetProgramHeader(Elf_Word i) const {
682 CHECK_LT(i, GetProgramHeaderNum()) << file_path_; // Sanity check for caller.
683 uint8_t* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
684 if (program_header >= End()) {
685 return nullptr; // Failure condition.
687 return reinterpret_cast<Elf_Phdr*>(program_header);
690 template <typename ElfTypes>
691 typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::FindProgamHeaderByType(Elf_Word type) const {
692 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
693 Elf_Phdr* program_header = GetProgramHeader(i);
694 if (program_header->p_type == type) {
695 return program_header;
701 template <typename ElfTypes>
702 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSectionHeaderNum() const {
703 return GetHeader().e_shnum;
706 template <typename ElfTypes>
707 typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionHeader(Elf_Word i) const {
708 // Can only access arbitrary sections when we have the whole file, not just program header.
709 // Even if we Load(), it doesn't bring in all the sections.
710 CHECK(!program_header_only_) << file_path_;
711 if (i >= GetSectionHeaderNum()) {
712 return nullptr; // Failure condition.
714 uint8_t* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
715 if (section_header >= End()) {
716 return nullptr; // Failure condition.
718 return reinterpret_cast<Elf_Shdr*>(section_header);
721 template <typename ElfTypes>
722 typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByType(Elf_Word type) const {
723 // Can only access arbitrary sections when we have the whole file, not just program header.
724 // We could change this to switch on known types if they were detected during loading.
725 CHECK(!program_header_only_) << file_path_;
726 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
727 Elf_Shdr* section_header = GetSectionHeader(i);
728 if (section_header->sh_type == type) {
729 return section_header;
736 static unsigned elfhash(const char *_name) {
737 const unsigned char *name = (const unsigned char *) _name;
741 h = (h << 4) + *name++;
749 template <typename ElfTypes>
750 typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionNameStringSection() const {
751 return GetSectionHeader(GetHeader().e_shstrndx);
754 template <typename ElfTypes>
755 const uint8_t* ElfFileImpl<ElfTypes>::FindDynamicSymbolAddress(
756 const std::string& symbol_name) const {
757 // Check that we have a hash section.
758 if (GetHashSectionStart() == nullptr) {
759 return nullptr; // Failure condition.
761 const Elf_Sym* sym = FindDynamicSymbol(symbol_name);
762 if (sym != nullptr) {
763 // TODO: we need to change this to calculate base_address_ in ::Open,
764 // otherwise it will be wrongly 0 if ::Load has not yet been called.
765 return base_address_ + sym->st_value;
771 // WARNING: Only called from FindDynamicSymbolAddress. Elides check for hash section.
772 template <typename ElfTypes>
773 const typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindDynamicSymbol(
774 const std::string& symbol_name) const {
775 if (GetHashBucketNum() == 0) {
776 // No dynamic symbols at all.
779 Elf_Word hash = elfhash(symbol_name.c_str());
780 Elf_Word bucket_index = hash % GetHashBucketNum();
782 Elf_Word symbol_and_chain_index = GetHashBucket(bucket_index, &ok);
786 while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
787 Elf_Sym* symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
788 if (symbol == nullptr) {
789 return nullptr; // Failure condition.
791 const char* name = GetString(SHT_DYNSYM, symbol->st_name);
792 if (symbol_name == name) {
795 symbol_and_chain_index = GetHashChain(symbol_and_chain_index, &ok);
803 template <typename ElfTypes>
804 bool ElfFileImpl<ElfTypes>::IsSymbolSectionType(Elf_Word section_type) {
805 return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
808 template <typename ElfTypes>
809 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSymbolNum(Elf_Shdr& section_header) const {
810 CHECK(IsSymbolSectionType(section_header.sh_type))
811 << file_path_ << " " << section_header.sh_type;
812 CHECK_NE(0U, section_header.sh_entsize) << file_path_;
813 return section_header.sh_size / section_header.sh_entsize;
816 template <typename ElfTypes>
817 typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbol(Elf_Word section_type, Elf_Word i) const {
818 Elf_Sym* sym_start = GetSymbolSectionStart(section_type);
819 if (sym_start == nullptr) {
822 return sym_start + i;
825 template <typename ElfTypes>
826 typename ElfFileImpl<ElfTypes>::SymbolTable**
827 ElfFileImpl<ElfTypes>::GetSymbolTable(Elf_Word section_type) {
828 CHECK(IsSymbolSectionType(section_type)) << file_path_ << " " << section_type;
829 switch (section_type) {
831 return &symtab_symbol_table_;
834 return &dynsym_symbol_table_;
837 LOG(FATAL) << section_type;
843 template <typename ElfTypes>
844 typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindSymbolByName(
845 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
846 CHECK(!program_header_only_) << file_path_;
847 CHECK(IsSymbolSectionType(section_type)) << file_path_ << " " << section_type;
849 SymbolTable** symbol_table = GetSymbolTable(section_type);
850 if (*symbol_table != nullptr || build_map) {
851 if (*symbol_table == nullptr) {
853 *symbol_table = new SymbolTable;
854 Elf_Shdr* symbol_section = FindSectionByType(section_type);
855 if (symbol_section == nullptr) {
856 return nullptr; // Failure condition.
858 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
859 if (string_section == nullptr) {
860 return nullptr; // Failure condition.
862 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
863 Elf_Sym* symbol = GetSymbol(section_type, i);
864 if (symbol == nullptr) {
865 return nullptr; // Failure condition.
867 unsigned char type = (sizeof(Elf_Addr) == sizeof(Elf64_Addr))
868 ? ELF64_ST_TYPE(symbol->st_info)
869 : ELF32_ST_TYPE(symbol->st_info);
870 if (type == STT_NOTYPE) {
873 const char* name = GetString(*string_section, symbol->st_name);
874 if (name == nullptr) {
877 std::pair<typename SymbolTable::iterator, bool> result =
878 (*symbol_table)->insert(std::make_pair(name, symbol));
879 if (!result.second) {
880 // If a duplicate, make sure it has the same logical value. Seen on x86.
881 if ((symbol->st_value != result.first->second->st_value) ||
882 (symbol->st_size != result.first->second->st_size) ||
883 (symbol->st_info != result.first->second->st_info) ||
884 (symbol->st_other != result.first->second->st_other) ||
885 (symbol->st_shndx != result.first->second->st_shndx)) {
886 return nullptr; // Failure condition.
891 CHECK(*symbol_table != nullptr);
892 typename SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
893 if (it == (*symbol_table)->end()) {
899 // Fall back to linear search
900 Elf_Shdr* symbol_section = FindSectionByType(section_type);
901 if (symbol_section == nullptr) {
904 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
905 if (string_section == nullptr) {
908 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
909 Elf_Sym* symbol = GetSymbol(section_type, i);
910 if (symbol == nullptr) {
911 return nullptr; // Failure condition.
913 const char* name = GetString(*string_section, symbol->st_name);
914 if (name == nullptr) {
917 if (symbol_name == name) {
924 template <typename ElfTypes>
925 typename ElfTypes::Addr ElfFileImpl<ElfTypes>::FindSymbolAddress(
926 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
927 Elf_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
928 if (symbol == nullptr) {
931 return symbol->st_value;
934 template <typename ElfTypes>
935 const char* ElfFileImpl<ElfTypes>::GetString(Elf_Shdr& string_section,
937 CHECK(!program_header_only_) << file_path_;
938 // TODO: remove this static_cast from enum when using -std=gnu++0x
939 if (static_cast<Elf_Word>(SHT_STRTAB) != string_section.sh_type) {
940 return nullptr; // Failure condition.
942 if (i >= string_section.sh_size) {
948 uint8_t* strings = Begin() + string_section.sh_offset;
949 uint8_t* string = strings + i;
950 if (string >= End()) {
953 return reinterpret_cast<const char*>(string);
956 template <typename ElfTypes>
957 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetDynamicNum() const {
958 return GetDynamicProgramHeader().p_filesz / sizeof(Elf_Dyn);
961 template <typename ElfTypes>
962 typename ElfTypes::Dyn& ElfFileImpl<ElfTypes>::GetDynamic(Elf_Word i) const {
963 CHECK_LT(i, GetDynamicNum()) << file_path_;
964 return *(GetDynamicSectionStart() + i);
967 template <typename ElfTypes>
968 typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::FindDynamicByType(Elf_Sword type) const {
969 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
970 Elf_Dyn* dyn = &GetDynamic(i);
971 if (dyn->d_tag == type) {
978 template <typename ElfTypes>
979 typename ElfTypes::Word ElfFileImpl<ElfTypes>::FindDynamicValueByType(Elf_Sword type) const {
980 Elf_Dyn* dyn = FindDynamicByType(type);
981 if (dyn == nullptr) {
984 return dyn->d_un.d_val;
988 template <typename ElfTypes>
989 typename ElfTypes::Rel* ElfFileImpl<ElfTypes>::GetRelSectionStart(Elf_Shdr& section_header) const {
990 CHECK(SHT_REL == section_header.sh_type) << file_path_ << " " << section_header.sh_type;
991 return reinterpret_cast<Elf_Rel*>(Begin() + section_header.sh_offset);
994 template <typename ElfTypes>
995 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelNum(Elf_Shdr& section_header) const {
996 CHECK(SHT_REL == section_header.sh_type) << file_path_ << " " << section_header.sh_type;
997 CHECK_NE(0U, section_header.sh_entsize) << file_path_;
998 return section_header.sh_size / section_header.sh_entsize;
1001 template <typename ElfTypes>
1002 typename ElfTypes::Rel& ElfFileImpl<ElfTypes>::GetRel(Elf_Shdr& section_header, Elf_Word i) const {
1003 CHECK(SHT_REL == section_header.sh_type) << file_path_ << " " << section_header.sh_type;
1004 CHECK_LT(i, GetRelNum(section_header)) << file_path_;
1005 return *(GetRelSectionStart(section_header) + i);
1008 template <typename ElfTypes>
1009 typename ElfTypes::Rela* ElfFileImpl<ElfTypes>::GetRelaSectionStart(Elf_Shdr& section_header) const {
1010 CHECK(SHT_RELA == section_header.sh_type) << file_path_ << " " << section_header.sh_type;
1011 return reinterpret_cast<Elf_Rela*>(Begin() + section_header.sh_offset);
1014 template <typename ElfTypes>
1015 typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelaNum(Elf_Shdr& section_header) const {
1016 CHECK(SHT_RELA == section_header.sh_type) << file_path_ << " " << section_header.sh_type;
1017 return section_header.sh_size / section_header.sh_entsize;
1020 template <typename ElfTypes>
1021 typename ElfTypes::Rela& ElfFileImpl<ElfTypes>::GetRela(Elf_Shdr& section_header, Elf_Word i) const {
1022 CHECK(SHT_RELA == section_header.sh_type) << file_path_ << " " << section_header.sh_type;
1023 CHECK_LT(i, GetRelaNum(section_header)) << file_path_;
1024 return *(GetRelaSectionStart(section_header) + i);
1027 // Base on bionic phdr_table_get_load_size
1028 template <typename ElfTypes>
1029 bool ElfFileImpl<ElfTypes>::GetLoadedSize(size_t* size, std::string* error_msg) const {
1030 Elf_Addr min_vaddr = static_cast<Elf_Addr>(-1);
1031 Elf_Addr max_vaddr = 0u;
1032 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1033 Elf_Phdr* program_header = GetProgramHeader(i);
1034 if (program_header->p_type != PT_LOAD) {
1037 Elf_Addr begin_vaddr = program_header->p_vaddr;
1038 if (begin_vaddr < min_vaddr) {
1039 min_vaddr = begin_vaddr;
1041 Elf_Addr end_vaddr = program_header->p_vaddr + program_header->p_memsz;
1042 if (UNLIKELY(begin_vaddr > end_vaddr)) {
1043 std::ostringstream oss;
1044 oss << "Program header #" << i << " has overflow in p_vaddr+p_memsz: 0x" << std::hex
1045 << program_header->p_vaddr << "+0x" << program_header->p_memsz << "=0x" << end_vaddr
1046 << " in ELF file \"" << file_path_ << "\"";
1047 *error_msg = oss.str();
1048 *size = static_cast<size_t>(-1);
1051 if (end_vaddr > max_vaddr) {
1052 max_vaddr = end_vaddr;
1055 min_vaddr = RoundDown(min_vaddr, kPageSize);
1056 max_vaddr = RoundUp(max_vaddr, kPageSize);
1057 CHECK_LT(min_vaddr, max_vaddr) << file_path_;
1058 Elf_Addr loaded_size = max_vaddr - min_vaddr;
1059 // Check that the loaded_size fits in size_t.
1060 if (UNLIKELY(loaded_size > std::numeric_limits<size_t>::max())) {
1061 std::ostringstream oss;
1062 oss << "Loaded size is 0x" << std::hex << loaded_size << " but maximum size_t is 0x"
1063 << std::numeric_limits<size_t>::max() << " for ELF file \"" << file_path_ << "\"";
1064 *error_msg = oss.str();
1065 *size = static_cast<size_t>(-1);
1068 *size = loaded_size;
1072 template <typename ElfTypes>
1073 bool ElfFileImpl<ElfTypes>::Load(File* file,
1076 std::string* error_msg) {
1077 CHECK(program_header_only_) << file->GetPath();
1080 InstructionSet elf_ISA = GetInstructionSetFromELF(GetHeader().e_machine, GetHeader().e_flags);
1081 if (elf_ISA != kRuntimeISA) {
1082 std::ostringstream oss;
1083 oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
1084 *error_msg = oss.str();
1089 bool reserved = false;
1090 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1091 Elf_Phdr* program_header = GetProgramHeader(i);
1092 if (program_header == nullptr) {
1093 *error_msg = StringPrintf("No program header for entry %d in ELF file %s.",
1094 i, file->GetPath().c_str());
1098 // Record .dynamic header information for later use
1099 if (program_header->p_type == PT_DYNAMIC) {
1100 dynamic_program_header_ = program_header;
1104 // Not something to load, move on.
1105 if (program_header->p_type != PT_LOAD) {
1109 // Found something to load.
1111 // Before load the actual segments, reserve a contiguous chunk
1112 // of required size and address for all segments, but with no
1113 // permissions. We'll then carve that up with the proper
1114 // permissions as we load the actual segments. If p_vaddr is
1115 // non-zero, the segments require the specific address specified,
1116 // which either was specified in the file because we already set
1117 // base_address_ after the first zero segment).
1118 int64_t temp_file_length = file->GetLength();
1119 if (temp_file_length < 0) {
1120 errno = -temp_file_length;
1121 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
1122 file->GetPath().c_str(), file->Fd(), strerror(errno));
1125 size_t file_length = static_cast<size_t>(temp_file_length);
1127 uint8_t* reserve_base = reinterpret_cast<uint8_t*>(program_header->p_vaddr);
1128 uint8_t* reserve_base_override = reserve_base;
1129 // Override the base (e.g. when compiling with --compile-pic)
1130 if (requested_base_ != nullptr) {
1131 reserve_base_override = requested_base_;
1133 std::string reservation_name("ElfFile reservation for ");
1134 reservation_name += file->GetPath();
1136 if (!GetLoadedSize(&loaded_size, error_msg)) {
1137 DCHECK(!error_msg->empty());
1140 std::unique_ptr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
1141 reserve_base_override,
1147 if (reserve.get() == nullptr) {
1148 *error_msg = StringPrintf("Failed to allocate %s: %s",
1149 reservation_name.c_str(), error_msg->c_str());
1154 // Base address is the difference of actual mapped location and the p_vaddr
1155 base_address_ = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(reserve->Begin())
1156 - reinterpret_cast<uintptr_t>(reserve_base));
1157 // By adding the p_vaddr of a section/symbol to base_address_ we will always get the
1158 // dynamic memory address of where that object is actually mapped
1160 // TODO: base_address_ needs to be calculated in ::Open, otherwise
1161 // FindDynamicSymbolAddress returns the wrong values until Load is called.
1162 segments_.push_back(reserve.release());
1164 // empty segment, nothing to map
1165 if (program_header->p_memsz == 0) {
1168 uint8_t* p_vaddr = base_address_ + program_header->p_vaddr;
1170 if (executable && ((program_header->p_flags & PF_X) != 0)) {
1173 if ((program_header->p_flags & PF_W) != 0) {
1176 if ((program_header->p_flags & PF_R) != 0) {
1182 flags |= MAP_SHARED;
1184 flags |= MAP_PRIVATE;
1186 if (program_header->p_filesz > program_header->p_memsz) {
1187 *error_msg = StringPrintf("Invalid p_filesz > p_memsz (%" PRIu64 " > %" PRIu64 "): %s",
1188 static_cast<uint64_t>(program_header->p_filesz),
1189 static_cast<uint64_t>(program_header->p_memsz),
1190 file->GetPath().c_str());
1193 if (program_header->p_filesz < program_header->p_memsz &&
1194 !IsAligned<kPageSize>(program_header->p_filesz)) {
1195 *error_msg = StringPrintf("Unsupported unaligned p_filesz < p_memsz (%" PRIu64
1196 " < %" PRIu64 "): %s",
1197 static_cast<uint64_t>(program_header->p_filesz),
1198 static_cast<uint64_t>(program_header->p_memsz),
1199 file->GetPath().c_str());
1202 if (file_length < (program_header->p_offset + program_header->p_filesz)) {
1203 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
1204 "%d of %" PRIu64 " bytes: '%s'", file_length, i,
1205 static_cast<uint64_t>(program_header->p_offset + program_header->p_filesz),
1206 file->GetPath().c_str());
1209 if (program_header->p_filesz != 0u) {
1210 std::unique_ptr<MemMap> segment(
1211 MemMap::MapFileAtAddress(p_vaddr,
1212 program_header->p_filesz,
1216 program_header->p_offset,
1218 /*reuse*/true, // implies MAP_FIXED
1219 file->GetPath().c_str(),
1221 if (segment.get() == nullptr) {
1222 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
1223 i, file->GetPath().c_str(), error_msg->c_str());
1226 if (segment->Begin() != p_vaddr) {
1227 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
1228 "instead mapped to %p",
1229 i, file->GetPath().c_str(), p_vaddr, segment->Begin());
1232 segments_.push_back(segment.release());
1234 if (program_header->p_filesz < program_header->p_memsz) {
1235 std::string name = StringPrintf("Zero-initialized segment %" PRIu64 " of ELF file %s",
1236 static_cast<uint64_t>(i), file->GetPath().c_str());
1237 std::unique_ptr<MemMap> segment(
1238 MemMap::MapAnonymous(name.c_str(),
1239 p_vaddr + program_header->p_filesz,
1240 program_header->p_memsz - program_header->p_filesz,
1241 prot, false, true /* reuse */, error_msg));
1242 if (segment == nullptr) {
1243 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s: %s",
1244 i, file->GetPath().c_str(), error_msg->c_str());
1247 if (segment->Begin() != p_vaddr) {
1248 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s "
1249 "at expected address %p, instead mapped to %p",
1250 i, file->GetPath().c_str(), p_vaddr, segment->Begin());
1253 segments_.push_back(segment.release());
1257 // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
1258 uint8_t* dsptr = base_address_ + GetDynamicProgramHeader().p_vaddr;
1259 if ((dsptr < Begin() || dsptr >= End()) && !ValidPointer(dsptr)) {
1260 *error_msg = StringPrintf("dynamic section address invalid in ELF file %s",
1261 file->GetPath().c_str());
1264 dynamic_section_start_ = reinterpret_cast<Elf_Dyn*>(dsptr);
1266 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1267 Elf_Dyn& elf_dyn = GetDynamic(i);
1268 uint8_t* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
1269 switch (elf_dyn.d_tag) {
1271 if (!ValidPointer(d_ptr)) {
1272 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1273 d_ptr, file->GetPath().c_str());
1276 hash_section_start_ = reinterpret_cast<Elf_Word*>(d_ptr);
1280 if (!ValidPointer(d_ptr)) {
1281 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1282 d_ptr, file->GetPath().c_str());
1285 dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
1289 if (!ValidPointer(d_ptr)) {
1290 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1291 d_ptr, file->GetPath().c_str());
1294 dynsym_section_start_ = reinterpret_cast<Elf_Sym*>(d_ptr);
1298 if (GetDynamicNum() != i+1) {
1299 *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
1300 "expected %d as implied by size of PT_DYNAMIC segment in %s",
1301 i + 1, GetDynamicNum(), file->GetPath().c_str());
1309 // Check for the existence of some sections.
1310 if (!CheckSectionsExist(file, error_msg)) {
1317 template <typename ElfTypes>
1318 bool ElfFileImpl<ElfTypes>::ValidPointer(const uint8_t* start) const {
1319 for (size_t i = 0; i < segments_.size(); ++i) {
1320 const MemMap* segment = segments_[i];
1321 if (segment->Begin() <= start && start < segment->End()) {
1329 template <typename ElfTypes>
1330 typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByName(
1331 const std::string& name) const {
1332 CHECK(!program_header_only_);
1333 Elf_Shdr* shstrtab_sec = GetSectionNameStringSection();
1334 if (shstrtab_sec == nullptr) {
1337 for (uint32_t i = 0; i < GetSectionHeaderNum(); i++) {
1338 Elf_Shdr* shdr = GetSectionHeader(i);
1339 if (shdr == nullptr) {
1342 const char* sec_name = GetString(*shstrtab_sec, shdr->sh_name);
1343 if (sec_name == nullptr) {
1346 if (name == sec_name) {
1353 template <typename ElfTypes>
1354 bool ElfFileImpl<ElfTypes>::FixupDebugSections(Elf_Addr base_address_delta) {
1355 if (base_address_delta == 0) {
1358 return ApplyOatPatchesTo(".debug_frame", base_address_delta) &&
1359 ApplyOatPatchesTo(".debug_info", base_address_delta) &&
1360 ApplyOatPatchesTo(".debug_line", base_address_delta);
1363 template <typename ElfTypes>
1364 bool ElfFileImpl<ElfTypes>::ApplyOatPatchesTo(
1365 const char* target_section_name, Elf_Addr delta) {
1366 auto target_section = FindSectionByName(target_section_name);
1367 if (target_section == nullptr) {
1370 std::string patches_name = target_section_name + std::string(".oat_patches");
1371 auto patches_section = FindSectionByName(patches_name.c_str());
1372 if (patches_section == nullptr) {
1373 LOG(ERROR) << patches_name << " section not found.";
1376 if (patches_section->sh_type != SHT_OAT_PATCH) {
1377 LOG(ERROR) << "Unexpected type of " << patches_name;
1381 Begin() + patches_section->sh_offset,
1382 Begin() + patches_section->sh_offset + patches_section->sh_size,
1384 Begin() + target_section->sh_offset,
1385 Begin() + target_section->sh_offset + target_section->sh_size);
1389 // Apply LEB128 encoded patches to given section.
1390 template <typename ElfTypes>
1391 void ElfFileImpl<ElfTypes>::ApplyOatPatches(
1392 const uint8_t* patches, const uint8_t* patches_end, Elf_Addr delta,
1393 uint8_t* to_patch, const uint8_t* to_patch_end) {
1394 typedef __attribute__((__aligned__(1))) Elf_Addr UnalignedAddress;
1395 while (patches < patches_end) {
1396 to_patch += DecodeUnsignedLeb128(&patches);
1397 DCHECK_LE(patches, patches_end) << "Unexpected end of patch list.";
1398 DCHECK_LT(to_patch, to_patch_end) << "Patch past the end of section.";
1399 *reinterpret_cast<UnalignedAddress*>(to_patch) += delta;
1403 template <typename ElfTypes>
1404 bool ElfFileImpl<ElfTypes>::Strip(File* file, std::string* error_msg) {
1405 // ELF files produced by MCLinker look roughly like this
1408 // | Elf_Ehdr | contains number of Elf_Shdr and offset to first
1410 // | Elf_Phdr | program headers
1415 // | section | mixture of needed and unneeded sections
1423 // | Elf_Shdr | section headers
1425 // | ... | contains offset to section start
1430 // - leave the Elf_Ehdr and Elf_Phdr values in place.
1431 // - walk the sections making a new set of Elf_Shdr section headers for what we want to keep
1432 // - move the sections are keeping up to fill in gaps of sections we want to strip
1433 // - write new Elf_Shdr section headers to end of file, updating Elf_Ehdr
1434 // - truncate rest of file
1437 std::vector<Elf_Shdr> section_headers;
1438 std::vector<Elf_Word> section_headers_original_indexes;
1439 section_headers.reserve(GetSectionHeaderNum());
1442 Elf_Shdr* string_section = GetSectionNameStringSection();
1443 CHECK(string_section != nullptr);
1444 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1445 Elf_Shdr* sh = GetSectionHeader(i);
1446 CHECK(sh != nullptr);
1447 const char* name = GetString(*string_section, sh->sh_name);
1448 if (name == nullptr) {
1450 section_headers.push_back(*sh);
1451 section_headers_original_indexes.push_back(0);
1454 if (StartsWith(name, ".debug")
1455 || (strcmp(name, ".strtab") == 0)
1456 || (strcmp(name, ".symtab") == 0)) {
1459 section_headers.push_back(*sh);
1460 section_headers_original_indexes.push_back(i);
1462 CHECK_NE(0U, section_headers.size());
1463 CHECK_EQ(section_headers.size(), section_headers_original_indexes.size());
1465 // section 0 is the null section, sections start at offset of first section
1466 CHECK(GetSectionHeader(1) != nullptr);
1467 Elf_Off offset = GetSectionHeader(1)->sh_offset;
1468 for (size_t i = 1; i < section_headers.size(); i++) {
1469 Elf_Shdr& new_sh = section_headers[i];
1470 Elf_Shdr* old_sh = GetSectionHeader(section_headers_original_indexes[i]);
1471 CHECK(old_sh != nullptr);
1472 CHECK_EQ(new_sh.sh_name, old_sh->sh_name);
1473 if (old_sh->sh_addralign > 1) {
1474 offset = RoundUp(offset, old_sh->sh_addralign);
1476 if (old_sh->sh_offset == offset) {
1478 offset += old_sh->sh_size;
1481 // shift section earlier
1482 memmove(Begin() + offset,
1483 Begin() + old_sh->sh_offset,
1485 new_sh.sh_offset = offset;
1486 offset += old_sh->sh_size;
1489 Elf_Off shoff = offset;
1490 size_t section_headers_size_in_bytes = section_headers.size() * sizeof(Elf_Shdr);
1491 memcpy(Begin() + offset, §ion_headers[0], section_headers_size_in_bytes);
1492 offset += section_headers_size_in_bytes;
1494 GetHeader().e_shnum = section_headers.size();
1495 GetHeader().e_shoff = shoff;
1496 int result = ftruncate(file->Fd(), offset);
1498 *error_msg = StringPrintf("Failed to truncate while stripping ELF file: '%s': %s",
1499 file->GetPath().c_str(), strerror(errno));
1505 static const bool DEBUG_FIXUP = false;
1507 template <typename ElfTypes>
1508 bool ElfFileImpl<ElfTypes>::Fixup(Elf_Addr base_address) {
1509 if (!FixupDynamic(base_address)) {
1510 LOG(WARNING) << "Failed to fixup .dynamic in " << file_path_;
1513 if (!FixupSectionHeaders(base_address)) {
1514 LOG(WARNING) << "Failed to fixup section headers in " << file_path_;
1517 if (!FixupProgramHeaders(base_address)) {
1518 LOG(WARNING) << "Failed to fixup program headers in " << file_path_;
1521 if (!FixupSymbols(base_address, true)) {
1522 LOG(WARNING) << "Failed to fixup .dynsym in " << file_path_;
1525 if (!FixupSymbols(base_address, false)) {
1526 LOG(WARNING) << "Failed to fixup .symtab in " << file_path_;
1529 if (!FixupRelocations(base_address)) {
1530 LOG(WARNING) << "Failed to fixup .rel.dyn in " << file_path_;
1533 static_assert(sizeof(Elf_Off) >= sizeof(base_address), "Potentially losing precision.");
1534 if (!FixupDebugSections(static_cast<Elf_Off>(base_address))) {
1535 LOG(WARNING) << "Failed to fixup debug sections in " << file_path_;
1541 template <typename ElfTypes>
1542 bool ElfFileImpl<ElfTypes>::FixupDynamic(Elf_Addr base_address) {
1543 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1544 Elf_Dyn& elf_dyn = GetDynamic(i);
1545 Elf_Word d_tag = elf_dyn.d_tag;
1546 if (IsDynamicSectionPointer(d_tag, GetHeader().e_machine)) {
1547 Elf_Addr d_ptr = elf_dyn.d_un.d_ptr;
1549 LOG(INFO) << StringPrintf("In %s moving Elf_Dyn[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1550 file_path_.c_str(), i,
1551 static_cast<uint64_t>(d_ptr),
1552 static_cast<uint64_t>(d_ptr + base_address));
1554 d_ptr += base_address;
1555 elf_dyn.d_un.d_ptr = d_ptr;
1561 template <typename ElfTypes>
1562 bool ElfFileImpl<ElfTypes>::FixupSectionHeaders(Elf_Addr base_address) {
1563 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1564 Elf_Shdr* sh = GetSectionHeader(i);
1565 CHECK(sh != nullptr);
1566 // 0 implies that the section will not exist in the memory of the process
1567 if (sh->sh_addr == 0) {
1571 LOG(INFO) << StringPrintf("In %s moving Elf_Shdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1572 file_path_.c_str(), i,
1573 static_cast<uint64_t>(sh->sh_addr),
1574 static_cast<uint64_t>(sh->sh_addr + base_address));
1576 sh->sh_addr += base_address;
1581 template <typename ElfTypes>
1582 bool ElfFileImpl<ElfTypes>::FixupProgramHeaders(Elf_Addr base_address) {
1583 // TODO: ELFObjectFile doesn't have give to Elf_Phdr, so we do that ourselves for now.
1584 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1585 Elf_Phdr* ph = GetProgramHeader(i);
1586 CHECK(ph != nullptr);
1587 CHECK_EQ(ph->p_vaddr, ph->p_paddr) << file_path_ << " i=" << i;
1588 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1589 << file_path_ << " i=" << i;
1591 LOG(INFO) << StringPrintf("In %s moving Elf_Phdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1592 file_path_.c_str(), i,
1593 static_cast<uint64_t>(ph->p_vaddr),
1594 static_cast<uint64_t>(ph->p_vaddr + base_address));
1596 ph->p_vaddr += base_address;
1597 ph->p_paddr += base_address;
1598 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1599 << file_path_ << " i=" << i;
1604 template <typename ElfTypes>
1605 bool ElfFileImpl<ElfTypes>::FixupSymbols(Elf_Addr base_address, bool dynamic) {
1606 Elf_Word section_type = dynamic ? SHT_DYNSYM : SHT_SYMTAB;
1607 // TODO: Unfortunate ELFObjectFile has protected symbol access, so use ElfFile
1608 Elf_Shdr* symbol_section = FindSectionByType(section_type);
1609 if (symbol_section == nullptr) {
1610 // file is missing optional .symtab
1611 CHECK(!dynamic) << file_path_;
1614 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
1615 Elf_Sym* symbol = GetSymbol(section_type, i);
1616 CHECK(symbol != nullptr);
1617 if (symbol->st_value != 0) {
1619 LOG(INFO) << StringPrintf("In %s moving Elf_Sym[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1620 file_path_.c_str(), i,
1621 static_cast<uint64_t>(symbol->st_value),
1622 static_cast<uint64_t>(symbol->st_value + base_address));
1624 symbol->st_value += base_address;
1630 template <typename ElfTypes>
1631 bool ElfFileImpl<ElfTypes>::FixupRelocations(Elf_Addr base_address) {
1632 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1633 Elf_Shdr* sh = GetSectionHeader(i);
1634 CHECK(sh != nullptr);
1635 if (sh->sh_type == SHT_REL) {
1636 for (uint32_t j = 0; j < GetRelNum(*sh); j++) {
1637 Elf_Rel& rel = GetRel(*sh, j);
1639 LOG(INFO) << StringPrintf("In %s moving Elf_Rel[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1640 file_path_.c_str(), j,
1641 static_cast<uint64_t>(rel.r_offset),
1642 static_cast<uint64_t>(rel.r_offset + base_address));
1644 rel.r_offset += base_address;
1646 } else if (sh->sh_type == SHT_RELA) {
1647 for (uint32_t j = 0; j < GetRelaNum(*sh); j++) {
1648 Elf_Rela& rela = GetRela(*sh, j);
1650 LOG(INFO) << StringPrintf("In %s moving Elf_Rela[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1651 file_path_.c_str(), j,
1652 static_cast<uint64_t>(rela.r_offset),
1653 static_cast<uint64_t>(rela.r_offset + base_address));
1655 rela.r_offset += base_address;
1662 // Explicit instantiations
1663 template class ElfFileImpl<ElfTypes32>;
1664 template class ElfFileImpl<ElfTypes64>;
1666 ElfFile::ElfFile(ElfFileImpl32* elf32) : elf32_(elf32), elf64_(nullptr) {
1669 ElfFile::ElfFile(ElfFileImpl64* elf64) : elf32_(nullptr), elf64_(elf64) {
1672 ElfFile::~ElfFile() {
1673 // Should never have 32 and 64-bit impls.
1674 CHECK_NE(elf32_.get() == nullptr, elf64_.get() == nullptr);
1677 ElfFile* ElfFile::Open(File* file,
1679 bool program_header_only,
1681 std::string* error_msg,
1682 uint8_t* requested_base) {
1683 if (file->GetLength() < EI_NIDENT) {
1684 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1685 file->GetPath().c_str());
1688 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT,
1694 file->GetPath().c_str(),
1696 if (map == nullptr && map->Size() != EI_NIDENT) {
1699 uint8_t* header = map->Begin();
1700 if (header[EI_CLASS] == ELFCLASS64) {
1701 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file,
1703 program_header_only,
1707 if (elf_file_impl == nullptr)
1709 return new ElfFile(elf_file_impl);
1710 } else if (header[EI_CLASS] == ELFCLASS32) {
1711 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file,
1713 program_header_only,
1717 if (elf_file_impl == nullptr) {
1720 return new ElfFile(elf_file_impl);
1722 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1723 ELFCLASS32, ELFCLASS64,
1724 file->GetPath().c_str(),
1730 ElfFile* ElfFile::Open(File* file, int mmap_prot, int mmap_flags, std::string* error_msg) {
1731 // low_4gb support not required for this path.
1732 constexpr bool low_4gb = false;
1733 if (file->GetLength() < EI_NIDENT) {
1734 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1735 file->GetPath().c_str());
1738 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT,
1744 file->GetPath().c_str(),
1746 if (map == nullptr && map->Size() != EI_NIDENT) {
1749 uint8_t* header = map->Begin();
1750 if (header[EI_CLASS] == ELFCLASS64) {
1751 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file,
1756 if (elf_file_impl == nullptr) {
1759 return new ElfFile(elf_file_impl);
1760 } else if (header[EI_CLASS] == ELFCLASS32) {
1761 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file,
1766 if (elf_file_impl == nullptr) {
1769 return new ElfFile(elf_file_impl);
1771 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1772 ELFCLASS32, ELFCLASS64,
1773 file->GetPath().c_str(),
1779 #define DELEGATE_TO_IMPL(func, ...) \
1780 if (elf64_.get() != nullptr) { \
1781 return elf64_->func(__VA_ARGS__); \
1783 DCHECK(elf32_.get() != nullptr); \
1784 return elf32_->func(__VA_ARGS__); \
1787 bool ElfFile::Load(File* file, bool executable, bool low_4gb, std::string* error_msg) {
1788 DELEGATE_TO_IMPL(Load, file, executable, low_4gb, error_msg);
1791 const uint8_t* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
1792 DELEGATE_TO_IMPL(FindDynamicSymbolAddress, symbol_name);
1795 size_t ElfFile::Size() const {
1796 DELEGATE_TO_IMPL(Size);
1799 uint8_t* ElfFile::Begin() const {
1800 DELEGATE_TO_IMPL(Begin);
1803 uint8_t* ElfFile::End() const {
1804 DELEGATE_TO_IMPL(End);
1807 const std::string& ElfFile::GetFilePath() const {
1808 DELEGATE_TO_IMPL(GetFilePath);
1811 bool ElfFile::GetSectionOffsetAndSize(const char* section_name, uint64_t* offset,
1812 uint64_t* size) const {
1813 if (elf32_.get() == nullptr) {
1814 CHECK(elf64_.get() != nullptr);
1816 Elf64_Shdr *shdr = elf64_->FindSectionByName(section_name);
1817 if (shdr == nullptr) {
1820 if (offset != nullptr) {
1821 *offset = shdr->sh_offset;
1823 if (size != nullptr) {
1824 *size = shdr->sh_size;
1828 Elf32_Shdr *shdr = elf32_->FindSectionByName(section_name);
1829 if (shdr == nullptr) {
1832 if (offset != nullptr) {
1833 *offset = shdr->sh_offset;
1835 if (size != nullptr) {
1836 *size = shdr->sh_size;
1842 bool ElfFile::HasSection(const std::string& name) const {
1843 if (elf64_.get() != nullptr) {
1844 return elf64_->FindSectionByName(name) != nullptr;
1846 return elf32_->FindSectionByName(name) != nullptr;
1850 uint64_t ElfFile::FindSymbolAddress(unsigned section_type,
1851 const std::string& symbol_name,
1853 DELEGATE_TO_IMPL(FindSymbolAddress, section_type, symbol_name, build_map);
1856 bool ElfFile::GetLoadedSize(size_t* size, std::string* error_msg) const {
1857 DELEGATE_TO_IMPL(GetLoadedSize, size, error_msg);
1860 bool ElfFile::Strip(File* file, std::string* error_msg) {
1861 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file, true, false, /*low_4gb*/false, error_msg));
1862 if (elf_file.get() == nullptr) {
1866 if (elf_file->elf64_.get() != nullptr) {
1867 return elf_file->elf64_->Strip(file, error_msg);
1869 return elf_file->elf32_->Strip(file, error_msg);
1873 bool ElfFile::Fixup(uint64_t base_address) {
1874 if (elf64_.get() != nullptr) {
1875 return elf64_->Fixup(static_cast<Elf64_Addr>(base_address));
1877 DCHECK(elf32_.get() != nullptr);
1878 CHECK(IsUint<32>(base_address)) << std::hex << base_address;
1879 return elf32_->Fixup(static_cast<Elf32_Addr>(base_address));
1881 DELEGATE_TO_IMPL(Fixup, base_address);