blob: e909e64e7af2786b986bd2f2aa2a46569df18319 [file] [log] [blame]
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001/*
2 * Copyright (C) 2012 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_file.h"
18
Tong Shen62d1ca32014-09-03 17:24:56 -070019#include <inttypes.h>
Nicolas Geoffraya7f198c2014-03-10 11:12:54 +000020#include <sys/types.h>
21#include <unistd.h>
22
Ian Rogersd582fa42014-11-05 23:46:43 -080023#include "arch/instruction_set.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080024#include "base/logging.h"
Ian Rogers576ca0c2014-06-06 15:58:22 -070025#include "base/stringprintf.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080026#include "base/stl_util.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070027#include "base/unix_file/fd_file.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070028#include "elf_file_impl.h"
29#include "elf_utils.h"
Alex Light3470ab42014-06-18 10:35:45 -070030#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080031#include "utils.h"
32
33namespace art {
34
Mark Mendellae9fd932014-02-10 16:14:35 -080035// -------------------------------------------------------------------
36// Binary GDB JIT Interface as described in
37// http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
38extern "C" {
39 typedef enum {
40 JIT_NOACTION = 0,
41 JIT_REGISTER_FN,
42 JIT_UNREGISTER_FN
43 } JITAction;
44
45 struct JITCodeEntry {
46 JITCodeEntry* next_;
47 JITCodeEntry* prev_;
Ian Rogers13735952014-10-08 12:43:28 -070048 const uint8_t *symfile_addr_;
Mark Mendellae9fd932014-02-10 16:14:35 -080049 uint64_t symfile_size_;
50 };
51
52 struct JITDescriptor {
53 uint32_t version_;
54 uint32_t action_flag_;
55 JITCodeEntry* relevant_entry_;
56 JITCodeEntry* first_entry_;
57 };
58
59 // GDB will place breakpoint into this function.
60 // To prevent GCC from inlining or removing it we place noinline attribute
61 // and inline assembler statement inside.
Andreas Gampe277ccbd2014-11-03 21:36:10 -080062 void __attribute__((noinline)) __jit_debug_register_code();
Mark Mendellae9fd932014-02-10 16:14:35 -080063 void __attribute__((noinline)) __jit_debug_register_code() {
64 __asm__("");
65 }
66
67 // GDB will inspect contents of this descriptor.
68 // Static initialization is necessary to prevent GDB from seeing
69 // uninitialized descriptor.
70 JITDescriptor __jit_debug_descriptor = { 1, JIT_NOACTION, nullptr, nullptr };
71}
72
73
Ian Rogers13735952014-10-08 12:43:28 -070074static JITCodeEntry* CreateCodeEntry(const uint8_t *symfile_addr,
Mark Mendellae9fd932014-02-10 16:14:35 -080075 uintptr_t symfile_size) {
76 JITCodeEntry* entry = new JITCodeEntry;
77 entry->symfile_addr_ = symfile_addr;
78 entry->symfile_size_ = symfile_size;
79 entry->prev_ = nullptr;
80
81 // TODO: Do we need a lock here?
82 entry->next_ = __jit_debug_descriptor.first_entry_;
83 if (entry->next_ != nullptr) {
84 entry->next_->prev_ = entry;
85 }
86 __jit_debug_descriptor.first_entry_ = entry;
87 __jit_debug_descriptor.relevant_entry_ = entry;
88
89 __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
90 __jit_debug_register_code();
91 return entry;
92}
93
94
95static void UnregisterCodeEntry(JITCodeEntry* entry) {
96 // TODO: Do we need a lock here?
97 if (entry->prev_ != nullptr) {
98 entry->prev_->next_ = entry->next_;
99 } else {
100 __jit_debug_descriptor.first_entry_ = entry->next_;
101 }
102
103 if (entry->next_ != nullptr) {
104 entry->next_->prev_ = entry->prev_;
105 }
106
107 __jit_debug_descriptor.relevant_entry_ = entry;
108 __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
109 __jit_debug_register_code();
110 delete entry;
111}
112
David Srbecky533c2072015-04-22 12:20:22 +0100113template <typename ElfTypes>
114ElfFileImpl<ElfTypes>::ElfFileImpl(File* file, bool writable,
115 bool program_header_only,
116 uint8_t* requested_base)
Brian Carlstromc1409452014-02-26 14:06:23 -0800117 : file_(file),
118 writable_(writable),
119 program_header_only_(program_header_only),
Alex Light3470ab42014-06-18 10:35:45 -0700120 header_(nullptr),
121 base_address_(nullptr),
122 program_headers_start_(nullptr),
123 section_headers_start_(nullptr),
124 dynamic_program_header_(nullptr),
125 dynamic_section_start_(nullptr),
126 symtab_section_start_(nullptr),
127 dynsym_section_start_(nullptr),
128 strtab_section_start_(nullptr),
129 dynstr_section_start_(nullptr),
130 hash_section_start_(nullptr),
131 symtab_symbol_table_(nullptr),
132 dynsym_symbol_table_(nullptr),
133 jit_elf_image_(nullptr),
Igor Murashkin46774762014-10-22 11:37:02 -0700134 jit_gdb_entry_(nullptr),
135 requested_base_(requested_base) {
Alex Light3470ab42014-06-18 10:35:45 -0700136 CHECK(file != nullptr);
Brian Carlstromc1409452014-02-26 14:06:23 -0800137}
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800138
David Srbecky533c2072015-04-22 12:20:22 +0100139template <typename ElfTypes>
140ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(
141 File* file, bool writable, bool program_header_only,
142 std::string* error_msg, uint8_t* requested_base) {
143 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
144 (file, writable, program_header_only, requested_base));
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800145 int prot;
146 int flags;
Alex Light3470ab42014-06-18 10:35:45 -0700147 if (writable) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800148 prot = PROT_READ | PROT_WRITE;
149 flags = MAP_SHARED;
150 } else {
151 prot = PROT_READ;
152 flags = MAP_PRIVATE;
153 }
Alex Light3470ab42014-06-18 10:35:45 -0700154 if (!elf_file->Setup(prot, flags, error_msg)) {
155 return nullptr;
156 }
157 return elf_file.release();
158}
159
David Srbecky533c2072015-04-22 12:20:22 +0100160template <typename ElfTypes>
161ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(
162 File* file, int prot, int flags, std::string* error_msg) {
163 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
164 (file, (prot & PROT_WRITE) == PROT_WRITE, /*program_header_only*/false,
165 /*requested_base*/nullptr));
Alex Light3470ab42014-06-18 10:35:45 -0700166 if (!elf_file->Setup(prot, flags, error_msg)) {
167 return nullptr;
168 }
169 return elf_file.release();
170}
171
David Srbecky533c2072015-04-22 12:20:22 +0100172template <typename ElfTypes>
173bool ElfFileImpl<ElfTypes>::Setup(int prot, int flags, std::string* error_msg) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800174 int64_t temp_file_length = file_->GetLength();
175 if (temp_file_length < 0) {
176 errno = -temp_file_length;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700177 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
178 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800179 return false;
180 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800181 size_t file_length = static_cast<size_t>(temp_file_length);
Tong Shen62d1ca32014-09-03 17:24:56 -0700182 if (file_length < sizeof(Elf_Ehdr)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800183 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
Tong Shen62d1ca32014-09-03 17:24:56 -0700184 "%zd bytes: '%s'", file_length, sizeof(Elf_Ehdr),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700185 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800186 return false;
187 }
188
Brian Carlstromc1409452014-02-26 14:06:23 -0800189 if (program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800190 // first just map ELF header to get program header size information
Tong Shen62d1ca32014-09-03 17:24:56 -0700191 size_t elf_header_size = sizeof(Elf_Ehdr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700192 if (!SetMap(MemMap::MapFile(elf_header_size, prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800193 file_->GetPath().c_str(), error_msg),
194 error_msg)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800195 return false;
196 }
197 // then remap to cover program header
198 size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
Brian Carlstrom3a223612013-10-10 17:18:24 -0700199 if (file_length < program_header_size) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800200 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700201 "header of %zd bytes: '%s'", file_length,
Tong Shen62d1ca32014-09-03 17:24:56 -0700202 sizeof(Elf_Ehdr), file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700203 return false;
204 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700205 if (!SetMap(MemMap::MapFile(program_header_size, prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800206 file_->GetPath().c_str(), error_msg),
207 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700208 *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800209 return false;
210 }
211 } else {
212 // otherwise map entire file
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700213 if (!SetMap(MemMap::MapFile(file_->GetLength(), prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800214 file_->GetPath().c_str(), error_msg),
215 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700216 *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800217 return false;
218 }
219 }
220
Andreas Gampedaab38c2014-09-12 18:38:24 -0700221 if (program_header_only_) {
222 program_headers_start_ = Begin() + GetHeader().e_phoff;
223 } else {
224 if (!CheckAndSet(GetHeader().e_phoff, "program headers", &program_headers_start_, error_msg)) {
225 return false;
226 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800227
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800228 // Setup section headers.
Andreas Gampedaab38c2014-09-12 18:38:24 -0700229 if (!CheckAndSet(GetHeader().e_shoff, "section headers", &section_headers_start_, error_msg)) {
230 return false;
231 }
232
233 // Find shstrtab.
Tong Shen62d1ca32014-09-03 17:24:56 -0700234 Elf_Shdr* shstrtab_section_header = GetSectionNameStringSection();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700235 if (shstrtab_section_header == nullptr) {
236 *error_msg = StringPrintf("Failed to find shstrtab section header in ELF file: '%s'",
237 file_->GetPath().c_str());
238 return false;
239 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800240
241 // Find .dynamic section info from program header
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000242 dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
Alex Light3470ab42014-06-18 10:35:45 -0700243 if (dynamic_program_header_ == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700244 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
245 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800246 return false;
247 }
248
Andreas Gampedaab38c2014-09-12 18:38:24 -0700249 if (!CheckAndSet(GetDynamicProgramHeader().p_offset, "dynamic section",
Ian Rogers13735952014-10-08 12:43:28 -0700250 reinterpret_cast<uint8_t**>(&dynamic_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700251 return false;
252 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800253
254 // Find other sections from section headers
Tong Shen62d1ca32014-09-03 17:24:56 -0700255 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
256 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700257 if (section_header == nullptr) {
258 *error_msg = StringPrintf("Failed to find section header for section %d in ELF file: '%s'",
259 i, file_->GetPath().c_str());
260 return false;
261 }
262 switch (section_header->sh_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000263 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700264 if (!CheckAndSet(section_header->sh_offset, "symtab",
Ian Rogers13735952014-10-08 12:43:28 -0700265 reinterpret_cast<uint8_t**>(&symtab_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700266 return false;
267 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800268 break;
269 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000270 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700271 if (!CheckAndSet(section_header->sh_offset, "dynsym",
Ian Rogers13735952014-10-08 12:43:28 -0700272 reinterpret_cast<uint8_t**>(&dynsym_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700273 return false;
274 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800275 break;
276 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000277 case SHT_STRTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800278 // TODO: base these off of sh_link from .symtab and .dynsym above
Andreas Gampedaab38c2014-09-12 18:38:24 -0700279 if ((section_header->sh_flags & SHF_ALLOC) != 0) {
280 // Check that this is named ".dynstr" and ignore otherwise.
281 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
282 if (strncmp(".dynstr", header_name, 8) == 0) {
283 if (!CheckAndSet(section_header->sh_offset, "dynstr",
Ian Rogers13735952014-10-08 12:43:28 -0700284 reinterpret_cast<uint8_t**>(&dynstr_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700285 return false;
286 }
287 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800288 } else {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700289 // Check that this is named ".strtab" and ignore otherwise.
290 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
291 if (strncmp(".strtab", header_name, 8) == 0) {
292 if (!CheckAndSet(section_header->sh_offset, "strtab",
Ian Rogers13735952014-10-08 12:43:28 -0700293 reinterpret_cast<uint8_t**>(&strtab_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700294 return false;
295 }
296 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800297 }
298 break;
299 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000300 case SHT_DYNAMIC: {
Ian Rogers13735952014-10-08 12:43:28 -0700301 if (reinterpret_cast<uint8_t*>(dynamic_section_start_) !=
Andreas Gampedaab38c2014-09-12 18:38:24 -0700302 Begin() + section_header->sh_offset) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800303 LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
Brian Carlstrom265091e2013-01-30 14:08:26 -0800304 << file_->GetPath() << ": " << std::hex
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800305 << reinterpret_cast<void*>(dynamic_section_start_)
Andreas Gampedaab38c2014-09-12 18:38:24 -0700306 << " != " << reinterpret_cast<void*>(Begin() + section_header->sh_offset);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800307 return false;
308 }
309 break;
310 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000311 case SHT_HASH: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700312 if (!CheckAndSet(section_header->sh_offset, "hash section",
Ian Rogers13735952014-10-08 12:43:28 -0700313 reinterpret_cast<uint8_t**>(&hash_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700314 return false;
315 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800316 break;
317 }
318 }
319 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700320
321 // Check for the existence of some sections.
322 if (!CheckSectionsExist(error_msg)) {
323 return false;
324 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800325 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700326
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800327 return true;
328}
329
David Srbecky533c2072015-04-22 12:20:22 +0100330template <typename ElfTypes>
331ElfFileImpl<ElfTypes>::~ElfFileImpl() {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800332 STLDeleteElements(&segments_);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800333 delete symtab_symbol_table_;
334 delete dynsym_symbol_table_;
Mark Mendellae9fd932014-02-10 16:14:35 -0800335 delete jit_elf_image_;
336 if (jit_gdb_entry_) {
337 UnregisterCodeEntry(jit_gdb_entry_);
338 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800339}
340
David Srbecky533c2072015-04-22 12:20:22 +0100341template <typename ElfTypes>
342bool ElfFileImpl<ElfTypes>::CheckAndSet(Elf32_Off offset, const char* label,
343 uint8_t** target, std::string* error_msg) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700344 if (Begin() + offset >= End()) {
345 *error_msg = StringPrintf("Offset %d is out of range for %s in ELF file: '%s'", offset, label,
346 file_->GetPath().c_str());
347 return false;
348 }
349 *target = Begin() + offset;
350 return true;
351}
352
David Srbecky533c2072015-04-22 12:20:22 +0100353template <typename ElfTypes>
354bool ElfFileImpl<ElfTypes>::CheckSectionsLinked(const uint8_t* source,
355 const uint8_t* target) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700356 // Only works in whole-program mode, as we need to iterate over the sections.
357 // Note that we normally can't search by type, as duplicates are allowed for most section types.
358 if (program_header_only_) {
359 return true;
360 }
361
Tong Shen62d1ca32014-09-03 17:24:56 -0700362 Elf_Shdr* source_section = nullptr;
363 Elf_Word target_index = 0;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700364 bool target_found = false;
Tong Shen62d1ca32014-09-03 17:24:56 -0700365 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
366 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700367
368 if (Begin() + section_header->sh_offset == source) {
369 // Found the source.
370 source_section = section_header;
371 if (target_index) {
372 break;
373 }
374 } else if (Begin() + section_header->sh_offset == target) {
375 target_index = i;
376 target_found = true;
377 if (source_section != nullptr) {
378 break;
379 }
380 }
381 }
382
383 return target_found && source_section != nullptr && source_section->sh_link == target_index;
384}
385
David Srbecky533c2072015-04-22 12:20:22 +0100386template <typename ElfTypes>
387bool ElfFileImpl<ElfTypes>::CheckSectionsExist(std::string* error_msg) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700388 if (!program_header_only_) {
389 // If in full mode, need section headers.
390 if (section_headers_start_ == nullptr) {
391 *error_msg = StringPrintf("No section headers in ELF file: '%s'", file_->GetPath().c_str());
392 return false;
393 }
394 }
395
396 // This is redundant, but defensive.
397 if (dynamic_program_header_ == nullptr) {
398 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
399 file_->GetPath().c_str());
400 return false;
401 }
402
403 // Need a dynamic section. This is redundant, but defensive.
404 if (dynamic_section_start_ == nullptr) {
405 *error_msg = StringPrintf("Failed to find dynamic section in ELF file: '%s'",
406 file_->GetPath().c_str());
407 return false;
408 }
409
410 // Symtab validation. These is not really a hard failure, as we are currently not using the
411 // symtab internally, but it's nice to be defensive.
412 if (symtab_section_start_ != nullptr) {
413 // When there's a symtab, there should be a strtab.
414 if (strtab_section_start_ == nullptr) {
415 *error_msg = StringPrintf("No strtab for symtab in ELF file: '%s'", file_->GetPath().c_str());
416 return false;
417 }
418
419 // The symtab should link to the strtab.
Ian Rogers13735952014-10-08 12:43:28 -0700420 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(symtab_section_start_),
421 reinterpret_cast<const uint8_t*>(strtab_section_start_))) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700422 *error_msg = StringPrintf("Symtab is not linked to the strtab in ELF file: '%s'",
423 file_->GetPath().c_str());
424 return false;
425 }
426 }
427
428 // We always need a dynstr & dynsym.
429 if (dynstr_section_start_ == nullptr) {
430 *error_msg = StringPrintf("No dynstr in ELF file: '%s'", file_->GetPath().c_str());
431 return false;
432 }
433 if (dynsym_section_start_ == nullptr) {
434 *error_msg = StringPrintf("No dynsym in ELF file: '%s'", file_->GetPath().c_str());
435 return false;
436 }
437
438 // Need a hash section for dynamic symbol lookup.
439 if (hash_section_start_ == nullptr) {
440 *error_msg = StringPrintf("Failed to find hash section in ELF file: '%s'",
441 file_->GetPath().c_str());
442 return false;
443 }
444
445 // And the hash section should be linking to the dynsym.
Ian Rogers13735952014-10-08 12:43:28 -0700446 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(hash_section_start_),
447 reinterpret_cast<const uint8_t*>(dynsym_section_start_))) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700448 *error_msg = StringPrintf("Hash section is not linked to the dynstr in ELF file: '%s'",
449 file_->GetPath().c_str());
450 return false;
451 }
452
Andreas Gampea696c0a2014-12-10 20:51:45 -0800453 // We'd also like to confirm a shstrtab in program_header_only_ mode (else Open() does this for
454 // us). This is usually the last in an oat file, and a good indicator of whether writing was
455 // successful (or the process crashed and left garbage).
456 if (program_header_only_) {
457 // It might not be mapped, but we can compare against the file size.
458 int64_t offset = static_cast<int64_t>(GetHeader().e_shoff +
459 (GetHeader().e_shstrndx * GetHeader().e_shentsize));
460 if (offset >= file_->GetLength()) {
461 *error_msg = StringPrintf("Shstrtab is not in the mapped ELF file: '%s'",
462 file_->GetPath().c_str());
463 return false;
464 }
465 }
466
Andreas Gampedaab38c2014-09-12 18:38:24 -0700467 return true;
468}
469
David Srbecky533c2072015-04-22 12:20:22 +0100470template <typename ElfTypes>
471bool ElfFileImpl<ElfTypes>::SetMap(MemMap* map, std::string* error_msg) {
Alex Light3470ab42014-06-18 10:35:45 -0700472 if (map == nullptr) {
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800473 // MemMap::Open should have already set an error.
474 DCHECK(!error_msg->empty());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800475 return false;
476 }
477 map_.reset(map);
Alex Light3470ab42014-06-18 10:35:45 -0700478 CHECK(map_.get() != nullptr) << file_->GetPath();
479 CHECK(map_->Begin() != nullptr) << file_->GetPath();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800480
Tong Shen62d1ca32014-09-03 17:24:56 -0700481 header_ = reinterpret_cast<Elf_Ehdr*>(map_->Begin());
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000482 if ((ELFMAG0 != header_->e_ident[EI_MAG0])
483 || (ELFMAG1 != header_->e_ident[EI_MAG1])
484 || (ELFMAG2 != header_->e_ident[EI_MAG2])
485 || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800486 *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
487 ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800488 file_->GetPath().c_str(),
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000489 header_->e_ident[EI_MAG0],
490 header_->e_ident[EI_MAG1],
491 header_->e_ident[EI_MAG2],
492 header_->e_ident[EI_MAG3]);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800493 return false;
494 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700495 uint8_t elf_class = (sizeof(Elf_Addr) == sizeof(Elf64_Addr)) ? ELFCLASS64 : ELFCLASS32;
496 if (elf_class != header_->e_ident[EI_CLASS]) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800497 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
Tong Shen62d1ca32014-09-03 17:24:56 -0700498 elf_class,
Brian Carlstromc1409452014-02-26 14:06:23 -0800499 file_->GetPath().c_str(),
500 header_->e_ident[EI_CLASS]);
501 return false;
502 }
503 if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
504 *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
505 ELFDATA2LSB,
506 file_->GetPath().c_str(),
507 header_->e_ident[EI_CLASS]);
508 return false;
509 }
510 if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
511 *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
512 EV_CURRENT,
513 file_->GetPath().c_str(),
514 header_->e_ident[EI_CLASS]);
515 return false;
516 }
517 if (ET_DYN != header_->e_type) {
518 *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
519 ET_DYN,
520 file_->GetPath().c_str(),
521 header_->e_type);
522 return false;
523 }
524 if (EV_CURRENT != header_->e_version) {
525 *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
526 EV_CURRENT,
527 file_->GetPath().c_str(),
528 header_->e_version);
529 return false;
530 }
531 if (0 != header_->e_entry) {
532 *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
533 0,
534 file_->GetPath().c_str(),
Tong Shen62d1ca32014-09-03 17:24:56 -0700535 static_cast<int32_t>(header_->e_entry));
Brian Carlstromc1409452014-02-26 14:06:23 -0800536 return false;
537 }
538 if (0 == header_->e_phoff) {
539 *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
540 file_->GetPath().c_str());
541 return false;
542 }
543 if (0 == header_->e_shoff) {
544 *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
545 file_->GetPath().c_str());
546 return false;
547 }
548 if (0 == header_->e_ehsize) {
549 *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
550 file_->GetPath().c_str());
551 return false;
552 }
553 if (0 == header_->e_phentsize) {
554 *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
555 file_->GetPath().c_str());
556 return false;
557 }
558 if (0 == header_->e_phnum) {
559 *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
560 file_->GetPath().c_str());
561 return false;
562 }
563 if (0 == header_->e_shentsize) {
564 *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
565 file_->GetPath().c_str());
566 return false;
567 }
568 if (0 == header_->e_shnum) {
569 *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
570 file_->GetPath().c_str());
571 return false;
572 }
573 if (0 == header_->e_shstrndx) {
574 *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
575 file_->GetPath().c_str());
576 return false;
577 }
578 if (header_->e_shstrndx >= header_->e_shnum) {
579 *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
580 header_->e_shstrndx,
581 header_->e_shnum,
582 file_->GetPath().c_str());
583 return false;
584 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800585
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800586 if (!program_header_only_) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800587 if (header_->e_phoff >= Size()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700588 *error_msg = StringPrintf("Failed to find e_phoff value %" PRIu64 " less than %zd in %s",
589 static_cast<uint64_t>(header_->e_phoff),
Brian Carlstromc1409452014-02-26 14:06:23 -0800590 Size(),
591 file_->GetPath().c_str());
592 return false;
593 }
594 if (header_->e_shoff >= Size()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700595 *error_msg = StringPrintf("Failed to find e_shoff value %" PRIu64 " less than %zd in %s",
596 static_cast<uint64_t>(header_->e_shoff),
Brian Carlstromc1409452014-02-26 14:06:23 -0800597 Size(),
598 file_->GetPath().c_str());
599 return false;
600 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800601 }
602 return true;
603}
604
David Srbecky533c2072015-04-22 12:20:22 +0100605template <typename ElfTypes>
606typename ElfTypes::Ehdr& ElfFileImpl<ElfTypes>::GetHeader() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700607 CHECK(header_ != nullptr); // Header has been checked in SetMap. This is a sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800608 return *header_;
609}
610
David Srbecky533c2072015-04-22 12:20:22 +0100611template <typename ElfTypes>
612uint8_t* ElfFileImpl<ElfTypes>::GetProgramHeadersStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700613 CHECK(program_headers_start_ != nullptr); // Header has been set in Setup. This is a sanity
614 // check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800615 return program_headers_start_;
616}
617
David Srbecky533c2072015-04-22 12:20:22 +0100618template <typename ElfTypes>
619uint8_t* ElfFileImpl<ElfTypes>::GetSectionHeadersStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700620 CHECK(!program_header_only_); // Only used in "full" mode.
621 CHECK(section_headers_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800622 return section_headers_start_;
623}
624
David Srbecky533c2072015-04-22 12:20:22 +0100625template <typename ElfTypes>
626typename ElfTypes::Phdr& ElfFileImpl<ElfTypes>::GetDynamicProgramHeader() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700627 CHECK(dynamic_program_header_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800628 return *dynamic_program_header_;
629}
630
David Srbecky533c2072015-04-22 12:20:22 +0100631template <typename ElfTypes>
632typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::GetDynamicSectionStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700633 CHECK(dynamic_section_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800634 return dynamic_section_start_;
635}
636
David Srbecky533c2072015-04-22 12:20:22 +0100637template <typename ElfTypes>
638typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbolSectionStart(
639 Elf_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800640 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800641 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000642 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700643 return symtab_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800644 break;
645 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000646 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700647 return dynsym_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800648 break;
649 }
650 default: {
651 LOG(FATAL) << section_type;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700652 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800653 }
654 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800655}
656
David Srbecky533c2072015-04-22 12:20:22 +0100657template <typename ElfTypes>
658const char* ElfFileImpl<ElfTypes>::GetStringSectionStart(
659 Elf_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800660 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800661 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000662 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700663 return strtab_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800664 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000665 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700666 return dynstr_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800667 }
668 default: {
669 LOG(FATAL) << section_type;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700670 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800671 }
672 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800673}
674
David Srbecky533c2072015-04-22 12:20:22 +0100675template <typename ElfTypes>
676const char* ElfFileImpl<ElfTypes>::GetString(Elf_Word section_type,
677 Elf_Word i) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800678 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
679 if (i == 0) {
Alex Light3470ab42014-06-18 10:35:45 -0700680 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800681 }
682 const char* string_section_start = GetStringSectionStart(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700683 if (string_section_start == nullptr) {
684 return nullptr;
685 }
686 return string_section_start + i;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800687}
688
Andreas Gampedaab38c2014-09-12 18:38:24 -0700689// WARNING: The following methods do not check for an error condition (non-existent hash section).
690// It is the caller's job to do this.
691
David Srbecky533c2072015-04-22 12:20:22 +0100692template <typename ElfTypes>
693typename ElfTypes::Word* ElfFileImpl<ElfTypes>::GetHashSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800694 return hash_section_start_;
695}
696
David Srbecky533c2072015-04-22 12:20:22 +0100697template <typename ElfTypes>
698typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucketNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800699 return GetHashSectionStart()[0];
700}
701
David Srbecky533c2072015-04-22 12:20:22 +0100702template <typename ElfTypes>
703typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChainNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800704 return GetHashSectionStart()[1];
705}
706
David Srbecky533c2072015-04-22 12:20:22 +0100707template <typename ElfTypes>
708typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucket(size_t i, bool* ok) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700709 if (i >= GetHashBucketNum()) {
710 *ok = false;
711 return 0;
712 }
713 *ok = true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800714 // 0 is nbucket, 1 is nchain
715 return GetHashSectionStart()[2 + i];
716}
717
David Srbecky533c2072015-04-22 12:20:22 +0100718template <typename ElfTypes>
719typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChain(size_t i, bool* ok) const {
Yevgeny Roubanacb01382014-11-24 13:40:56 +0600720 if (i >= GetHashChainNum()) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700721 *ok = false;
722 return 0;
723 }
724 *ok = true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800725 // 0 is nbucket, 1 is nchain, & chains are after buckets
726 return GetHashSectionStart()[2 + GetHashBucketNum() + i];
727}
728
David Srbecky533c2072015-04-22 12:20:22 +0100729template <typename ElfTypes>
730typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetProgramHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800731 return GetHeader().e_phnum;
732}
733
David Srbecky533c2072015-04-22 12:20:22 +0100734template <typename ElfTypes>
735typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::GetProgramHeader(Elf_Word i) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700736 CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath(); // Sanity check for caller.
Ian Rogers13735952014-10-08 12:43:28 -0700737 uint8_t* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700738 if (program_header >= End()) {
739 return nullptr; // Failure condition.
740 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700741 return reinterpret_cast<Elf_Phdr*>(program_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800742}
743
David Srbecky533c2072015-04-22 12:20:22 +0100744template <typename ElfTypes>
745typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::FindProgamHeaderByType(Elf_Word type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700746 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
747 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700748 if (program_header->p_type == type) {
749 return program_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800750 }
751 }
Alex Light3470ab42014-06-18 10:35:45 -0700752 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800753}
754
David Srbecky533c2072015-04-22 12:20:22 +0100755template <typename ElfTypes>
756typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSectionHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800757 return GetHeader().e_shnum;
758}
759
David Srbecky533c2072015-04-22 12:20:22 +0100760template <typename ElfTypes>
761typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionHeader(Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800762 // Can only access arbitrary sections when we have the whole file, not just program header.
763 // Even if we Load(), it doesn't bring in all the sections.
764 CHECK(!program_header_only_) << file_->GetPath();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700765 if (i >= GetSectionHeaderNum()) {
766 return nullptr; // Failure condition.
767 }
Ian Rogers13735952014-10-08 12:43:28 -0700768 uint8_t* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700769 if (section_header >= End()) {
770 return nullptr; // Failure condition.
771 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700772 return reinterpret_cast<Elf_Shdr*>(section_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800773}
774
David Srbecky533c2072015-04-22 12:20:22 +0100775template <typename ElfTypes>
776typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByType(Elf_Word type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800777 // Can only access arbitrary sections when we have the whole file, not just program header.
778 // We could change this to switch on known types if they were detected during loading.
779 CHECK(!program_header_only_) << file_->GetPath();
Tong Shen62d1ca32014-09-03 17:24:56 -0700780 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
781 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700782 if (section_header->sh_type == type) {
783 return section_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800784 }
785 }
Alex Light3470ab42014-06-18 10:35:45 -0700786 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800787}
788
789// from bionic
Brian Carlstrom265091e2013-01-30 14:08:26 -0800790static unsigned elfhash(const char *_name) {
791 const unsigned char *name = (const unsigned char *) _name;
792 unsigned h = 0, g;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800793
Brian Carlstromdf629502013-07-17 22:39:56 -0700794 while (*name) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800795 h = (h << 4) + *name++;
796 g = h & 0xf0000000;
797 h ^= g;
798 h ^= g >> 24;
799 }
800 return h;
801}
802
David Srbecky533c2072015-04-22 12:20:22 +0100803template <typename ElfTypes>
804typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionNameStringSection() const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800805 return GetSectionHeader(GetHeader().e_shstrndx);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800806}
807
David Srbecky533c2072015-04-22 12:20:22 +0100808template <typename ElfTypes>
809const uint8_t* ElfFileImpl<ElfTypes>::FindDynamicSymbolAddress(
810 const std::string& symbol_name) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700811 // Check that we have a hash section.
812 if (GetHashSectionStart() == nullptr) {
813 return nullptr; // Failure condition.
814 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700815 const Elf_Sym* sym = FindDynamicSymbol(symbol_name);
Alex Light3470ab42014-06-18 10:35:45 -0700816 if (sym != nullptr) {
Igor Murashkin46774762014-10-22 11:37:02 -0700817 // TODO: we need to change this to calculate base_address_ in ::Open,
818 // otherwise it will be wrongly 0 if ::Load has not yet been called.
Alex Light3470ab42014-06-18 10:35:45 -0700819 return base_address_ + sym->st_value;
820 } else {
821 return nullptr;
822 }
823}
824
Andreas Gampedaab38c2014-09-12 18:38:24 -0700825// WARNING: Only called from FindDynamicSymbolAddress. Elides check for hash section.
David Srbecky533c2072015-04-22 12:20:22 +0100826template <typename ElfTypes>
827const typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindDynamicSymbol(
828 const std::string& symbol_name) const {
Andreas Gampec48b2062014-09-08 23:39:45 -0700829 if (GetHashBucketNum() == 0) {
830 // No dynamic symbols at all.
831 return nullptr;
832 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700833 Elf_Word hash = elfhash(symbol_name.c_str());
834 Elf_Word bucket_index = hash % GetHashBucketNum();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700835 bool ok;
Tong Shen62d1ca32014-09-03 17:24:56 -0700836 Elf_Word symbol_and_chain_index = GetHashBucket(bucket_index, &ok);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700837 if (!ok) {
838 return nullptr;
839 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800840 while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700841 Elf_Sym* symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700842 if (symbol == nullptr) {
843 return nullptr; // Failure condition.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800844 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700845 const char* name = GetString(SHT_DYNSYM, symbol->st_name);
846 if (symbol_name == name) {
847 return symbol;
848 }
849 symbol_and_chain_index = GetHashChain(symbol_and_chain_index, &ok);
850 if (!ok) {
851 return nullptr;
852 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800853 }
Alex Light3470ab42014-06-18 10:35:45 -0700854 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800855}
856
David Srbecky533c2072015-04-22 12:20:22 +0100857template <typename ElfTypes>
858bool ElfFileImpl<ElfTypes>::IsSymbolSectionType(Elf_Word section_type) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700859 return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
860}
861
David Srbecky533c2072015-04-22 12:20:22 +0100862template <typename ElfTypes>
863typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSymbolNum(Elf_Shdr& section_header) const {
Brian Carlstromc1409452014-02-26 14:06:23 -0800864 CHECK(IsSymbolSectionType(section_header.sh_type))
865 << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800866 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
867 return section_header.sh_size / section_header.sh_entsize;
868}
869
David Srbecky533c2072015-04-22 12:20:22 +0100870template <typename ElfTypes>
871typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbol(Elf_Word section_type, Elf_Word i) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700872 Elf_Sym* sym_start = GetSymbolSectionStart(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700873 if (sym_start == nullptr) {
874 return nullptr;
875 }
876 return sym_start + i;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800877}
878
David Srbecky533c2072015-04-22 12:20:22 +0100879template <typename ElfTypes>
880typename ElfFileImpl<ElfTypes>::SymbolTable**
881ElfFileImpl<ElfTypes>::GetSymbolTable(Elf_Word section_type) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800882 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
883 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000884 case SHT_SYMTAB: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800885 return &symtab_symbol_table_;
886 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000887 case SHT_DYNSYM: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800888 return &dynsym_symbol_table_;
889 }
890 default: {
891 LOG(FATAL) << section_type;
Alex Light3470ab42014-06-18 10:35:45 -0700892 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800893 }
894 }
895}
896
David Srbecky533c2072015-04-22 12:20:22 +0100897template <typename ElfTypes>
898typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindSymbolByName(
899 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800900 CHECK(!program_header_only_) << file_->GetPath();
901 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800902
903 SymbolTable** symbol_table = GetSymbolTable(section_type);
Alex Light3470ab42014-06-18 10:35:45 -0700904 if (*symbol_table != nullptr || build_map) {
905 if (*symbol_table == nullptr) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800906 DCHECK(build_map);
907 *symbol_table = new SymbolTable;
Tong Shen62d1ca32014-09-03 17:24:56 -0700908 Elf_Shdr* symbol_section = FindSectionByType(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700909 if (symbol_section == nullptr) {
910 return nullptr; // Failure condition.
911 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700912 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700913 if (string_section == nullptr) {
914 return nullptr; // Failure condition.
915 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800916 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700917 Elf_Sym* symbol = GetSymbol(section_type, i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700918 if (symbol == nullptr) {
919 return nullptr; // Failure condition.
920 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700921 unsigned char type = (sizeof(Elf_Addr) == sizeof(Elf64_Addr))
922 ? ELF64_ST_TYPE(symbol->st_info)
923 : ELF32_ST_TYPE(symbol->st_info);
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000924 if (type == STT_NOTYPE) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800925 continue;
926 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700927 const char* name = GetString(*string_section, symbol->st_name);
Alex Light3470ab42014-06-18 10:35:45 -0700928 if (name == nullptr) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800929 continue;
930 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700931 std::pair<typename SymbolTable::iterator, bool> result =
Andreas Gampedaab38c2014-09-12 18:38:24 -0700932 (*symbol_table)->insert(std::make_pair(name, symbol));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800933 if (!result.second) {
934 // If a duplicate, make sure it has the same logical value. Seen on x86.
Andreas Gampedaab38c2014-09-12 18:38:24 -0700935 if ((symbol->st_value != result.first->second->st_value) ||
936 (symbol->st_size != result.first->second->st_size) ||
937 (symbol->st_info != result.first->second->st_info) ||
938 (symbol->st_other != result.first->second->st_other) ||
939 (symbol->st_shndx != result.first->second->st_shndx)) {
940 return nullptr; // Failure condition.
941 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800942 }
943 }
944 }
Alex Light3470ab42014-06-18 10:35:45 -0700945 CHECK(*symbol_table != nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -0700946 typename SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800947 if (it == (*symbol_table)->end()) {
Alex Light3470ab42014-06-18 10:35:45 -0700948 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800949 }
950 return it->second;
951 }
952
953 // Fall back to linear search
Tong Shen62d1ca32014-09-03 17:24:56 -0700954 Elf_Shdr* symbol_section = FindSectionByType(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700955 if (symbol_section == nullptr) {
956 return nullptr;
957 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700958 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700959 if (string_section == nullptr) {
960 return nullptr;
961 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800962 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700963 Elf_Sym* symbol = GetSymbol(section_type, i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700964 if (symbol == nullptr) {
965 return nullptr; // Failure condition.
966 }
967 const char* name = GetString(*string_section, symbol->st_name);
Alex Light3470ab42014-06-18 10:35:45 -0700968 if (name == nullptr) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800969 continue;
970 }
971 if (symbol_name == name) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700972 return symbol;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800973 }
974 }
Alex Light3470ab42014-06-18 10:35:45 -0700975 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800976}
977
David Srbecky533c2072015-04-22 12:20:22 +0100978template <typename ElfTypes>
979typename ElfTypes::Addr ElfFileImpl<ElfTypes>::FindSymbolAddress(
980 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700981 Elf_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
Alex Light3470ab42014-06-18 10:35:45 -0700982 if (symbol == nullptr) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800983 return 0;
984 }
985 return symbol->st_value;
986}
987
David Srbecky533c2072015-04-22 12:20:22 +0100988template <typename ElfTypes>
989const char* ElfFileImpl<ElfTypes>::GetString(Elf_Shdr& string_section,
990 Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800991 CHECK(!program_header_only_) << file_->GetPath();
992 // TODO: remove this static_cast from enum when using -std=gnu++0x
Tong Shen62d1ca32014-09-03 17:24:56 -0700993 if (static_cast<Elf_Word>(SHT_STRTAB) != string_section.sh_type) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700994 return nullptr; // Failure condition.
995 }
996 if (i >= string_section.sh_size) {
997 return nullptr;
998 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800999 if (i == 0) {
Alex Light3470ab42014-06-18 10:35:45 -07001000 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001001 }
Ian Rogers13735952014-10-08 12:43:28 -07001002 uint8_t* strings = Begin() + string_section.sh_offset;
1003 uint8_t* string = strings + i;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001004 if (string >= End()) {
1005 return nullptr;
1006 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001007 return reinterpret_cast<const char*>(string);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001008}
1009
David Srbecky533c2072015-04-22 12:20:22 +01001010template <typename ElfTypes>
1011typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetDynamicNum() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001012 return GetDynamicProgramHeader().p_filesz / sizeof(Elf_Dyn);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001013}
1014
David Srbecky533c2072015-04-22 12:20:22 +01001015template <typename ElfTypes>
1016typename ElfTypes::Dyn& ElfFileImpl<ElfTypes>::GetDynamic(Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001017 CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
1018 return *(GetDynamicSectionStart() + i);
1019}
1020
David Srbecky533c2072015-04-22 12:20:22 +01001021template <typename ElfTypes>
1022typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::FindDynamicByType(Elf_Sword type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001023 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1024 Elf_Dyn* dyn = &GetDynamic(i);
Alex Light53cb16b2014-06-12 11:26:29 -07001025 if (dyn->d_tag == type) {
1026 return dyn;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001027 }
1028 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001029 return nullptr;
Alex Light53cb16b2014-06-12 11:26:29 -07001030}
1031
David Srbecky533c2072015-04-22 12:20:22 +01001032template <typename ElfTypes>
1033typename ElfTypes::Word ElfFileImpl<ElfTypes>::FindDynamicValueByType(Elf_Sword type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001034 Elf_Dyn* dyn = FindDynamicByType(type);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001035 if (dyn == nullptr) {
Alex Light53cb16b2014-06-12 11:26:29 -07001036 return 0;
1037 } else {
1038 return dyn->d_un.d_val;
1039 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001040}
1041
David Srbecky533c2072015-04-22 12:20:22 +01001042template <typename ElfTypes>
1043typename ElfTypes::Rel* ElfFileImpl<ElfTypes>::GetRelSectionStart(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001044 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Tong Shen62d1ca32014-09-03 17:24:56 -07001045 return reinterpret_cast<Elf_Rel*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001046}
1047
David Srbecky533c2072015-04-22 12:20:22 +01001048template <typename ElfTypes>
1049typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelNum(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001050 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001051 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
1052 return section_header.sh_size / section_header.sh_entsize;
1053}
1054
David Srbecky533c2072015-04-22 12:20:22 +01001055template <typename ElfTypes>
1056typename ElfTypes::Rel& ElfFileImpl<ElfTypes>::GetRel(Elf_Shdr& section_header, Elf_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001057 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001058 CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
1059 return *(GetRelSectionStart(section_header) + i);
1060}
1061
David Srbecky533c2072015-04-22 12:20:22 +01001062template <typename ElfTypes>
1063typename ElfTypes::Rela* ElfFileImpl<ElfTypes>::GetRelaSectionStart(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001064 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Tong Shen62d1ca32014-09-03 17:24:56 -07001065 return reinterpret_cast<Elf_Rela*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001066}
1067
David Srbecky533c2072015-04-22 12:20:22 +01001068template <typename ElfTypes>
1069typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelaNum(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001070 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001071 return section_header.sh_size / section_header.sh_entsize;
1072}
1073
David Srbecky533c2072015-04-22 12:20:22 +01001074template <typename ElfTypes>
1075typename ElfTypes::Rela& ElfFileImpl<ElfTypes>::GetRela(Elf_Shdr& section_header, Elf_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001076 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001077 CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
1078 return *(GetRelaSectionStart(section_header) + i);
1079}
1080
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001081// Base on bionic phdr_table_get_load_size
David Srbecky533c2072015-04-22 12:20:22 +01001082template <typename ElfTypes>
1083size_t ElfFileImpl<ElfTypes>::GetLoadedSize() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001084 Elf_Addr min_vaddr = 0xFFFFFFFFu;
1085 Elf_Addr max_vaddr = 0x00000000u;
1086 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1087 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001088 if (program_header->p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001089 continue;
1090 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001091 Elf_Addr begin_vaddr = program_header->p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001092 if (begin_vaddr < min_vaddr) {
1093 min_vaddr = begin_vaddr;
1094 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001095 Elf_Addr end_vaddr = program_header->p_vaddr + program_header->p_memsz;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001096 if (end_vaddr > max_vaddr) {
1097 max_vaddr = end_vaddr;
1098 }
1099 }
1100 min_vaddr = RoundDown(min_vaddr, kPageSize);
1101 max_vaddr = RoundUp(max_vaddr, kPageSize);
1102 CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
1103 size_t loaded_size = max_vaddr - min_vaddr;
1104 return loaded_size;
1105}
1106
David Srbecky533c2072015-04-22 12:20:22 +01001107template <typename ElfTypes>
1108bool ElfFileImpl<ElfTypes>::Load(bool executable, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001109 CHECK(program_header_only_) << file_->GetPath();
Andreas Gampe91268c12014-04-03 17:50:24 -07001110
1111 if (executable) {
Andreas Gampe6f611412015-01-21 22:25:24 -08001112 InstructionSet elf_ISA = GetInstructionSetFromELF(GetHeader().e_machine, GetHeader().e_flags);
Andreas Gampe91268c12014-04-03 17:50:24 -07001113 if (elf_ISA != kRuntimeISA) {
1114 std::ostringstream oss;
1115 oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
1116 *error_msg = oss.str();
1117 return false;
1118 }
1119 }
1120
Jim_Guoa62a5882014-04-28 11:11:57 +08001121 bool reserved = false;
Tong Shen62d1ca32014-09-03 17:24:56 -07001122 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1123 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001124 if (program_header == nullptr) {
1125 *error_msg = StringPrintf("No program header for entry %d in ELF file %s.",
1126 i, file_->GetPath().c_str());
1127 return false;
1128 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001129
1130 // Record .dynamic header information for later use
Andreas Gampedaab38c2014-09-12 18:38:24 -07001131 if (program_header->p_type == PT_DYNAMIC) {
1132 dynamic_program_header_ = program_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001133 continue;
1134 }
1135
1136 // Not something to load, move on.
Andreas Gampedaab38c2014-09-12 18:38:24 -07001137 if (program_header->p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001138 continue;
1139 }
1140
1141 // Found something to load.
1142
Jim_Guoa62a5882014-04-28 11:11:57 +08001143 // Before load the actual segments, reserve a contiguous chunk
1144 // of required size and address for all segments, but with no
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001145 // permissions. We'll then carve that up with the proper
1146 // permissions as we load the actual segments. If p_vaddr is
1147 // non-zero, the segments require the specific address specified,
1148 // which either was specified in the file because we already set
1149 // base_address_ after the first zero segment).
Ian Rogerscdfcf372014-01-23 20:38:36 -08001150 int64_t temp_file_length = file_->GetLength();
1151 if (temp_file_length < 0) {
1152 errno = -temp_file_length;
1153 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
1154 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
1155 return false;
1156 }
1157 size_t file_length = static_cast<size_t>(temp_file_length);
Jim_Guoa62a5882014-04-28 11:11:57 +08001158 if (!reserved) {
Igor Murashkin46774762014-10-22 11:37:02 -07001159 uint8_t* reserve_base = reinterpret_cast<uint8_t*>(program_header->p_vaddr);
1160 uint8_t* reserve_base_override = reserve_base;
1161 // Override the base (e.g. when compiling with --compile-pic)
1162 if (requested_base_ != nullptr) {
1163 reserve_base_override = requested_base_;
1164 }
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001165 std::string reservation_name("ElfFile reservation for ");
1166 reservation_name += file_->GetPath();
Ian Rogers700a4022014-05-19 16:49:03 -07001167 std::unique_ptr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
Igor Murashkin46774762014-10-22 11:37:02 -07001168 reserve_base_override,
Vladimir Marko5c42c292015-02-25 12:02:49 +00001169 GetLoadedSize(), PROT_NONE, false, false,
Jim_Guoa62a5882014-04-28 11:11:57 +08001170 error_msg));
Brian Carlstromc1409452014-02-26 14:06:23 -08001171 if (reserve.get() == nullptr) {
1172 *error_msg = StringPrintf("Failed to allocate %s: %s",
1173 reservation_name.c_str(), error_msg->c_str());
1174 return false;
1175 }
Jim_Guoa62a5882014-04-28 11:11:57 +08001176 reserved = true;
Igor Murashkin46774762014-10-22 11:37:02 -07001177
1178 // Base address is the difference of actual mapped location and the p_vaddr
1179 base_address_ = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(reserve->Begin())
1180 - reinterpret_cast<uintptr_t>(reserve_base));
1181 // By adding the p_vaddr of a section/symbol to base_address_ we will always get the
1182 // dynamic memory address of where that object is actually mapped
1183 //
1184 // TODO: base_address_ needs to be calculated in ::Open, otherwise
1185 // FindDynamicSymbolAddress returns the wrong values until Load is called.
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001186 segments_.push_back(reserve.release());
1187 }
1188 // empty segment, nothing to map
Andreas Gampedaab38c2014-09-12 18:38:24 -07001189 if (program_header->p_memsz == 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001190 continue;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001191 }
Ian Rogers13735952014-10-08 12:43:28 -07001192 uint8_t* p_vaddr = base_address_ + program_header->p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001193 int prot = 0;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001194 if (executable && ((program_header->p_flags & PF_X) != 0)) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001195 prot |= PROT_EXEC;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001196 }
Andreas Gampedaab38c2014-09-12 18:38:24 -07001197 if ((program_header->p_flags & PF_W) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001198 prot |= PROT_WRITE;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001199 }
Andreas Gampedaab38c2014-09-12 18:38:24 -07001200 if ((program_header->p_flags & PF_R) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001201 prot |= PROT_READ;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001202 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -07001203 int flags = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001204 if (writable_) {
1205 prot |= PROT_WRITE;
1206 flags |= MAP_SHARED;
1207 } else {
1208 flags |= MAP_PRIVATE;
1209 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001210 if (program_header->p_filesz > program_header->p_memsz) {
1211 *error_msg = StringPrintf("Invalid p_filesz > p_memsz (%" PRIu64 " > %" PRIu64 "): %s",
1212 static_cast<uint64_t>(program_header->p_filesz),
1213 static_cast<uint64_t>(program_header->p_memsz),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001214 file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -07001215 return false;
1216 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001217 if (program_header->p_filesz < program_header->p_memsz &&
1218 !IsAligned<kPageSize>(program_header->p_filesz)) {
1219 *error_msg = StringPrintf("Unsupported unaligned p_filesz < p_memsz (%" PRIu64
1220 " < %" PRIu64 "): %s",
1221 static_cast<uint64_t>(program_header->p_filesz),
1222 static_cast<uint64_t>(program_header->p_memsz),
1223 file_->GetPath().c_str());
Brian Carlstromc1409452014-02-26 14:06:23 -08001224 return false;
1225 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001226 if (file_length < (program_header->p_offset + program_header->p_filesz)) {
1227 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
1228 "%d of %" PRIu64 " bytes: '%s'", file_length, i,
1229 static_cast<uint64_t>(program_header->p_offset + program_header->p_filesz),
1230 file_->GetPath().c_str());
Brian Carlstromc1409452014-02-26 14:06:23 -08001231 return false;
1232 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001233 if (program_header->p_filesz != 0u) {
1234 std::unique_ptr<MemMap> segment(
1235 MemMap::MapFileAtAddress(p_vaddr,
1236 program_header->p_filesz,
1237 prot, flags, file_->Fd(),
1238 program_header->p_offset,
1239 true, // implies MAP_FIXED
1240 file_->GetPath().c_str(),
1241 error_msg));
1242 if (segment.get() == nullptr) {
1243 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
1244 i, file_->GetPath().c_str(), error_msg->c_str());
1245 return false;
1246 }
1247 if (segment->Begin() != p_vaddr) {
1248 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
1249 "instead mapped to %p",
1250 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
1251 return false;
1252 }
1253 segments_.push_back(segment.release());
1254 }
1255 if (program_header->p_filesz < program_header->p_memsz) {
1256 std::string name = StringPrintf("Zero-initialized segment %" PRIu64 " of ELF file %s",
1257 static_cast<uint64_t>(i), file_->GetPath().c_str());
1258 std::unique_ptr<MemMap> segment(
1259 MemMap::MapAnonymous(name.c_str(),
1260 p_vaddr + program_header->p_filesz,
1261 program_header->p_memsz - program_header->p_filesz,
1262 prot, false, true /* reuse */, error_msg));
1263 if (segment == nullptr) {
1264 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s: %s",
1265 i, file_->GetPath().c_str(), error_msg->c_str());
1266 return false;
1267 }
1268 if (segment->Begin() != p_vaddr) {
1269 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s "
1270 "at expected address %p, instead mapped to %p",
1271 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
1272 return false;
1273 }
1274 segments_.push_back(segment.release());
1275 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001276 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001277
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001278 // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
Ian Rogers13735952014-10-08 12:43:28 -07001279 uint8_t* dsptr = base_address_ + GetDynamicProgramHeader().p_vaddr;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001280 if ((dsptr < Begin() || dsptr >= End()) && !ValidPointer(dsptr)) {
1281 *error_msg = StringPrintf("dynamic section address invalid in ELF file %s",
1282 file_->GetPath().c_str());
1283 return false;
1284 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001285 dynamic_section_start_ = reinterpret_cast<Elf_Dyn*>(dsptr);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001286
Tong Shen62d1ca32014-09-03 17:24:56 -07001287 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1288 Elf_Dyn& elf_dyn = GetDynamic(i);
Ian Rogers13735952014-10-08 12:43:28 -07001289 uint8_t* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001290 switch (elf_dyn.d_tag) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001291 case DT_HASH: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001292 if (!ValidPointer(d_ptr)) {
1293 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1294 d_ptr, file_->GetPath().c_str());
1295 return false;
1296 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001297 hash_section_start_ = reinterpret_cast<Elf_Word*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001298 break;
1299 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001300 case DT_STRTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001301 if (!ValidPointer(d_ptr)) {
1302 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1303 d_ptr, file_->GetPath().c_str());
1304 return false;
1305 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001306 dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
1307 break;
1308 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001309 case DT_SYMTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001310 if (!ValidPointer(d_ptr)) {
1311 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1312 d_ptr, file_->GetPath().c_str());
1313 return false;
1314 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001315 dynsym_section_start_ = reinterpret_cast<Elf_Sym*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001316 break;
1317 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001318 case DT_NULL: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001319 if (GetDynamicNum() != i+1) {
1320 *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
1321 "expected %d as implied by size of PT_DYNAMIC segment in %s",
1322 i + 1, GetDynamicNum(), file_->GetPath().c_str());
1323 return false;
1324 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001325 break;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001326 }
1327 }
1328 }
1329
Andreas Gampedaab38c2014-09-12 18:38:24 -07001330 // Check for the existence of some sections.
1331 if (!CheckSectionsExist(error_msg)) {
1332 return false;
1333 }
1334
Mark Mendellae9fd932014-02-10 16:14:35 -08001335 // Use GDB JIT support to do stack backtrace, etc.
1336 if (executable) {
1337 GdbJITSupport();
1338 }
1339
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001340 return true;
1341}
1342
David Srbecky533c2072015-04-22 12:20:22 +01001343template <typename ElfTypes>
1344bool ElfFileImpl<ElfTypes>::ValidPointer(const uint8_t* start) const {
Brian Carlstromc1409452014-02-26 14:06:23 -08001345 for (size_t i = 0; i < segments_.size(); ++i) {
1346 const MemMap* segment = segments_[i];
1347 if (segment->Begin() <= start && start < segment->End()) {
1348 return true;
1349 }
1350 }
1351 return false;
1352}
1353
Alex Light3470ab42014-06-18 10:35:45 -07001354
David Srbecky533c2072015-04-22 12:20:22 +01001355template <typename ElfTypes>
1356typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByName(
1357 const std::string& name) const {
Alex Light3470ab42014-06-18 10:35:45 -07001358 CHECK(!program_header_only_);
Tong Shen62d1ca32014-09-03 17:24:56 -07001359 Elf_Shdr* shstrtab_sec = GetSectionNameStringSection();
Andreas Gampedaab38c2014-09-12 18:38:24 -07001360 if (shstrtab_sec == nullptr) {
1361 return nullptr;
1362 }
Alex Light3470ab42014-06-18 10:35:45 -07001363 for (uint32_t i = 0; i < GetSectionHeaderNum(); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001364 Elf_Shdr* shdr = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001365 if (shdr == nullptr) {
1366 return nullptr;
1367 }
1368 const char* sec_name = GetString(*shstrtab_sec, shdr->sh_name);
Alex Light3470ab42014-06-18 10:35:45 -07001369 if (sec_name == nullptr) {
1370 continue;
1371 }
1372 if (name == sec_name) {
Andreas Gampedaab38c2014-09-12 18:38:24 -07001373 return shdr;
Alex Light3470ab42014-06-18 10:35:45 -07001374 }
1375 }
1376 return nullptr;
Mark Mendellae9fd932014-02-10 16:14:35 -08001377}
1378
David Srbecky533c2072015-04-22 12:20:22 +01001379template <typename ElfTypes>
1380bool ElfFileImpl<ElfTypes>::FixupDebugSections(typename std::make_signed<Elf_Off>::type base_address_delta) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001381 const Elf_Shdr* debug_info = FindSectionByName(".debug_info");
1382 const Elf_Shdr* debug_abbrev = FindSectionByName(".debug_abbrev");
Tong Shen62d1ca32014-09-03 17:24:56 -07001383 const Elf_Shdr* debug_str = FindSectionByName(".debug_str");
Tong Shen62d1ca32014-09-03 17:24:56 -07001384 const Elf_Shdr* strtab_sec = FindSectionByName(".strtab");
1385 const Elf_Shdr* symtab_sec = FindSectionByName(".symtab");
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001386
1387 if (debug_info == nullptr || debug_abbrev == nullptr ||
1388 debug_str == nullptr || strtab_sec == nullptr || symtab_sec == nullptr) {
1389 // Release version of ART does not generate debug info.
1390 return true;
1391 }
1392 if (base_address_delta == 0) {
1393 return true;
1394 }
David Srbecky2f6cdb02015-04-11 00:17:53 +01001395 if (!ApplyOatPatchesTo(".debug_info", base_address_delta)) {
1396 return false;
1397 }
1398 if (!ApplyOatPatchesTo(".debug_line", base_address_delta)) {
1399 return false;
1400 }
1401 return true;
1402}
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001403
David Srbecky533c2072015-04-22 12:20:22 +01001404template <typename ElfTypes>
1405bool ElfFileImpl<ElfTypes>::ApplyOatPatchesTo(
1406 const char* target_section_name,
1407 typename std::make_signed<Elf_Off>::type delta) {
David Srbecky2f6cdb02015-04-11 00:17:53 +01001408 auto patches_section = FindSectionByName(".oat_patches");
1409 if (patches_section == nullptr) {
1410 LOG(ERROR) << ".oat_patches section not found.";
Alex Light3470ab42014-06-18 10:35:45 -07001411 return false;
1412 }
David Srbecky2f6cdb02015-04-11 00:17:53 +01001413 if (patches_section->sh_type != SHT_OAT_PATCH) {
1414 LOG(ERROR) << "Unexpected type of .oat_patches.";
Alex Light3470ab42014-06-18 10:35:45 -07001415 return false;
1416 }
David Srbecky2f6cdb02015-04-11 00:17:53 +01001417 auto target_section = FindSectionByName(target_section_name);
1418 if (target_section == nullptr) {
1419 LOG(ERROR) << target_section_name << " section not found.";
1420 return false;
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001421 }
David Srbecky2f6cdb02015-04-11 00:17:53 +01001422 if (!ApplyOatPatches(
1423 Begin() + patches_section->sh_offset,
1424 Begin() + patches_section->sh_offset + patches_section->sh_size,
1425 target_section_name, delta,
1426 Begin() + target_section->sh_offset,
1427 Begin() + target_section->sh_offset + target_section->sh_size)) {
1428 LOG(ERROR) << target_section_name << " section not found in .oat_patches.";
1429 }
1430 return true;
1431}
1432
1433// Apply .oat_patches to given section.
David Srbecky533c2072015-04-22 12:20:22 +01001434template <typename ElfTypes>
1435bool ElfFileImpl<ElfTypes>::ApplyOatPatches(
1436 const uint8_t* patches, const uint8_t* patches_end,
1437 const char* target_section_name,
1438 typename std::make_signed<Elf_Off>::type delta,
1439 uint8_t* to_patch, const uint8_t* to_patch_end) {
David Srbecky2f6cdb02015-04-11 00:17:53 +01001440 // Read null-terminated section name.
1441 const char* section_name;
1442 while ((section_name = reinterpret_cast<const char*>(patches))[0] != '\0') {
1443 patches += strlen(section_name) + 1;
1444 uint32_t length = DecodeUnsignedLeb128(&patches);
1445 const uint8_t* next_section = patches + length;
1446 // Is it the section we want to patch?
1447 if (strcmp(section_name, target_section_name) == 0) {
1448 // Read LEB128 encoded list of advances.
1449 while (patches < next_section) {
1450 DCHECK_LT(patches, patches_end) << "Unexpected end of .oat_patches.";
1451 to_patch += DecodeUnsignedLeb128(&patches);
1452 DCHECK_LT(to_patch, to_patch_end) << "Patch past the end of " << section_name;
1453 // TODO: 32-bit vs 64-bit. What is the right type to use here?
1454 auto* patch_loc = reinterpret_cast<typename std::make_signed<Elf_Off>::type*>(to_patch);
1455 *patch_loc += delta;
1456 }
1457 return true;
1458 }
1459 patches = next_section;
1460 }
1461 return false;
Alex Light3470ab42014-06-18 10:35:45 -07001462}
Mark Mendellae9fd932014-02-10 16:14:35 -08001463
David Srbecky533c2072015-04-22 12:20:22 +01001464template <typename ElfTypes>
1465void ElfFileImpl<ElfTypes>::GdbJITSupport() {
Mark Mendellae9fd932014-02-10 16:14:35 -08001466 // We only get here if we only are mapping the program header.
1467 DCHECK(program_header_only_);
1468
1469 // Well, we need the whole file to do this.
1470 std::string error_msg;
Alex Light3470ab42014-06-18 10:35:45 -07001471 // Make it MAP_PRIVATE so we can just give it to gdb if all the necessary
1472 // sections are there.
David Srbecky533c2072015-04-22 12:20:22 +01001473 std::unique_ptr<ElfFileImpl<ElfTypes>> all_ptr(
1474 Open(const_cast<File*>(file_), PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
Alex Light3470ab42014-06-18 10:35:45 -07001475 if (all_ptr.get() == nullptr) {
Mark Mendellae9fd932014-02-10 16:14:35 -08001476 return;
1477 }
David Srbecky533c2072015-04-22 12:20:22 +01001478 ElfFileImpl<ElfTypes>& all = *all_ptr;
Alex Light3470ab42014-06-18 10:35:45 -07001479
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001480 // We need the eh_frame for gdb but debug info might be present without it.
Tong Shen62d1ca32014-09-03 17:24:56 -07001481 const Elf_Shdr* eh_frame = all.FindSectionByName(".eh_frame");
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001482 if (eh_frame == nullptr) {
Mark Mendellae9fd932014-02-10 16:14:35 -08001483 return;
1484 }
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001485
1486 // Do we have interesting sections?
Alex Light3470ab42014-06-18 10:35:45 -07001487 // We need to add in a strtab and symtab to the image.
1488 // all is MAP_PRIVATE so it can be written to freely.
1489 // We also already have strtab and symtab so we are fine there.
Tong Shen62d1ca32014-09-03 17:24:56 -07001490 Elf_Ehdr& elf_hdr = all.GetHeader();
Mark Mendellae9fd932014-02-10 16:14:35 -08001491 elf_hdr.e_entry = 0;
1492 elf_hdr.e_phoff = 0;
1493 elf_hdr.e_phnum = 0;
1494 elf_hdr.e_phentsize = 0;
1495 elf_hdr.e_type = ET_EXEC;
1496
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001497 // Since base_address_ is 0 if we are actually loaded at a known address (i.e. this is boot.oat)
1498 // and the actual address stuff starts at in regular files this is good.
1499 if (!all.FixupDebugSections(reinterpret_cast<intptr_t>(base_address_))) {
Alex Light3470ab42014-06-18 10:35:45 -07001500 LOG(ERROR) << "Failed to load GDB data";
1501 return;
Mark Mendellae9fd932014-02-10 16:14:35 -08001502 }
1503
Alex Light3470ab42014-06-18 10:35:45 -07001504 jit_gdb_entry_ = CreateCodeEntry(all.Begin(), all.Size());
1505 gdb_file_mapping_.reset(all_ptr.release());
Mark Mendellae9fd932014-02-10 16:14:35 -08001506}
1507
David Srbecky533c2072015-04-22 12:20:22 +01001508template <typename ElfTypes>
1509bool ElfFileImpl<ElfTypes>::Strip(std::string* error_msg) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001510 // ELF files produced by MCLinker look roughly like this
1511 //
1512 // +------------+
1513 // | Elf_Ehdr | contains number of Elf_Shdr and offset to first
1514 // +------------+
1515 // | Elf_Phdr | program headers
1516 // | Elf_Phdr |
1517 // | ... |
1518 // | Elf_Phdr |
1519 // +------------+
1520 // | section | mixture of needed and unneeded sections
1521 // +------------+
1522 // | section |
1523 // +------------+
1524 // | ... |
1525 // +------------+
1526 // | section |
1527 // +------------+
1528 // | Elf_Shdr | section headers
1529 // | Elf_Shdr |
1530 // | ... | contains offset to section start
1531 // | Elf_Shdr |
1532 // +------------+
1533 //
1534 // To strip:
1535 // - leave the Elf_Ehdr and Elf_Phdr values in place.
1536 // - walk the sections making a new set of Elf_Shdr section headers for what we want to keep
1537 // - move the sections are keeping up to fill in gaps of sections we want to strip
1538 // - write new Elf_Shdr section headers to end of file, updating Elf_Ehdr
1539 // - truncate rest of file
1540 //
1541
1542 std::vector<Elf_Shdr> section_headers;
1543 std::vector<Elf_Word> section_headers_original_indexes;
1544 section_headers.reserve(GetSectionHeaderNum());
1545
1546
1547 Elf_Shdr* string_section = GetSectionNameStringSection();
1548 CHECK(string_section != nullptr);
1549 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1550 Elf_Shdr* sh = GetSectionHeader(i);
1551 CHECK(sh != nullptr);
1552 const char* name = GetString(*string_section, sh->sh_name);
1553 if (name == nullptr) {
1554 CHECK_EQ(0U, i);
1555 section_headers.push_back(*sh);
1556 section_headers_original_indexes.push_back(0);
1557 continue;
1558 }
1559 if (StartsWith(name, ".debug")
1560 || (strcmp(name, ".strtab") == 0)
1561 || (strcmp(name, ".symtab") == 0)) {
1562 continue;
1563 }
1564 section_headers.push_back(*sh);
1565 section_headers_original_indexes.push_back(i);
1566 }
1567 CHECK_NE(0U, section_headers.size());
1568 CHECK_EQ(section_headers.size(), section_headers_original_indexes.size());
1569
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001570 // section 0 is the null section, sections start at offset of first section
Tong Shen62d1ca32014-09-03 17:24:56 -07001571 CHECK(GetSectionHeader(1) != nullptr);
1572 Elf_Off offset = GetSectionHeader(1)->sh_offset;
1573 for (size_t i = 1; i < section_headers.size(); i++) {
1574 Elf_Shdr& new_sh = section_headers[i];
1575 Elf_Shdr* old_sh = GetSectionHeader(section_headers_original_indexes[i]);
1576 CHECK(old_sh != nullptr);
1577 CHECK_EQ(new_sh.sh_name, old_sh->sh_name);
1578 if (old_sh->sh_addralign > 1) {
1579 offset = RoundUp(offset, old_sh->sh_addralign);
1580 }
1581 if (old_sh->sh_offset == offset) {
1582 // already in place
1583 offset += old_sh->sh_size;
1584 continue;
1585 }
1586 // shift section earlier
1587 memmove(Begin() + offset,
1588 Begin() + old_sh->sh_offset,
1589 old_sh->sh_size);
1590 new_sh.sh_offset = offset;
1591 offset += old_sh->sh_size;
1592 }
1593
1594 Elf_Off shoff = offset;
1595 size_t section_headers_size_in_bytes = section_headers.size() * sizeof(Elf_Shdr);
1596 memcpy(Begin() + offset, &section_headers[0], section_headers_size_in_bytes);
1597 offset += section_headers_size_in_bytes;
1598
1599 GetHeader().e_shnum = section_headers.size();
1600 GetHeader().e_shoff = shoff;
1601 int result = ftruncate(file_->Fd(), offset);
1602 if (result != 0) {
1603 *error_msg = StringPrintf("Failed to truncate while stripping ELF file: '%s': %s",
1604 file_->GetPath().c_str(), strerror(errno));
1605 return false;
1606 }
1607 return true;
1608}
1609
1610static const bool DEBUG_FIXUP = false;
1611
David Srbecky533c2072015-04-22 12:20:22 +01001612template <typename ElfTypes>
1613bool ElfFileImpl<ElfTypes>::Fixup(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001614 if (!FixupDynamic(base_address)) {
1615 LOG(WARNING) << "Failed to fixup .dynamic in " << file_->GetPath();
1616 return false;
1617 }
1618 if (!FixupSectionHeaders(base_address)) {
1619 LOG(WARNING) << "Failed to fixup section headers in " << file_->GetPath();
1620 return false;
1621 }
1622 if (!FixupProgramHeaders(base_address)) {
1623 LOG(WARNING) << "Failed to fixup program headers in " << file_->GetPath();
1624 return false;
1625 }
1626 if (!FixupSymbols(base_address, true)) {
1627 LOG(WARNING) << "Failed to fixup .dynsym in " << file_->GetPath();
1628 return false;
1629 }
1630 if (!FixupSymbols(base_address, false)) {
1631 LOG(WARNING) << "Failed to fixup .symtab in " << file_->GetPath();
1632 return false;
1633 }
1634 if (!FixupRelocations(base_address)) {
1635 LOG(WARNING) << "Failed to fixup .rel.dyn in " << file_->GetPath();
1636 return false;
1637 }
Andreas Gampe3c54b002015-04-07 16:09:30 -07001638 static_assert(sizeof(Elf_Off) >= sizeof(base_address), "Potentially losing precision.");
1639 if (!FixupDebugSections(static_cast<Elf_Off>(base_address))) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001640 LOG(WARNING) << "Failed to fixup debug sections in " << file_->GetPath();
1641 return false;
1642 }
1643 return true;
1644}
1645
David Srbecky533c2072015-04-22 12:20:22 +01001646template <typename ElfTypes>
1647bool ElfFileImpl<ElfTypes>::FixupDynamic(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001648 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1649 Elf_Dyn& elf_dyn = GetDynamic(i);
1650 Elf_Word d_tag = elf_dyn.d_tag;
1651 if (IsDynamicSectionPointer(d_tag, GetHeader().e_machine)) {
1652 Elf_Addr d_ptr = elf_dyn.d_un.d_ptr;
1653 if (DEBUG_FIXUP) {
1654 LOG(INFO) << StringPrintf("In %s moving Elf_Dyn[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1655 GetFile().GetPath().c_str(), i,
1656 static_cast<uint64_t>(d_ptr),
1657 static_cast<uint64_t>(d_ptr + base_address));
1658 }
1659 d_ptr += base_address;
1660 elf_dyn.d_un.d_ptr = d_ptr;
1661 }
1662 }
1663 return true;
1664}
1665
David Srbecky533c2072015-04-22 12:20:22 +01001666template <typename ElfTypes>
1667bool ElfFileImpl<ElfTypes>::FixupSectionHeaders(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001668 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1669 Elf_Shdr* sh = GetSectionHeader(i);
1670 CHECK(sh != nullptr);
1671 // 0 implies that the section will not exist in the memory of the process
1672 if (sh->sh_addr == 0) {
1673 continue;
1674 }
1675 if (DEBUG_FIXUP) {
1676 LOG(INFO) << StringPrintf("In %s moving Elf_Shdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1677 GetFile().GetPath().c_str(), i,
1678 static_cast<uint64_t>(sh->sh_addr),
1679 static_cast<uint64_t>(sh->sh_addr + base_address));
1680 }
1681 sh->sh_addr += base_address;
1682 }
1683 return true;
1684}
1685
David Srbecky533c2072015-04-22 12:20:22 +01001686template <typename ElfTypes>
1687bool ElfFileImpl<ElfTypes>::FixupProgramHeaders(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001688 // TODO: ELFObjectFile doesn't have give to Elf_Phdr, so we do that ourselves for now.
1689 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1690 Elf_Phdr* ph = GetProgramHeader(i);
1691 CHECK(ph != nullptr);
1692 CHECK_EQ(ph->p_vaddr, ph->p_paddr) << GetFile().GetPath() << " i=" << i;
1693 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1694 << GetFile().GetPath() << " i=" << i;
1695 if (DEBUG_FIXUP) {
1696 LOG(INFO) << StringPrintf("In %s moving Elf_Phdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1697 GetFile().GetPath().c_str(), i,
1698 static_cast<uint64_t>(ph->p_vaddr),
1699 static_cast<uint64_t>(ph->p_vaddr + base_address));
1700 }
1701 ph->p_vaddr += base_address;
1702 ph->p_paddr += base_address;
1703 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1704 << GetFile().GetPath() << " i=" << i;
1705 }
1706 return true;
1707}
1708
David Srbecky533c2072015-04-22 12:20:22 +01001709template <typename ElfTypes>
1710bool ElfFileImpl<ElfTypes>::FixupSymbols(Elf_Addr base_address, bool dynamic) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001711 Elf_Word section_type = dynamic ? SHT_DYNSYM : SHT_SYMTAB;
1712 // TODO: Unfortunate ELFObjectFile has protected symbol access, so use ElfFile
1713 Elf_Shdr* symbol_section = FindSectionByType(section_type);
1714 if (symbol_section == nullptr) {
1715 // file is missing optional .symtab
1716 CHECK(!dynamic) << GetFile().GetPath();
1717 return true;
1718 }
1719 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
1720 Elf_Sym* symbol = GetSymbol(section_type, i);
1721 CHECK(symbol != nullptr);
1722 if (symbol->st_value != 0) {
1723 if (DEBUG_FIXUP) {
1724 LOG(INFO) << StringPrintf("In %s moving Elf_Sym[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1725 GetFile().GetPath().c_str(), i,
1726 static_cast<uint64_t>(symbol->st_value),
1727 static_cast<uint64_t>(symbol->st_value + base_address));
1728 }
1729 symbol->st_value += base_address;
1730 }
1731 }
1732 return true;
1733}
1734
David Srbecky533c2072015-04-22 12:20:22 +01001735template <typename ElfTypes>
1736bool ElfFileImpl<ElfTypes>::FixupRelocations(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001737 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1738 Elf_Shdr* sh = GetSectionHeader(i);
1739 CHECK(sh != nullptr);
1740 if (sh->sh_type == SHT_REL) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001741 for (uint32_t j = 0; j < GetRelNum(*sh); j++) {
1742 Elf_Rel& rel = GetRel(*sh, j);
Tong Shen62d1ca32014-09-03 17:24:56 -07001743 if (DEBUG_FIXUP) {
1744 LOG(INFO) << StringPrintf("In %s moving Elf_Rel[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001745 GetFile().GetPath().c_str(), j,
Tong Shen62d1ca32014-09-03 17:24:56 -07001746 static_cast<uint64_t>(rel.r_offset),
1747 static_cast<uint64_t>(rel.r_offset + base_address));
1748 }
1749 rel.r_offset += base_address;
1750 }
1751 } else if (sh->sh_type == SHT_RELA) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001752 for (uint32_t j = 0; j < GetRelaNum(*sh); j++) {
1753 Elf_Rela& rela = GetRela(*sh, j);
Tong Shen62d1ca32014-09-03 17:24:56 -07001754 if (DEBUG_FIXUP) {
1755 LOG(INFO) << StringPrintf("In %s moving Elf_Rela[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001756 GetFile().GetPath().c_str(), j,
Tong Shen62d1ca32014-09-03 17:24:56 -07001757 static_cast<uint64_t>(rela.r_offset),
1758 static_cast<uint64_t>(rela.r_offset + base_address));
1759 }
1760 rela.r_offset += base_address;
1761 }
1762 }
1763 }
1764 return true;
1765}
1766
1767// Explicit instantiations
David Srbecky533c2072015-04-22 12:20:22 +01001768template class ElfFileImpl<ElfTypes32>;
1769template class ElfFileImpl<ElfTypes64>;
Tong Shen62d1ca32014-09-03 17:24:56 -07001770
Ian Rogersd4c4d952014-10-16 20:31:53 -07001771ElfFile::ElfFile(ElfFileImpl32* elf32) : elf32_(elf32), elf64_(nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001772}
1773
Ian Rogersd4c4d952014-10-16 20:31:53 -07001774ElfFile::ElfFile(ElfFileImpl64* elf64) : elf32_(nullptr), elf64_(elf64) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001775}
1776
1777ElfFile::~ElfFile() {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001778 // Should never have 32 and 64-bit impls.
1779 CHECK_NE(elf32_.get() == nullptr, elf64_.get() == nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -07001780}
1781
Igor Murashkin46774762014-10-22 11:37:02 -07001782ElfFile* ElfFile::Open(File* file, bool writable, bool program_header_only, std::string* error_msg,
1783 uint8_t* requested_base) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001784 if (file->GetLength() < EI_NIDENT) {
1785 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1786 file->GetPath().c_str());
1787 return nullptr;
1788 }
1789 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT, PROT_READ, MAP_PRIVATE, file->Fd(), 0,
1790 file->GetPath().c_str(), error_msg));
1791 if (map == nullptr && map->Size() != EI_NIDENT) {
1792 return nullptr;
1793 }
Ian Rogers13735952014-10-08 12:43:28 -07001794 uint8_t* header = map->Begin();
Tong Shen62d1ca32014-09-03 17:24:56 -07001795 if (header[EI_CLASS] == ELFCLASS64) {
Igor Murashkin46774762014-10-22 11:37:02 -07001796 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file, writable, program_header_only,
1797 error_msg, requested_base);
Tong Shen62d1ca32014-09-03 17:24:56 -07001798 if (elf_file_impl == nullptr)
1799 return nullptr;
1800 return new ElfFile(elf_file_impl);
1801 } else if (header[EI_CLASS] == ELFCLASS32) {
Igor Murashkin46774762014-10-22 11:37:02 -07001802 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file, writable, program_header_only,
1803 error_msg, requested_base);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001804 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001805 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001806 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001807 return new ElfFile(elf_file_impl);
1808 } else {
1809 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1810 ELFCLASS32, ELFCLASS64,
1811 file->GetPath().c_str(),
1812 header[EI_CLASS]);
1813 return nullptr;
1814 }
1815}
1816
1817ElfFile* ElfFile::Open(File* file, int mmap_prot, int mmap_flags, std::string* error_msg) {
1818 if (file->GetLength() < EI_NIDENT) {
1819 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1820 file->GetPath().c_str());
1821 return nullptr;
1822 }
1823 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT, PROT_READ, MAP_PRIVATE, file->Fd(), 0,
1824 file->GetPath().c_str(), error_msg));
1825 if (map == nullptr && map->Size() != EI_NIDENT) {
1826 return nullptr;
1827 }
Ian Rogers13735952014-10-08 12:43:28 -07001828 uint8_t* header = map->Begin();
Tong Shen62d1ca32014-09-03 17:24:56 -07001829 if (header[EI_CLASS] == ELFCLASS64) {
1830 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file, mmap_prot, mmap_flags, error_msg);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001831 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001832 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001833 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001834 return new ElfFile(elf_file_impl);
1835 } else if (header[EI_CLASS] == ELFCLASS32) {
1836 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file, mmap_prot, mmap_flags, error_msg);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001837 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001838 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001839 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001840 return new ElfFile(elf_file_impl);
1841 } else {
1842 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1843 ELFCLASS32, ELFCLASS64,
1844 file->GetPath().c_str(),
1845 header[EI_CLASS]);
1846 return nullptr;
1847 }
1848}
1849
1850#define DELEGATE_TO_IMPL(func, ...) \
Ian Rogersd4c4d952014-10-16 20:31:53 -07001851 if (elf64_.get() != nullptr) { \
1852 return elf64_->func(__VA_ARGS__); \
Tong Shen62d1ca32014-09-03 17:24:56 -07001853 } else { \
Ian Rogersd4c4d952014-10-16 20:31:53 -07001854 DCHECK(elf32_.get() != nullptr); \
1855 return elf32_->func(__VA_ARGS__); \
Tong Shen62d1ca32014-09-03 17:24:56 -07001856 }
1857
1858bool ElfFile::Load(bool executable, std::string* error_msg) {
1859 DELEGATE_TO_IMPL(Load, executable, error_msg);
1860}
1861
Ian Rogers13735952014-10-08 12:43:28 -07001862const uint8_t* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001863 DELEGATE_TO_IMPL(FindDynamicSymbolAddress, symbol_name);
1864}
1865
1866size_t ElfFile::Size() const {
1867 DELEGATE_TO_IMPL(Size);
1868}
1869
Ian Rogers13735952014-10-08 12:43:28 -07001870uint8_t* ElfFile::Begin() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001871 DELEGATE_TO_IMPL(Begin);
1872}
1873
Ian Rogers13735952014-10-08 12:43:28 -07001874uint8_t* ElfFile::End() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001875 DELEGATE_TO_IMPL(End);
1876}
1877
1878const File& ElfFile::GetFile() const {
1879 DELEGATE_TO_IMPL(GetFile);
1880}
1881
1882bool ElfFile::GetSectionOffsetAndSize(const char* section_name, uint64_t* offset, uint64_t* size) {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001883 if (elf32_.get() == nullptr) {
1884 CHECK(elf64_.get() != nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -07001885
Ian Rogersd4c4d952014-10-16 20:31:53 -07001886 Elf64_Shdr *shdr = elf64_->FindSectionByName(section_name);
1887 if (shdr == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001888 return false;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001889 }
1890 if (offset != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001891 *offset = shdr->sh_offset;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001892 }
1893 if (size != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001894 *size = shdr->sh_size;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001895 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001896 return true;
1897 } else {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001898 Elf32_Shdr *shdr = elf32_->FindSectionByName(section_name);
1899 if (shdr == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001900 return false;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001901 }
1902 if (offset != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001903 *offset = shdr->sh_offset;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001904 }
1905 if (size != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001906 *size = shdr->sh_size;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001907 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001908 return true;
1909 }
1910}
1911
1912uint64_t ElfFile::FindSymbolAddress(unsigned section_type,
1913 const std::string& symbol_name,
1914 bool build_map) {
1915 DELEGATE_TO_IMPL(FindSymbolAddress, section_type, symbol_name, build_map);
1916}
1917
1918size_t ElfFile::GetLoadedSize() const {
1919 DELEGATE_TO_IMPL(GetLoadedSize);
1920}
1921
1922bool ElfFile::Strip(File* file, std::string* error_msg) {
1923 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file, true, false, error_msg));
1924 if (elf_file.get() == nullptr) {
1925 return false;
1926 }
1927
Ian Rogersd4c4d952014-10-16 20:31:53 -07001928 if (elf_file->elf64_.get() != nullptr)
1929 return elf_file->elf64_->Strip(error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001930 else
Ian Rogersd4c4d952014-10-16 20:31:53 -07001931 return elf_file->elf32_->Strip(error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001932}
1933
Andreas Gampe3c54b002015-04-07 16:09:30 -07001934bool ElfFile::Fixup(uint64_t base_address) {
1935 if (elf64_.get() != nullptr) {
1936 return elf64_->Fixup(static_cast<Elf64_Addr>(base_address));
1937 } else {
1938 DCHECK(elf32_.get() != nullptr);
1939 CHECK(IsUint<32>(base_address)) << std::hex << base_address;
1940 return elf32_->Fixup(static_cast<Elf32_Addr>(base_address));
1941 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001942 DELEGATE_TO_IMPL(Fixup, base_address);
1943}
1944
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001945} // namespace art