blob: 0df8211c57f74ea866ff7b0e9be1a9b33cd2452c [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
Nicolas Geoffraya7f198c2014-03-10 11:12:54 +000019#include <sys/types.h>
20#include <unistd.h>
21
Brian Carlstrom700c8d32012-11-05 10:42:02 -080022#include "base/logging.h"
Ian Rogers576ca0c2014-06-06 15:58:22 -070023#include "base/stringprintf.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080024#include "base/stl_util.h"
25#include "utils.h"
Andreas Gampe91268c12014-04-03 17:50:24 -070026#include "instruction_set.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080027
28namespace art {
29
Mark Mendellae9fd932014-02-10 16:14:35 -080030// -------------------------------------------------------------------
31// Binary GDB JIT Interface as described in
32// http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
33extern "C" {
34 typedef enum {
35 JIT_NOACTION = 0,
36 JIT_REGISTER_FN,
37 JIT_UNREGISTER_FN
38 } JITAction;
39
40 struct JITCodeEntry {
41 JITCodeEntry* next_;
42 JITCodeEntry* prev_;
43 const byte *symfile_addr_;
44 uint64_t symfile_size_;
45 };
46
47 struct JITDescriptor {
48 uint32_t version_;
49 uint32_t action_flag_;
50 JITCodeEntry* relevant_entry_;
51 JITCodeEntry* first_entry_;
52 };
53
54 // GDB will place breakpoint into this function.
55 // To prevent GCC from inlining or removing it we place noinline attribute
56 // and inline assembler statement inside.
57 void __attribute__((noinline)) __jit_debug_register_code() {
58 __asm__("");
59 }
60
61 // GDB will inspect contents of this descriptor.
62 // Static initialization is necessary to prevent GDB from seeing
63 // uninitialized descriptor.
64 JITDescriptor __jit_debug_descriptor = { 1, JIT_NOACTION, nullptr, nullptr };
65}
66
67
68static JITCodeEntry* CreateCodeEntry(const byte *symfile_addr,
69 uintptr_t symfile_size) {
70 JITCodeEntry* entry = new JITCodeEntry;
71 entry->symfile_addr_ = symfile_addr;
72 entry->symfile_size_ = symfile_size;
73 entry->prev_ = nullptr;
74
75 // TODO: Do we need a lock here?
76 entry->next_ = __jit_debug_descriptor.first_entry_;
77 if (entry->next_ != nullptr) {
78 entry->next_->prev_ = entry;
79 }
80 __jit_debug_descriptor.first_entry_ = entry;
81 __jit_debug_descriptor.relevant_entry_ = entry;
82
83 __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
84 __jit_debug_register_code();
85 return entry;
86}
87
88
89static void UnregisterCodeEntry(JITCodeEntry* entry) {
90 // TODO: Do we need a lock here?
91 if (entry->prev_ != nullptr) {
92 entry->prev_->next_ = entry->next_;
93 } else {
94 __jit_debug_descriptor.first_entry_ = entry->next_;
95 }
96
97 if (entry->next_ != nullptr) {
98 entry->next_->prev_ = entry->prev_;
99 }
100
101 __jit_debug_descriptor.relevant_entry_ = entry;
102 __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
103 __jit_debug_register_code();
104 delete entry;
105}
106
Brian Carlstromc1409452014-02-26 14:06:23 -0800107ElfFile::ElfFile(File* file, bool writable, bool program_header_only)
108 : file_(file),
109 writable_(writable),
110 program_header_only_(program_header_only),
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700111 header_(NULL),
112 base_address_(NULL),
113 program_headers_start_(NULL),
114 section_headers_start_(NULL),
115 dynamic_program_header_(NULL),
116 dynamic_section_start_(NULL),
117 symtab_section_start_(NULL),
118 dynsym_section_start_(NULL),
119 strtab_section_start_(NULL),
120 dynstr_section_start_(NULL),
121 hash_section_start_(NULL),
122 symtab_symbol_table_(NULL),
Mark Mendellae9fd932014-02-10 16:14:35 -0800123 dynsym_symbol_table_(NULL),
124 jit_elf_image_(NULL),
125 jit_gdb_entry_(NULL) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800126 CHECK(file != NULL);
127}
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800128
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700129ElfFile* ElfFile::Open(File* file, bool writable, bool program_header_only,
130 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700131 std::unique_ptr<ElfFile> elf_file(new ElfFile(file, writable, program_header_only));
Brian Carlstromc1409452014-02-26 14:06:23 -0800132 if (!elf_file->Setup(error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700133 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800134 }
135 return elf_file.release();
136}
137
Brian Carlstromc1409452014-02-26 14:06:23 -0800138bool ElfFile::Setup(std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800139 int prot;
140 int flags;
141 if (writable_) {
142 prot = PROT_READ | PROT_WRITE;
143 flags = MAP_SHARED;
144 } else {
145 prot = PROT_READ;
146 flags = MAP_PRIVATE;
147 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800148 int64_t temp_file_length = file_->GetLength();
149 if (temp_file_length < 0) {
150 errno = -temp_file_length;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700151 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
152 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800153 return false;
154 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800155 size_t file_length = static_cast<size_t>(temp_file_length);
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000156 if (file_length < sizeof(Elf32_Ehdr)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800157 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000158 "%zd bytes: '%s'", file_length, sizeof(Elf32_Ehdr),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700159 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800160 return false;
161 }
162
Brian Carlstromc1409452014-02-26 14:06:23 -0800163 if (program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800164 // first just map ELF header to get program header size information
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000165 size_t elf_header_size = sizeof(Elf32_Ehdr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700166 if (!SetMap(MemMap::MapFile(elf_header_size, prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800167 file_->GetPath().c_str(), error_msg),
168 error_msg)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800169 return false;
170 }
171 // then remap to cover program header
172 size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
Brian Carlstrom3a223612013-10-10 17:18:24 -0700173 if (file_length < program_header_size) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800174 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700175 "header of %zd bytes: '%s'", file_length,
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000176 sizeof(Elf32_Ehdr), file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700177 return false;
178 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700179 if (!SetMap(MemMap::MapFile(program_header_size, prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800180 file_->GetPath().c_str(), error_msg),
181 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700182 *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800183 return false;
184 }
185 } else {
186 // otherwise map entire file
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700187 if (!SetMap(MemMap::MapFile(file_->GetLength(), prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800188 file_->GetPath().c_str(), error_msg),
189 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700190 *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800191 return false;
192 }
193 }
194
195 // Either way, the program header is relative to the elf header
196 program_headers_start_ = Begin() + GetHeader().e_phoff;
197
Brian Carlstromc1409452014-02-26 14:06:23 -0800198 if (!program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800199 // Setup section headers.
200 section_headers_start_ = Begin() + GetHeader().e_shoff;
201
202 // Find .dynamic section info from program header
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000203 dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800204 if (dynamic_program_header_ == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700205 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
206 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800207 return false;
208 }
209
210 dynamic_section_start_
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000211 = reinterpret_cast<Elf32_Dyn*>(Begin() + GetDynamicProgramHeader().p_offset);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800212
213 // Find other sections from section headers
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000214 for (Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
215 Elf32_Shdr& section_header = GetSectionHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800216 byte* section_addr = Begin() + section_header.sh_offset;
217 switch (section_header.sh_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000218 case SHT_SYMTAB: {
219 symtab_section_start_ = reinterpret_cast<Elf32_Sym*>(section_addr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800220 break;
221 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000222 case SHT_DYNSYM: {
223 dynsym_section_start_ = reinterpret_cast<Elf32_Sym*>(section_addr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800224 break;
225 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000226 case SHT_STRTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800227 // TODO: base these off of sh_link from .symtab and .dynsym above
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000228 if ((section_header.sh_flags & SHF_ALLOC) != 0) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800229 dynstr_section_start_ = reinterpret_cast<char*>(section_addr);
230 } else {
231 strtab_section_start_ = reinterpret_cast<char*>(section_addr);
232 }
233 break;
234 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000235 case SHT_DYNAMIC: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800236 if (reinterpret_cast<byte*>(dynamic_section_start_) != section_addr) {
237 LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
Brian Carlstrom265091e2013-01-30 14:08:26 -0800238 << file_->GetPath() << ": " << std::hex
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800239 << reinterpret_cast<void*>(dynamic_section_start_)
240 << " != " << reinterpret_cast<void*>(section_addr);
241 return false;
242 }
243 break;
244 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000245 case SHT_HASH: {
246 hash_section_start_ = reinterpret_cast<Elf32_Word*>(section_addr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800247 break;
248 }
249 }
250 }
251 }
252 return true;
253}
254
255ElfFile::~ElfFile() {
256 STLDeleteElements(&segments_);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800257 delete symtab_symbol_table_;
258 delete dynsym_symbol_table_;
Mark Mendellae9fd932014-02-10 16:14:35 -0800259 delete jit_elf_image_;
260 if (jit_gdb_entry_) {
261 UnregisterCodeEntry(jit_gdb_entry_);
262 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800263}
264
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800265bool ElfFile::SetMap(MemMap* map, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800266 if (map == NULL) {
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800267 // MemMap::Open should have already set an error.
268 DCHECK(!error_msg->empty());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800269 return false;
270 }
271 map_.reset(map);
272 CHECK(map_.get() != NULL) << file_->GetPath();
273 CHECK(map_->Begin() != NULL) << file_->GetPath();
274
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000275 header_ = reinterpret_cast<Elf32_Ehdr*>(map_->Begin());
276 if ((ELFMAG0 != header_->e_ident[EI_MAG0])
277 || (ELFMAG1 != header_->e_ident[EI_MAG1])
278 || (ELFMAG2 != header_->e_ident[EI_MAG2])
279 || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800280 *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
281 ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800282 file_->GetPath().c_str(),
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000283 header_->e_ident[EI_MAG0],
284 header_->e_ident[EI_MAG1],
285 header_->e_ident[EI_MAG2],
286 header_->e_ident[EI_MAG3]);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800287 return false;
288 }
Brian Carlstromc1409452014-02-26 14:06:23 -0800289 if (ELFCLASS32 != header_->e_ident[EI_CLASS]) {
290 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
291 ELFCLASS32,
292 file_->GetPath().c_str(),
293 header_->e_ident[EI_CLASS]);
294 return false;
295 }
296 if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
297 *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
298 ELFDATA2LSB,
299 file_->GetPath().c_str(),
300 header_->e_ident[EI_CLASS]);
301 return false;
302 }
303 if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
304 *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
305 EV_CURRENT,
306 file_->GetPath().c_str(),
307 header_->e_ident[EI_CLASS]);
308 return false;
309 }
310 if (ET_DYN != header_->e_type) {
311 *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
312 ET_DYN,
313 file_->GetPath().c_str(),
314 header_->e_type);
315 return false;
316 }
317 if (EV_CURRENT != header_->e_version) {
318 *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
319 EV_CURRENT,
320 file_->GetPath().c_str(),
321 header_->e_version);
322 return false;
323 }
324 if (0 != header_->e_entry) {
325 *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
326 0,
327 file_->GetPath().c_str(),
328 header_->e_entry);
329 return false;
330 }
331 if (0 == header_->e_phoff) {
332 *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
333 file_->GetPath().c_str());
334 return false;
335 }
336 if (0 == header_->e_shoff) {
337 *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
338 file_->GetPath().c_str());
339 return false;
340 }
341 if (0 == header_->e_ehsize) {
342 *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
343 file_->GetPath().c_str());
344 return false;
345 }
346 if (0 == header_->e_phentsize) {
347 *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
348 file_->GetPath().c_str());
349 return false;
350 }
351 if (0 == header_->e_phnum) {
352 *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
353 file_->GetPath().c_str());
354 return false;
355 }
356 if (0 == header_->e_shentsize) {
357 *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
358 file_->GetPath().c_str());
359 return false;
360 }
361 if (0 == header_->e_shnum) {
362 *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
363 file_->GetPath().c_str());
364 return false;
365 }
366 if (0 == header_->e_shstrndx) {
367 *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
368 file_->GetPath().c_str());
369 return false;
370 }
371 if (header_->e_shstrndx >= header_->e_shnum) {
372 *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
373 header_->e_shstrndx,
374 header_->e_shnum,
375 file_->GetPath().c_str());
376 return false;
377 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800378
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800379 if (!program_header_only_) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800380 if (header_->e_phoff >= Size()) {
Dmitry Petrochenko659d87d2014-02-27 14:23:11 +0700381 *error_msg = StringPrintf("Failed to find e_phoff value %d less than %zd in %s",
Brian Carlstromc1409452014-02-26 14:06:23 -0800382 header_->e_phoff,
383 Size(),
384 file_->GetPath().c_str());
385 return false;
386 }
387 if (header_->e_shoff >= Size()) {
Dmitry Petrochenko659d87d2014-02-27 14:23:11 +0700388 *error_msg = StringPrintf("Failed to find e_shoff value %d less than %zd in %s",
Brian Carlstromc1409452014-02-26 14:06:23 -0800389 header_->e_shoff,
390 Size(),
391 file_->GetPath().c_str());
392 return false;
393 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800394 }
395 return true;
396}
397
398
Brian Carlstromc1409452014-02-26 14:06:23 -0800399Elf32_Ehdr& ElfFile::GetHeader() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800400 CHECK(header_ != NULL);
401 return *header_;
402}
403
Brian Carlstromc1409452014-02-26 14:06:23 -0800404byte* ElfFile::GetProgramHeadersStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800405 CHECK(program_headers_start_ != NULL);
406 return program_headers_start_;
407}
408
Brian Carlstromc1409452014-02-26 14:06:23 -0800409byte* ElfFile::GetSectionHeadersStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800410 CHECK(section_headers_start_ != NULL);
411 return section_headers_start_;
412}
413
Brian Carlstromc1409452014-02-26 14:06:23 -0800414Elf32_Phdr& ElfFile::GetDynamicProgramHeader() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800415 CHECK(dynamic_program_header_ != NULL);
416 return *dynamic_program_header_;
417}
418
Brian Carlstromc1409452014-02-26 14:06:23 -0800419Elf32_Dyn* ElfFile::GetDynamicSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800420 CHECK(dynamic_section_start_ != NULL);
421 return dynamic_section_start_;
422}
423
Brian Carlstromc1409452014-02-26 14:06:23 -0800424Elf32_Sym* ElfFile::GetSymbolSectionStart(Elf32_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800425 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000426 Elf32_Sym* symbol_section_start;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800427 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000428 case SHT_SYMTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800429 symbol_section_start = symtab_section_start_;
430 break;
431 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000432 case SHT_DYNSYM: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800433 symbol_section_start = dynsym_section_start_;
434 break;
435 }
436 default: {
437 LOG(FATAL) << section_type;
438 symbol_section_start = NULL;
439 }
440 }
441 CHECK(symbol_section_start != NULL);
442 return symbol_section_start;
443}
444
Brian Carlstromc1409452014-02-26 14:06:23 -0800445const char* ElfFile::GetStringSectionStart(Elf32_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800446 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800447 const char* string_section_start;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800448 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000449 case SHT_SYMTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800450 string_section_start = strtab_section_start_;
451 break;
452 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000453 case SHT_DYNSYM: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800454 string_section_start = dynstr_section_start_;
455 break;
456 }
457 default: {
458 LOG(FATAL) << section_type;
459 string_section_start = NULL;
460 }
461 }
462 CHECK(string_section_start != NULL);
463 return string_section_start;
464}
465
Brian Carlstromc1409452014-02-26 14:06:23 -0800466const char* ElfFile::GetString(Elf32_Word section_type, Elf32_Word i) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800467 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
468 if (i == 0) {
469 return NULL;
470 }
471 const char* string_section_start = GetStringSectionStart(section_type);
472 const char* string = string_section_start + i;
473 return string;
474}
475
Brian Carlstromc1409452014-02-26 14:06:23 -0800476Elf32_Word* ElfFile::GetHashSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800477 CHECK(hash_section_start_ != NULL);
478 return hash_section_start_;
479}
480
Brian Carlstromc1409452014-02-26 14:06:23 -0800481Elf32_Word ElfFile::GetHashBucketNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800482 return GetHashSectionStart()[0];
483}
484
Brian Carlstromc1409452014-02-26 14:06:23 -0800485Elf32_Word ElfFile::GetHashChainNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800486 return GetHashSectionStart()[1];
487}
488
Brian Carlstromc1409452014-02-26 14:06:23 -0800489Elf32_Word ElfFile::GetHashBucket(size_t i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800490 CHECK_LT(i, GetHashBucketNum());
491 // 0 is nbucket, 1 is nchain
492 return GetHashSectionStart()[2 + i];
493}
494
Brian Carlstromc1409452014-02-26 14:06:23 -0800495Elf32_Word ElfFile::GetHashChain(size_t i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800496 CHECK_LT(i, GetHashChainNum());
497 // 0 is nbucket, 1 is nchain, & chains are after buckets
498 return GetHashSectionStart()[2 + GetHashBucketNum() + i];
499}
500
Brian Carlstromc1409452014-02-26 14:06:23 -0800501Elf32_Word ElfFile::GetProgramHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800502 return GetHeader().e_phnum;
503}
504
Brian Carlstromc1409452014-02-26 14:06:23 -0800505Elf32_Phdr& ElfFile::GetProgramHeader(Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800506 CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath();
507 byte* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
508 CHECK_LT(program_header, End()) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000509 return *reinterpret_cast<Elf32_Phdr*>(program_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800510}
511
Brian Carlstromc1409452014-02-26 14:06:23 -0800512Elf32_Phdr* ElfFile::FindProgamHeaderByType(Elf32_Word type) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000513 for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
514 Elf32_Phdr& program_header = GetProgramHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800515 if (program_header.p_type == type) {
516 return &program_header;
517 }
518 }
519 return NULL;
520}
521
Brian Carlstromc1409452014-02-26 14:06:23 -0800522Elf32_Word ElfFile::GetSectionHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800523 return GetHeader().e_shnum;
524}
525
Brian Carlstromc1409452014-02-26 14:06:23 -0800526Elf32_Shdr& ElfFile::GetSectionHeader(Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800527 // Can only access arbitrary sections when we have the whole file, not just program header.
528 // Even if we Load(), it doesn't bring in all the sections.
529 CHECK(!program_header_only_) << file_->GetPath();
530 CHECK_LT(i, GetSectionHeaderNum()) << file_->GetPath();
531 byte* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
532 CHECK_LT(section_header, End()) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000533 return *reinterpret_cast<Elf32_Shdr*>(section_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800534}
535
Brian Carlstromc1409452014-02-26 14:06:23 -0800536Elf32_Shdr* ElfFile::FindSectionByType(Elf32_Word type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800537 // Can only access arbitrary sections when we have the whole file, not just program header.
538 // We could change this to switch on known types if they were detected during loading.
539 CHECK(!program_header_only_) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000540 for (Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
541 Elf32_Shdr& section_header = GetSectionHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800542 if (section_header.sh_type == type) {
543 return &section_header;
544 }
545 }
546 return NULL;
547}
548
549// from bionic
Brian Carlstrom265091e2013-01-30 14:08:26 -0800550static unsigned elfhash(const char *_name) {
551 const unsigned char *name = (const unsigned char *) _name;
552 unsigned h = 0, g;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800553
Brian Carlstromdf629502013-07-17 22:39:56 -0700554 while (*name) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800555 h = (h << 4) + *name++;
556 g = h & 0xf0000000;
557 h ^= g;
558 h ^= g >> 24;
559 }
560 return h;
561}
562
Brian Carlstromc1409452014-02-26 14:06:23 -0800563Elf32_Shdr& ElfFile::GetSectionNameStringSection() const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800564 return GetSectionHeader(GetHeader().e_shstrndx);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800565}
566
Brian Carlstromc1409452014-02-26 14:06:23 -0800567const byte* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000568 Elf32_Word hash = elfhash(symbol_name.c_str());
569 Elf32_Word bucket_index = hash % GetHashBucketNum();
570 Elf32_Word symbol_and_chain_index = GetHashBucket(bucket_index);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800571 while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000572 Elf32_Sym& symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
573 const char* name = GetString(SHT_DYNSYM, symbol.st_name);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800574 if (symbol_name == name) {
575 return base_address_ + symbol.st_value;
576 }
577 symbol_and_chain_index = GetHashChain(symbol_and_chain_index);
578 }
579 return NULL;
580}
581
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000582bool ElfFile::IsSymbolSectionType(Elf32_Word section_type) {
583 return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800584}
585
Brian Carlstromc1409452014-02-26 14:06:23 -0800586Elf32_Word ElfFile::GetSymbolNum(Elf32_Shdr& section_header) const {
587 CHECK(IsSymbolSectionType(section_header.sh_type))
588 << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800589 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
590 return section_header.sh_size / section_header.sh_entsize;
591}
592
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000593Elf32_Sym& ElfFile::GetSymbol(Elf32_Word section_type,
Brian Carlstromc1409452014-02-26 14:06:23 -0800594 Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800595 return *(GetSymbolSectionStart(section_type) + i);
596}
597
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000598ElfFile::SymbolTable** ElfFile::GetSymbolTable(Elf32_Word section_type) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800599 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
600 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000601 case SHT_SYMTAB: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800602 return &symtab_symbol_table_;
603 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000604 case SHT_DYNSYM: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800605 return &dynsym_symbol_table_;
606 }
607 default: {
608 LOG(FATAL) << section_type;
609 return NULL;
610 }
611 }
612}
613
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000614Elf32_Sym* ElfFile::FindSymbolByName(Elf32_Word section_type,
615 const std::string& symbol_name,
616 bool build_map) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800617 CHECK(!program_header_only_) << file_->GetPath();
618 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800619
620 SymbolTable** symbol_table = GetSymbolTable(section_type);
621 if (*symbol_table != NULL || build_map) {
622 if (*symbol_table == NULL) {
623 DCHECK(build_map);
624 *symbol_table = new SymbolTable;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000625 Elf32_Shdr* symbol_section = FindSectionByType(section_type);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800626 CHECK(symbol_section != NULL) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000627 Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800628 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000629 Elf32_Sym& symbol = GetSymbol(section_type, i);
630 unsigned char type = ELF32_ST_TYPE(symbol.st_info);
631 if (type == STT_NOTYPE) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800632 continue;
633 }
634 const char* name = GetString(string_section, symbol.st_name);
635 if (name == NULL) {
636 continue;
637 }
Brian Carlstromc1409452014-02-26 14:06:23 -0800638 std::pair<SymbolTable::iterator, bool> result =
639 (*symbol_table)->insert(std::make_pair(name, &symbol));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800640 if (!result.second) {
641 // If a duplicate, make sure it has the same logical value. Seen on x86.
642 CHECK_EQ(symbol.st_value, result.first->second->st_value);
643 CHECK_EQ(symbol.st_size, result.first->second->st_size);
644 CHECK_EQ(symbol.st_info, result.first->second->st_info);
645 CHECK_EQ(symbol.st_other, result.first->second->st_other);
646 CHECK_EQ(symbol.st_shndx, result.first->second->st_shndx);
647 }
648 }
649 }
650 CHECK(*symbol_table != NULL);
651 SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
652 if (it == (*symbol_table)->end()) {
653 return NULL;
654 }
655 return it->second;
656 }
657
658 // Fall back to linear search
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000659 Elf32_Shdr* symbol_section = FindSectionByType(section_type);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800660 CHECK(symbol_section != NULL) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000661 Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800662 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000663 Elf32_Sym& symbol = GetSymbol(section_type, i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800664 const char* name = GetString(string_section, symbol.st_name);
665 if (name == NULL) {
666 continue;
667 }
668 if (symbol_name == name) {
669 return &symbol;
670 }
671 }
672 return NULL;
673}
674
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000675Elf32_Addr ElfFile::FindSymbolAddress(Elf32_Word section_type,
Brian Carlstromc1409452014-02-26 14:06:23 -0800676 const std::string& symbol_name,
677 bool build_map) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000678 Elf32_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800679 if (symbol == NULL) {
680 return 0;
681 }
682 return symbol->st_value;
683}
684
Brian Carlstromc1409452014-02-26 14:06:23 -0800685const char* ElfFile::GetString(Elf32_Shdr& string_section, Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800686 CHECK(!program_header_only_) << file_->GetPath();
687 // TODO: remove this static_cast from enum when using -std=gnu++0x
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000688 CHECK_EQ(static_cast<Elf32_Word>(SHT_STRTAB), string_section.sh_type) << file_->GetPath();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800689 CHECK_LT(i, string_section.sh_size) << file_->GetPath();
690 if (i == 0) {
691 return NULL;
692 }
693 byte* strings = Begin() + string_section.sh_offset;
694 byte* string = strings + i;
695 CHECK_LT(string, End()) << file_->GetPath();
Brian Carlstrom265091e2013-01-30 14:08:26 -0800696 return reinterpret_cast<const char*>(string);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800697}
698
Brian Carlstromc1409452014-02-26 14:06:23 -0800699Elf32_Word ElfFile::GetDynamicNum() const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000700 return GetDynamicProgramHeader().p_filesz / sizeof(Elf32_Dyn);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800701}
702
Brian Carlstromc1409452014-02-26 14:06:23 -0800703Elf32_Dyn& ElfFile::GetDynamic(Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800704 CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
705 return *(GetDynamicSectionStart() + i);
706}
707
Brian Carlstromc1409452014-02-26 14:06:23 -0800708Elf32_Word ElfFile::FindDynamicValueByType(Elf32_Sword type) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000709 for (Elf32_Word i = 0; i < GetDynamicNum(); i++) {
710 Elf32_Dyn& elf_dyn = GetDynamic(i);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800711 if (elf_dyn.d_tag == type) {
712 return elf_dyn.d_un.d_val;
713 }
714 }
715 return 0;
716}
717
Brian Carlstromc1409452014-02-26 14:06:23 -0800718Elf32_Rel* ElfFile::GetRelSectionStart(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000719 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
720 return reinterpret_cast<Elf32_Rel*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800721}
722
Brian Carlstromc1409452014-02-26 14:06:23 -0800723Elf32_Word ElfFile::GetRelNum(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000724 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800725 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
726 return section_header.sh_size / section_header.sh_entsize;
727}
728
Brian Carlstromc1409452014-02-26 14:06:23 -0800729Elf32_Rel& ElfFile::GetRel(Elf32_Shdr& section_header, Elf32_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000730 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800731 CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
732 return *(GetRelSectionStart(section_header) + i);
733}
734
Brian Carlstromc1409452014-02-26 14:06:23 -0800735Elf32_Rela* ElfFile::GetRelaSectionStart(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000736 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
737 return reinterpret_cast<Elf32_Rela*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800738}
739
Brian Carlstromc1409452014-02-26 14:06:23 -0800740Elf32_Word ElfFile::GetRelaNum(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000741 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800742 return section_header.sh_size / section_header.sh_entsize;
743}
744
Brian Carlstromc1409452014-02-26 14:06:23 -0800745Elf32_Rela& ElfFile::GetRela(Elf32_Shdr& section_header, Elf32_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000746 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800747 CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
748 return *(GetRelaSectionStart(section_header) + i);
749}
750
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800751// Base on bionic phdr_table_get_load_size
Brian Carlstromc1409452014-02-26 14:06:23 -0800752size_t ElfFile::GetLoadedSize() const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000753 Elf32_Addr min_vaddr = 0xFFFFFFFFu;
754 Elf32_Addr max_vaddr = 0x00000000u;
755 for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
756 Elf32_Phdr& program_header = GetProgramHeader(i);
757 if (program_header.p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800758 continue;
759 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000760 Elf32_Addr begin_vaddr = program_header.p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800761 if (begin_vaddr < min_vaddr) {
762 min_vaddr = begin_vaddr;
763 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000764 Elf32_Addr end_vaddr = program_header.p_vaddr + program_header.p_memsz;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800765 if (end_vaddr > max_vaddr) {
766 max_vaddr = end_vaddr;
767 }
768 }
769 min_vaddr = RoundDown(min_vaddr, kPageSize);
770 max_vaddr = RoundUp(max_vaddr, kPageSize);
771 CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
772 size_t loaded_size = max_vaddr - min_vaddr;
773 return loaded_size;
774}
775
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700776bool ElfFile::Load(bool executable, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800777 CHECK(program_header_only_) << file_->GetPath();
Andreas Gampe91268c12014-04-03 17:50:24 -0700778
779 if (executable) {
780 InstructionSet elf_ISA = kNone;
781 switch (GetHeader().e_machine) {
782 case EM_ARM: {
783 elf_ISA = kArm;
784 break;
785 }
786 case EM_AARCH64: {
787 elf_ISA = kArm64;
788 break;
789 }
790 case EM_386: {
791 elf_ISA = kX86;
792 break;
793 }
794 case EM_X86_64: {
795 elf_ISA = kX86_64;
796 break;
797 }
798 case EM_MIPS: {
799 elf_ISA = kMips;
800 break;
801 }
802 }
803
804 if (elf_ISA != kRuntimeISA) {
805 std::ostringstream oss;
806 oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
807 *error_msg = oss.str();
808 return false;
809 }
810 }
811
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000812 for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
813 Elf32_Phdr& program_header = GetProgramHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800814
815 // Record .dynamic header information for later use
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000816 if (program_header.p_type == PT_DYNAMIC) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800817 dynamic_program_header_ = &program_header;
818 continue;
819 }
820
821 // Not something to load, move on.
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000822 if (program_header.p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800823 continue;
824 }
825
826 // Found something to load.
827
828 // If p_vaddr is zero, it must be the first loadable segment,
829 // since they must be in order. Since it is zero, there isn't a
830 // specific address requested, so first request a contiguous chunk
831 // of required size for all segments, but with no
832 // permissions. We'll then carve that up with the proper
833 // permissions as we load the actual segments. If p_vaddr is
834 // non-zero, the segments require the specific address specified,
835 // which either was specified in the file because we already set
836 // base_address_ after the first zero segment).
Ian Rogerscdfcf372014-01-23 20:38:36 -0800837 int64_t temp_file_length = file_->GetLength();
838 if (temp_file_length < 0) {
839 errno = -temp_file_length;
840 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
841 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
842 return false;
843 }
844 size_t file_length = static_cast<size_t>(temp_file_length);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800845 if (program_header.p_vaddr == 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700846 std::string reservation_name("ElfFile reservation for ");
847 reservation_name += file_->GetPath();
Ian Rogers700a4022014-05-19 16:49:03 -0700848 std::unique_ptr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800849 NULL, GetLoadedSize(), PROT_NONE, false,
Brian Carlstromc1409452014-02-26 14:06:23 -0800850 error_msg));
851 if (reserve.get() == nullptr) {
852 *error_msg = StringPrintf("Failed to allocate %s: %s",
853 reservation_name.c_str(), error_msg->c_str());
854 return false;
855 }
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700856 base_address_ = reserve->Begin();
857 segments_.push_back(reserve.release());
858 }
859 // empty segment, nothing to map
860 if (program_header.p_memsz == 0) {
861 continue;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800862 }
863 byte* p_vaddr = base_address_ + program_header.p_vaddr;
864 int prot = 0;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000865 if (executable && ((program_header.p_flags & PF_X) != 0)) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700866 prot |= PROT_EXEC;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800867 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000868 if ((program_header.p_flags & PF_W) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700869 prot |= PROT_WRITE;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800870 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000871 if ((program_header.p_flags & PF_R) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700872 prot |= PROT_READ;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800873 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700874 int flags = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800875 if (writable_) {
876 prot |= PROT_WRITE;
877 flags |= MAP_SHARED;
878 } else {
879 flags |= MAP_PRIVATE;
880 }
Brian Carlstrom3a223612013-10-10 17:18:24 -0700881 if (file_length < (program_header.p_offset + program_header.p_memsz)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800882 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700883 "%d of %d bytes: '%s'", file_length, i,
884 program_header.p_offset + program_header.p_memsz,
885 file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700886 return false;
887 }
Ian Rogers700a4022014-05-19 16:49:03 -0700888 std::unique_ptr<MemMap> segment(MemMap::MapFileAtAddress(p_vaddr,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800889 program_header.p_memsz,
890 prot, flags, file_->Fd(),
891 program_header.p_offset,
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700892 true, // implies MAP_FIXED
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700893 file_->GetPath().c_str(),
894 error_msg));
Brian Carlstromc1409452014-02-26 14:06:23 -0800895 if (segment.get() == nullptr) {
896 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
897 i, file_->GetPath().c_str(), error_msg->c_str());
898 return false;
899 }
900 if (segment->Begin() != p_vaddr) {
901 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
902 "instead mapped to %p",
903 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
904 return false;
905 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800906 segments_.push_back(segment.release());
907 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800908
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800909 // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
910 dynamic_section_start_
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000911 = reinterpret_cast<Elf32_Dyn*>(base_address_ + GetDynamicProgramHeader().p_vaddr);
912 for (Elf32_Word i = 0; i < GetDynamicNum(); i++) {
913 Elf32_Dyn& elf_dyn = GetDynamic(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800914 byte* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
915 switch (elf_dyn.d_tag) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000916 case DT_HASH: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800917 if (!ValidPointer(d_ptr)) {
918 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
919 d_ptr, file_->GetPath().c_str());
920 return false;
921 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000922 hash_section_start_ = reinterpret_cast<Elf32_Word*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800923 break;
924 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000925 case DT_STRTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800926 if (!ValidPointer(d_ptr)) {
927 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
928 d_ptr, file_->GetPath().c_str());
929 return false;
930 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800931 dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
932 break;
933 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000934 case DT_SYMTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800935 if (!ValidPointer(d_ptr)) {
936 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
937 d_ptr, file_->GetPath().c_str());
938 return false;
939 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000940 dynsym_section_start_ = reinterpret_cast<Elf32_Sym*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800941 break;
942 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000943 case DT_NULL: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800944 if (GetDynamicNum() != i+1) {
945 *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
946 "expected %d as implied by size of PT_DYNAMIC segment in %s",
947 i + 1, GetDynamicNum(), file_->GetPath().c_str());
948 return false;
949 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800950 break;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800951 }
952 }
953 }
954
Mark Mendellae9fd932014-02-10 16:14:35 -0800955 // Use GDB JIT support to do stack backtrace, etc.
956 if (executable) {
957 GdbJITSupport();
958 }
959
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800960 return true;
961}
962
Brian Carlstromc1409452014-02-26 14:06:23 -0800963bool ElfFile::ValidPointer(const byte* start) const {
964 for (size_t i = 0; i < segments_.size(); ++i) {
965 const MemMap* segment = segments_[i];
966 if (segment->Begin() <= start && start < segment->End()) {
967 return true;
968 }
969 }
970 return false;
971}
972
Mark Mendellae9fd932014-02-10 16:14:35 -0800973static bool check_section_name(ElfFile& file, int section_num, const char *name) {
974 Elf32_Shdr& section_header = file.GetSectionHeader(section_num);
975 const char *section_name = file.GetString(SHT_SYMTAB, section_header.sh_name);
976 return strcmp(name, section_name) == 0;
977}
978
979static void IncrementUint32(byte *p, uint32_t increment) {
980 uint32_t *u = reinterpret_cast<uint32_t *>(p);
981 *u += increment;
982}
983
984static void RoundAndClear(byte *image, uint32_t& offset, int pwr2) {
985 uint32_t mask = pwr2 - 1;
986 while (offset & mask) {
987 image[offset++] = 0;
988 }
989}
990
991// Simple macro to bump a point to a section header to the next one.
992#define BUMP_SHENT(sp) \
993 sp = reinterpret_cast<Elf32_Shdr *> (\
994 reinterpret_cast<byte*>(sp) + elf_hdr.e_shentsize);\
995 offset += elf_hdr.e_shentsize
996
997void ElfFile::GdbJITSupport() {
998 // We only get here if we only are mapping the program header.
999 DCHECK(program_header_only_);
1000
1001 // Well, we need the whole file to do this.
1002 std::string error_msg;
Ian Rogers700a4022014-05-19 16:49:03 -07001003 std::unique_ptr<ElfFile> ptr(Open(const_cast<File*>(file_), false, false, &error_msg));
Mark Mendellae9fd932014-02-10 16:14:35 -08001004 ElfFile& all = *ptr;
1005
1006 // Do we have interesting sections?
1007 // Is this an OAT file with interesting sections?
1008 if (all.GetSectionHeaderNum() != kExpectedSectionsInOATFile) {
1009 return;
1010 }
1011 if (!check_section_name(all, 8, ".debug_info") ||
1012 !check_section_name(all, 9, ".debug_abbrev") ||
1013 !check_section_name(all, 10, ".debug_frame") ||
1014 !check_section_name(all, 11, ".debug_str")) {
1015 return;
1016 }
Ian Rogers1a570662014-03-12 01:02:21 -07001017#ifdef __LP64__
1018 if (true) {
1019 return; // No ELF debug support in 64bit.
1020 }
1021#endif
Kenny Root6243e0e2014-03-03 13:33:48 -08001022 // This is not needed if we have no .text segment.
1023 uint32_t text_start_addr = 0;
1024 for (uint32_t i = 0; i < segments_.size(); i++) {
1025 if (segments_[i]->GetProtect() & PROT_EXEC) {
1026 // We found the .text section.
1027 text_start_addr = PointerToLowMemUInt32(segments_[i]->Begin());
1028 break;
1029 }
1030 }
1031 if (text_start_addr == 0U) {
1032 return;
1033 }
1034
Mark Mendellae9fd932014-02-10 16:14:35 -08001035 // Okay, we are good enough. Fake up an ELF image and tell GDB about it.
1036 // We need some extra space for the debug and string sections, the ELF header, and the
1037 // section header.
1038 uint32_t needed_size = KB;
1039
1040 for (Elf32_Word i = 1; i < all.GetSectionHeaderNum(); i++) {
1041 Elf32_Shdr& section_header = all.GetSectionHeader(i);
1042 if (section_header.sh_addr == 0 && section_header.sh_type != SHT_DYNSYM) {
1043 // Debug section: we need it.
1044 needed_size += section_header.sh_size;
1045 } else if (section_header.sh_type == SHT_STRTAB &&
1046 strcmp(".shstrtab",
1047 all.GetString(SHT_SYMTAB, section_header.sh_name)) == 0) {
1048 // We also need the shared string table.
1049 needed_size += section_header.sh_size;
1050
1051 // We also need the extra strings .symtab\0.strtab\0
1052 needed_size += 16;
1053 }
1054 }
1055
1056 // Start creating our image.
1057 jit_elf_image_ = new byte[needed_size];
1058
1059 // Create the Elf Header by copying the old one
1060 Elf32_Ehdr& elf_hdr =
1061 *reinterpret_cast<Elf32_Ehdr*>(jit_elf_image_);
1062
1063 elf_hdr = all.GetHeader();
1064 elf_hdr.e_entry = 0;
1065 elf_hdr.e_phoff = 0;
1066 elf_hdr.e_phnum = 0;
1067 elf_hdr.e_phentsize = 0;
1068 elf_hdr.e_type = ET_EXEC;
1069
1070 uint32_t offset = sizeof(Elf32_Ehdr);
1071
1072 // Copy the debug sections and string table.
1073 uint32_t debug_offsets[kExpectedSectionsInOATFile];
1074 memset(debug_offsets, '\0', sizeof debug_offsets);
1075 Elf32_Shdr *text_header = nullptr;
1076 int extra_shstrtab_entries = -1;
1077 int text_section_index = -1;
1078 int section_index = 1;
1079 for (Elf32_Word i = 1; i < kExpectedSectionsInOATFile; i++) {
1080 Elf32_Shdr& section_header = all.GetSectionHeader(i);
1081 // Round up to multiple of 4, ensuring zero fill.
1082 RoundAndClear(jit_elf_image_, offset, 4);
1083 if (section_header.sh_addr == 0 && section_header.sh_type != SHT_DYNSYM) {
1084 // Debug section: we need it. Unfortunately, it wasn't mapped in.
1085 debug_offsets[i] = offset;
1086 // Read it from the file.
1087 lseek(file_->Fd(), section_header.sh_offset, SEEK_SET);
1088 read(file_->Fd(), jit_elf_image_ + offset, section_header.sh_size);
1089 offset += section_header.sh_size;
1090 section_index++;
1091 offset += 16;
1092 } else if (section_header.sh_type == SHT_STRTAB &&
1093 strcmp(".shstrtab",
1094 all.GetString(SHT_SYMTAB, section_header.sh_name)) == 0) {
1095 // We also need the shared string table.
1096 debug_offsets[i] = offset;
1097 // Read it from the file.
1098 lseek(file_->Fd(), section_header.sh_offset, SEEK_SET);
1099 read(file_->Fd(), jit_elf_image_ + offset, section_header.sh_size);
1100 offset += section_header.sh_size;
1101 // We also need the extra strings .symtab\0.strtab\0
1102 extra_shstrtab_entries = section_header.sh_size;
1103 memcpy(jit_elf_image_+offset, ".symtab\0.strtab\0", 16);
1104 offset += 16;
1105 section_index++;
1106 } else if (section_header.sh_flags & SHF_EXECINSTR) {
1107 DCHECK(strcmp(".text", all.GetString(SHT_SYMTAB,
1108 section_header.sh_name)) == 0);
1109 text_header = &section_header;
1110 text_section_index = section_index++;
1111 }
1112 }
1113 DCHECK(text_header != nullptr);
1114 DCHECK_NE(extra_shstrtab_entries, -1);
1115
1116 // We now need to update the addresses for debug_info and debug_frame to get to the
1117 // correct offset within the .text section.
Mark Mendellae9fd932014-02-10 16:14:35 -08001118 byte *p = jit_elf_image_+debug_offsets[8];
1119 byte *end = p + all.GetSectionHeader(8).sh_size;
1120
1121 // For debug_info; patch compilation using low_pc @ offset 13, high_pc at offset 17.
1122 IncrementUint32(p + 13, text_start_addr);
1123 IncrementUint32(p + 17, text_start_addr);
1124
1125 // Now fix the low_pc, high_pc for each method address.
1126 // First method starts at offset 0x15, each subsequent method is 1+3*4 bytes further.
1127 for (p += 0x15; p < end; p += 1 /* attr# */ + 3 * sizeof(uint32_t) /* addresses */) {
1128 IncrementUint32(p + 1 + sizeof(uint32_t), text_start_addr);
1129 IncrementUint32(p + 1 + 2 * sizeof(uint32_t), text_start_addr);
1130 }
1131
1132 // Now we have to handle the debug_frame method start addresses
1133 p = jit_elf_image_+debug_offsets[10];
1134 end = p + all.GetSectionHeader(10).sh_size;
1135
1136 // Skip past the CIE.
1137 p += *reinterpret_cast<uint32_t *>(p) + 4;
1138
1139 // And walk the FDEs.
1140 for (; p < end; p += *reinterpret_cast<uint32_t *>(p) + sizeof(uint32_t)) {
1141 IncrementUint32(p + 2 * sizeof(uint32_t), text_start_addr);
1142 }
1143
1144 // Create the data for the symbol table.
1145 const int kSymbtabAlignment = 16;
1146 RoundAndClear(jit_elf_image_, offset, kSymbtabAlignment);
1147 uint32_t symtab_offset = offset;
1148
1149 // First entry is empty.
1150 memset(jit_elf_image_+offset, 0, sizeof(Elf32_Sym));
1151 offset += sizeof(Elf32_Sym);
1152
1153 // Symbol 1 is the real .text section.
1154 Elf32_Sym& sym_ent = *reinterpret_cast<Elf32_Sym*>(jit_elf_image_+offset);
1155 sym_ent.st_name = 1; /* .text */
1156 sym_ent.st_value = text_start_addr;
1157 sym_ent.st_size = text_header->sh_size;
1158 SetBindingAndType(&sym_ent, STB_LOCAL, STT_SECTION);
1159 sym_ent.st_other = 0;
1160 sym_ent.st_shndx = text_section_index;
1161 offset += sizeof(Elf32_Sym);
1162
1163 // Create the data for the string table.
1164 RoundAndClear(jit_elf_image_, offset, kSymbtabAlignment);
1165 const int kTextStringSize = 7;
1166 uint32_t strtab_offset = offset;
1167 memcpy(jit_elf_image_+offset, "\0.text", kTextStringSize);
1168 offset += kTextStringSize;
1169
1170 // Create the section header table.
1171 // Round up to multiple of kSymbtabAlignment, ensuring zero fill.
1172 RoundAndClear(jit_elf_image_, offset, kSymbtabAlignment);
1173 elf_hdr.e_shoff = offset;
1174 Elf32_Shdr *sp =
1175 reinterpret_cast<Elf32_Shdr *>(jit_elf_image_ + offset);
1176
1177 // Copy the first empty index.
1178 *sp = all.GetSectionHeader(0);
1179 BUMP_SHENT(sp);
1180
1181 elf_hdr.e_shnum = 1;
1182 for (Elf32_Word i = 1; i < kExpectedSectionsInOATFile; i++) {
1183 Elf32_Shdr& section_header = all.GetSectionHeader(i);
1184 if (section_header.sh_addr == 0 && section_header.sh_type != SHT_DYNSYM) {
1185 // Debug section: we need it.
1186 *sp = section_header;
1187 sp->sh_offset = debug_offsets[i];
1188 sp->sh_addr = 0;
1189 elf_hdr.e_shnum++;
1190 BUMP_SHENT(sp);
1191 } else if (section_header.sh_type == SHT_STRTAB &&
1192 strcmp(".shstrtab",
1193 all.GetString(SHT_SYMTAB, section_header.sh_name)) == 0) {
1194 // We also need the shared string table.
1195 *sp = section_header;
1196 sp->sh_offset = debug_offsets[i];
1197 sp->sh_size += 16; /* sizeof ".symtab\0.strtab\0" */
1198 sp->sh_addr = 0;
1199 elf_hdr.e_shstrndx = elf_hdr.e_shnum;
1200 elf_hdr.e_shnum++;
1201 BUMP_SHENT(sp);
1202 }
1203 }
1204
1205 // Add a .text section for the matching code section.
1206 *sp = *text_header;
1207 sp->sh_type = SHT_NOBITS;
1208 sp->sh_offset = 0;
1209 sp->sh_addr = text_start_addr;
1210 elf_hdr.e_shnum++;
1211 BUMP_SHENT(sp);
1212
1213 // .symtab section: Need an empty index and the .text entry
1214 sp->sh_name = extra_shstrtab_entries;
1215 sp->sh_type = SHT_SYMTAB;
1216 sp->sh_flags = 0;
1217 sp->sh_addr = 0;
1218 sp->sh_offset = symtab_offset;
1219 sp->sh_size = 2 * sizeof(Elf32_Sym);
1220 sp->sh_link = elf_hdr.e_shnum + 1; // Link to .strtab section.
1221 sp->sh_info = 0;
1222 sp->sh_addralign = 16;
1223 sp->sh_entsize = sizeof(Elf32_Sym);
1224 elf_hdr.e_shnum++;
1225 BUMP_SHENT(sp);
1226
1227 // .strtab section: Enough for .text\0.
1228 sp->sh_name = extra_shstrtab_entries + 8;
1229 sp->sh_type = SHT_STRTAB;
1230 sp->sh_flags = 0;
1231 sp->sh_addr = 0;
1232 sp->sh_offset = strtab_offset;
1233 sp->sh_size = kTextStringSize;
1234 sp->sh_link = 0;
1235 sp->sh_info = 0;
1236 sp->sh_addralign = 16;
1237 sp->sh_entsize = 0;
1238 elf_hdr.e_shnum++;
1239 BUMP_SHENT(sp);
1240
1241 // We now have enough information to tell GDB about our file.
1242 jit_gdb_entry_ = CreateCodeEntry(jit_elf_image_, offset);
1243}
1244
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001245} // namespace art