blob: 01ca60f6c071a77588617f9300aa8dbd1e8be2b2 [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"
23#include "base/stl_util.h"
24#include "utils.h"
Andreas Gampe91268c12014-04-03 17:50:24 -070025#include "instruction_set.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080026
27namespace art {
28
Mark Mendellae9fd932014-02-10 16:14:35 -080029// -------------------------------------------------------------------
30// Binary GDB JIT Interface as described in
31// http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
32extern "C" {
33 typedef enum {
34 JIT_NOACTION = 0,
35 JIT_REGISTER_FN,
36 JIT_UNREGISTER_FN
37 } JITAction;
38
39 struct JITCodeEntry {
40 JITCodeEntry* next_;
41 JITCodeEntry* prev_;
42 const byte *symfile_addr_;
43 uint64_t symfile_size_;
44 };
45
46 struct JITDescriptor {
47 uint32_t version_;
48 uint32_t action_flag_;
49 JITCodeEntry* relevant_entry_;
50 JITCodeEntry* first_entry_;
51 };
52
53 // GDB will place breakpoint into this function.
54 // To prevent GCC from inlining or removing it we place noinline attribute
55 // and inline assembler statement inside.
56 void __attribute__((noinline)) __jit_debug_register_code() {
57 __asm__("");
58 }
59
60 // GDB will inspect contents of this descriptor.
61 // Static initialization is necessary to prevent GDB from seeing
62 // uninitialized descriptor.
63 JITDescriptor __jit_debug_descriptor = { 1, JIT_NOACTION, nullptr, nullptr };
64}
65
66
67static JITCodeEntry* CreateCodeEntry(const byte *symfile_addr,
68 uintptr_t symfile_size) {
69 JITCodeEntry* entry = new JITCodeEntry;
70 entry->symfile_addr_ = symfile_addr;
71 entry->symfile_size_ = symfile_size;
72 entry->prev_ = nullptr;
73
74 // TODO: Do we need a lock here?
75 entry->next_ = __jit_debug_descriptor.first_entry_;
76 if (entry->next_ != nullptr) {
77 entry->next_->prev_ = entry;
78 }
79 __jit_debug_descriptor.first_entry_ = entry;
80 __jit_debug_descriptor.relevant_entry_ = entry;
81
82 __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
83 __jit_debug_register_code();
84 return entry;
85}
86
87
88static void UnregisterCodeEntry(JITCodeEntry* entry) {
89 // TODO: Do we need a lock here?
90 if (entry->prev_ != nullptr) {
91 entry->prev_->next_ = entry->next_;
92 } else {
93 __jit_debug_descriptor.first_entry_ = entry->next_;
94 }
95
96 if (entry->next_ != nullptr) {
97 entry->next_->prev_ = entry->prev_;
98 }
99
100 __jit_debug_descriptor.relevant_entry_ = entry;
101 __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
102 __jit_debug_register_code();
103 delete entry;
104}
105
Brian Carlstromc1409452014-02-26 14:06:23 -0800106ElfFile::ElfFile(File* file, bool writable, bool program_header_only)
107 : file_(file),
108 writable_(writable),
109 program_header_only_(program_header_only),
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700110 header_(NULL),
111 base_address_(NULL),
112 program_headers_start_(NULL),
113 section_headers_start_(NULL),
114 dynamic_program_header_(NULL),
115 dynamic_section_start_(NULL),
116 symtab_section_start_(NULL),
117 dynsym_section_start_(NULL),
118 strtab_section_start_(NULL),
119 dynstr_section_start_(NULL),
120 hash_section_start_(NULL),
121 symtab_symbol_table_(NULL),
Mark Mendellae9fd932014-02-10 16:14:35 -0800122 dynsym_symbol_table_(NULL),
123 jit_elf_image_(NULL),
124 jit_gdb_entry_(NULL) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800125 CHECK(file != NULL);
126}
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800127
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700128ElfFile* ElfFile::Open(File* file, bool writable, bool program_header_only,
129 std::string* error_msg) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800130 UniquePtr<ElfFile> elf_file(new ElfFile(file, writable, program_header_only));
131 if (!elf_file->Setup(error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800133 }
134 return elf_file.release();
135}
136
Brian Carlstromc1409452014-02-26 14:06:23 -0800137bool ElfFile::Setup(std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800138 int prot;
139 int flags;
140 if (writable_) {
141 prot = PROT_READ | PROT_WRITE;
142 flags = MAP_SHARED;
143 } else {
144 prot = PROT_READ;
145 flags = MAP_PRIVATE;
146 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800147 int64_t temp_file_length = file_->GetLength();
148 if (temp_file_length < 0) {
149 errno = -temp_file_length;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700150 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
151 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800152 return false;
153 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800154 size_t file_length = static_cast<size_t>(temp_file_length);
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000155 if (file_length < sizeof(Elf32_Ehdr)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800156 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000157 "%zd bytes: '%s'", file_length, sizeof(Elf32_Ehdr),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700158 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800159 return false;
160 }
161
Brian Carlstromc1409452014-02-26 14:06:23 -0800162 if (program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800163 // first just map ELF header to get program header size information
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000164 size_t elf_header_size = sizeof(Elf32_Ehdr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700165 if (!SetMap(MemMap::MapFile(elf_header_size, prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800166 file_->GetPath().c_str(), error_msg),
167 error_msg)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800168 return false;
169 }
170 // then remap to cover program header
171 size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
Brian Carlstrom3a223612013-10-10 17:18:24 -0700172 if (file_length < program_header_size) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800173 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700174 "header of %zd bytes: '%s'", file_length,
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000175 sizeof(Elf32_Ehdr), file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700176 return false;
177 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700178 if (!SetMap(MemMap::MapFile(program_header_size, prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800179 file_->GetPath().c_str(), error_msg),
180 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700181 *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800182 return false;
183 }
184 } else {
185 // otherwise map entire file
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700186 if (!SetMap(MemMap::MapFile(file_->GetLength(), prot, flags, file_->Fd(), 0,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800187 file_->GetPath().c_str(), error_msg),
188 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700189 *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800190 return false;
191 }
192 }
193
194 // Either way, the program header is relative to the elf header
195 program_headers_start_ = Begin() + GetHeader().e_phoff;
196
Brian Carlstromc1409452014-02-26 14:06:23 -0800197 if (!program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800198 // Setup section headers.
199 section_headers_start_ = Begin() + GetHeader().e_shoff;
200
201 // Find .dynamic section info from program header
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000202 dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800203 if (dynamic_program_header_ == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700204 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
205 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800206 return false;
207 }
208
209 dynamic_section_start_
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000210 = reinterpret_cast<Elf32_Dyn*>(Begin() + GetDynamicProgramHeader().p_offset);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800211
212 // Find other sections from section headers
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000213 for (Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
214 Elf32_Shdr& section_header = GetSectionHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800215 byte* section_addr = Begin() + section_header.sh_offset;
216 switch (section_header.sh_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000217 case SHT_SYMTAB: {
218 symtab_section_start_ = reinterpret_cast<Elf32_Sym*>(section_addr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800219 break;
220 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000221 case SHT_DYNSYM: {
222 dynsym_section_start_ = reinterpret_cast<Elf32_Sym*>(section_addr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800223 break;
224 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000225 case SHT_STRTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800226 // TODO: base these off of sh_link from .symtab and .dynsym above
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000227 if ((section_header.sh_flags & SHF_ALLOC) != 0) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800228 dynstr_section_start_ = reinterpret_cast<char*>(section_addr);
229 } else {
230 strtab_section_start_ = reinterpret_cast<char*>(section_addr);
231 }
232 break;
233 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000234 case SHT_DYNAMIC: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800235 if (reinterpret_cast<byte*>(dynamic_section_start_) != section_addr) {
236 LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
Brian Carlstrom265091e2013-01-30 14:08:26 -0800237 << file_->GetPath() << ": " << std::hex
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800238 << reinterpret_cast<void*>(dynamic_section_start_)
239 << " != " << reinterpret_cast<void*>(section_addr);
240 return false;
241 }
242 break;
243 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000244 case SHT_HASH: {
245 hash_section_start_ = reinterpret_cast<Elf32_Word*>(section_addr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800246 break;
247 }
248 }
249 }
250 }
251 return true;
252}
253
254ElfFile::~ElfFile() {
255 STLDeleteElements(&segments_);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800256 delete symtab_symbol_table_;
257 delete dynsym_symbol_table_;
Mark Mendellae9fd932014-02-10 16:14:35 -0800258 delete jit_elf_image_;
259 if (jit_gdb_entry_) {
260 UnregisterCodeEntry(jit_gdb_entry_);
261 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800262}
263
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800264bool ElfFile::SetMap(MemMap* map, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800265 if (map == NULL) {
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800266 // MemMap::Open should have already set an error.
267 DCHECK(!error_msg->empty());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800268 return false;
269 }
270 map_.reset(map);
271 CHECK(map_.get() != NULL) << file_->GetPath();
272 CHECK(map_->Begin() != NULL) << file_->GetPath();
273
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000274 header_ = reinterpret_cast<Elf32_Ehdr*>(map_->Begin());
275 if ((ELFMAG0 != header_->e_ident[EI_MAG0])
276 || (ELFMAG1 != header_->e_ident[EI_MAG1])
277 || (ELFMAG2 != header_->e_ident[EI_MAG2])
278 || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800279 *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
280 ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800281 file_->GetPath().c_str(),
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000282 header_->e_ident[EI_MAG0],
283 header_->e_ident[EI_MAG1],
284 header_->e_ident[EI_MAG2],
285 header_->e_ident[EI_MAG3]);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800286 return false;
287 }
Brian Carlstromc1409452014-02-26 14:06:23 -0800288 if (ELFCLASS32 != header_->e_ident[EI_CLASS]) {
289 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
290 ELFCLASS32,
291 file_->GetPath().c_str(),
292 header_->e_ident[EI_CLASS]);
293 return false;
294 }
295 if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
296 *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
297 ELFDATA2LSB,
298 file_->GetPath().c_str(),
299 header_->e_ident[EI_CLASS]);
300 return false;
301 }
302 if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
303 *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
304 EV_CURRENT,
305 file_->GetPath().c_str(),
306 header_->e_ident[EI_CLASS]);
307 return false;
308 }
309 if (ET_DYN != header_->e_type) {
310 *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
311 ET_DYN,
312 file_->GetPath().c_str(),
313 header_->e_type);
314 return false;
315 }
316 if (EV_CURRENT != header_->e_version) {
317 *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
318 EV_CURRENT,
319 file_->GetPath().c_str(),
320 header_->e_version);
321 return false;
322 }
323 if (0 != header_->e_entry) {
324 *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
325 0,
326 file_->GetPath().c_str(),
327 header_->e_entry);
328 return false;
329 }
330 if (0 == header_->e_phoff) {
331 *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
332 file_->GetPath().c_str());
333 return false;
334 }
335 if (0 == header_->e_shoff) {
336 *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
337 file_->GetPath().c_str());
338 return false;
339 }
340 if (0 == header_->e_ehsize) {
341 *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
342 file_->GetPath().c_str());
343 return false;
344 }
345 if (0 == header_->e_phentsize) {
346 *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
347 file_->GetPath().c_str());
348 return false;
349 }
350 if (0 == header_->e_phnum) {
351 *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
352 file_->GetPath().c_str());
353 return false;
354 }
355 if (0 == header_->e_shentsize) {
356 *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
357 file_->GetPath().c_str());
358 return false;
359 }
360 if (0 == header_->e_shnum) {
361 *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
362 file_->GetPath().c_str());
363 return false;
364 }
365 if (0 == header_->e_shstrndx) {
366 *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
367 file_->GetPath().c_str());
368 return false;
369 }
370 if (header_->e_shstrndx >= header_->e_shnum) {
371 *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
372 header_->e_shstrndx,
373 header_->e_shnum,
374 file_->GetPath().c_str());
375 return false;
376 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800377
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800378 if (!program_header_only_) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800379 if (header_->e_phoff >= Size()) {
Dmitry Petrochenko659d87d2014-02-27 14:23:11 +0700380 *error_msg = StringPrintf("Failed to find e_phoff value %d less than %zd in %s",
Brian Carlstromc1409452014-02-26 14:06:23 -0800381 header_->e_phoff,
382 Size(),
383 file_->GetPath().c_str());
384 return false;
385 }
386 if (header_->e_shoff >= Size()) {
Dmitry Petrochenko659d87d2014-02-27 14:23:11 +0700387 *error_msg = StringPrintf("Failed to find e_shoff value %d less than %zd in %s",
Brian Carlstromc1409452014-02-26 14:06:23 -0800388 header_->e_shoff,
389 Size(),
390 file_->GetPath().c_str());
391 return false;
392 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800393 }
394 return true;
395}
396
397
Brian Carlstromc1409452014-02-26 14:06:23 -0800398Elf32_Ehdr& ElfFile::GetHeader() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800399 CHECK(header_ != NULL);
400 return *header_;
401}
402
Brian Carlstromc1409452014-02-26 14:06:23 -0800403byte* ElfFile::GetProgramHeadersStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800404 CHECK(program_headers_start_ != NULL);
405 return program_headers_start_;
406}
407
Brian Carlstromc1409452014-02-26 14:06:23 -0800408byte* ElfFile::GetSectionHeadersStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800409 CHECK(section_headers_start_ != NULL);
410 return section_headers_start_;
411}
412
Brian Carlstromc1409452014-02-26 14:06:23 -0800413Elf32_Phdr& ElfFile::GetDynamicProgramHeader() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800414 CHECK(dynamic_program_header_ != NULL);
415 return *dynamic_program_header_;
416}
417
Brian Carlstromc1409452014-02-26 14:06:23 -0800418Elf32_Dyn* ElfFile::GetDynamicSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800419 CHECK(dynamic_section_start_ != NULL);
420 return dynamic_section_start_;
421}
422
Brian Carlstromc1409452014-02-26 14:06:23 -0800423Elf32_Sym* ElfFile::GetSymbolSectionStart(Elf32_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800424 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000425 Elf32_Sym* symbol_section_start;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800426 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000427 case SHT_SYMTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800428 symbol_section_start = symtab_section_start_;
429 break;
430 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000431 case SHT_DYNSYM: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800432 symbol_section_start = dynsym_section_start_;
433 break;
434 }
435 default: {
436 LOG(FATAL) << section_type;
437 symbol_section_start = NULL;
438 }
439 }
440 CHECK(symbol_section_start != NULL);
441 return symbol_section_start;
442}
443
Brian Carlstromc1409452014-02-26 14:06:23 -0800444const char* ElfFile::GetStringSectionStart(Elf32_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800445 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800446 const char* string_section_start;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800447 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000448 case SHT_SYMTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800449 string_section_start = strtab_section_start_;
450 break;
451 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000452 case SHT_DYNSYM: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800453 string_section_start = dynstr_section_start_;
454 break;
455 }
456 default: {
457 LOG(FATAL) << section_type;
458 string_section_start = NULL;
459 }
460 }
461 CHECK(string_section_start != NULL);
462 return string_section_start;
463}
464
Brian Carlstromc1409452014-02-26 14:06:23 -0800465const char* ElfFile::GetString(Elf32_Word section_type, Elf32_Word i) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800466 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
467 if (i == 0) {
468 return NULL;
469 }
470 const char* string_section_start = GetStringSectionStart(section_type);
471 const char* string = string_section_start + i;
472 return string;
473}
474
Brian Carlstromc1409452014-02-26 14:06:23 -0800475Elf32_Word* ElfFile::GetHashSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800476 CHECK(hash_section_start_ != NULL);
477 return hash_section_start_;
478}
479
Brian Carlstromc1409452014-02-26 14:06:23 -0800480Elf32_Word ElfFile::GetHashBucketNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800481 return GetHashSectionStart()[0];
482}
483
Brian Carlstromc1409452014-02-26 14:06:23 -0800484Elf32_Word ElfFile::GetHashChainNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800485 return GetHashSectionStart()[1];
486}
487
Brian Carlstromc1409452014-02-26 14:06:23 -0800488Elf32_Word ElfFile::GetHashBucket(size_t i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800489 CHECK_LT(i, GetHashBucketNum());
490 // 0 is nbucket, 1 is nchain
491 return GetHashSectionStart()[2 + i];
492}
493
Brian Carlstromc1409452014-02-26 14:06:23 -0800494Elf32_Word ElfFile::GetHashChain(size_t i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800495 CHECK_LT(i, GetHashChainNum());
496 // 0 is nbucket, 1 is nchain, & chains are after buckets
497 return GetHashSectionStart()[2 + GetHashBucketNum() + i];
498}
499
Brian Carlstromc1409452014-02-26 14:06:23 -0800500Elf32_Word ElfFile::GetProgramHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800501 return GetHeader().e_phnum;
502}
503
Brian Carlstromc1409452014-02-26 14:06:23 -0800504Elf32_Phdr& ElfFile::GetProgramHeader(Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800505 CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath();
506 byte* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
507 CHECK_LT(program_header, End()) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000508 return *reinterpret_cast<Elf32_Phdr*>(program_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800509}
510
Brian Carlstromc1409452014-02-26 14:06:23 -0800511Elf32_Phdr* ElfFile::FindProgamHeaderByType(Elf32_Word type) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000512 for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
513 Elf32_Phdr& program_header = GetProgramHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800514 if (program_header.p_type == type) {
515 return &program_header;
516 }
517 }
518 return NULL;
519}
520
Brian Carlstromc1409452014-02-26 14:06:23 -0800521Elf32_Word ElfFile::GetSectionHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800522 return GetHeader().e_shnum;
523}
524
Brian Carlstromc1409452014-02-26 14:06:23 -0800525Elf32_Shdr& ElfFile::GetSectionHeader(Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800526 // Can only access arbitrary sections when we have the whole file, not just program header.
527 // Even if we Load(), it doesn't bring in all the sections.
528 CHECK(!program_header_only_) << file_->GetPath();
529 CHECK_LT(i, GetSectionHeaderNum()) << file_->GetPath();
530 byte* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
531 CHECK_LT(section_header, End()) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000532 return *reinterpret_cast<Elf32_Shdr*>(section_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800533}
534
Brian Carlstromc1409452014-02-26 14:06:23 -0800535Elf32_Shdr* ElfFile::FindSectionByType(Elf32_Word type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800536 // Can only access arbitrary sections when we have the whole file, not just program header.
537 // We could change this to switch on known types if they were detected during loading.
538 CHECK(!program_header_only_) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000539 for (Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
540 Elf32_Shdr& section_header = GetSectionHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800541 if (section_header.sh_type == type) {
542 return &section_header;
543 }
544 }
545 return NULL;
546}
547
548// from bionic
Brian Carlstrom265091e2013-01-30 14:08:26 -0800549static unsigned elfhash(const char *_name) {
550 const unsigned char *name = (const unsigned char *) _name;
551 unsigned h = 0, g;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800552
Brian Carlstromdf629502013-07-17 22:39:56 -0700553 while (*name) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800554 h = (h << 4) + *name++;
555 g = h & 0xf0000000;
556 h ^= g;
557 h ^= g >> 24;
558 }
559 return h;
560}
561
Brian Carlstromc1409452014-02-26 14:06:23 -0800562Elf32_Shdr& ElfFile::GetSectionNameStringSection() const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800563 return GetSectionHeader(GetHeader().e_shstrndx);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800564}
565
Brian Carlstromc1409452014-02-26 14:06:23 -0800566const byte* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000567 Elf32_Word hash = elfhash(symbol_name.c_str());
568 Elf32_Word bucket_index = hash % GetHashBucketNum();
569 Elf32_Word symbol_and_chain_index = GetHashBucket(bucket_index);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800570 while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000571 Elf32_Sym& symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
572 const char* name = GetString(SHT_DYNSYM, symbol.st_name);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800573 if (symbol_name == name) {
574 return base_address_ + symbol.st_value;
575 }
576 symbol_and_chain_index = GetHashChain(symbol_and_chain_index);
577 }
578 return NULL;
579}
580
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000581bool ElfFile::IsSymbolSectionType(Elf32_Word section_type) {
582 return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800583}
584
Brian Carlstromc1409452014-02-26 14:06:23 -0800585Elf32_Word ElfFile::GetSymbolNum(Elf32_Shdr& section_header) const {
586 CHECK(IsSymbolSectionType(section_header.sh_type))
587 << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800588 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
589 return section_header.sh_size / section_header.sh_entsize;
590}
591
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000592Elf32_Sym& ElfFile::GetSymbol(Elf32_Word section_type,
Brian Carlstromc1409452014-02-26 14:06:23 -0800593 Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800594 return *(GetSymbolSectionStart(section_type) + i);
595}
596
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000597ElfFile::SymbolTable** ElfFile::GetSymbolTable(Elf32_Word section_type) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800598 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
599 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000600 case SHT_SYMTAB: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800601 return &symtab_symbol_table_;
602 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000603 case SHT_DYNSYM: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800604 return &dynsym_symbol_table_;
605 }
606 default: {
607 LOG(FATAL) << section_type;
608 return NULL;
609 }
610 }
611}
612
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000613Elf32_Sym* ElfFile::FindSymbolByName(Elf32_Word section_type,
614 const std::string& symbol_name,
615 bool build_map) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800616 CHECK(!program_header_only_) << file_->GetPath();
617 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800618
619 SymbolTable** symbol_table = GetSymbolTable(section_type);
620 if (*symbol_table != NULL || build_map) {
621 if (*symbol_table == NULL) {
622 DCHECK(build_map);
623 *symbol_table = new SymbolTable;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000624 Elf32_Shdr* symbol_section = FindSectionByType(section_type);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800625 CHECK(symbol_section != NULL) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000626 Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800627 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000628 Elf32_Sym& symbol = GetSymbol(section_type, i);
629 unsigned char type = ELF32_ST_TYPE(symbol.st_info);
630 if (type == STT_NOTYPE) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800631 continue;
632 }
633 const char* name = GetString(string_section, symbol.st_name);
634 if (name == NULL) {
635 continue;
636 }
Brian Carlstromc1409452014-02-26 14:06:23 -0800637 std::pair<SymbolTable::iterator, bool> result =
638 (*symbol_table)->insert(std::make_pair(name, &symbol));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800639 if (!result.second) {
640 // If a duplicate, make sure it has the same logical value. Seen on x86.
641 CHECK_EQ(symbol.st_value, result.first->second->st_value);
642 CHECK_EQ(symbol.st_size, result.first->second->st_size);
643 CHECK_EQ(symbol.st_info, result.first->second->st_info);
644 CHECK_EQ(symbol.st_other, result.first->second->st_other);
645 CHECK_EQ(symbol.st_shndx, result.first->second->st_shndx);
646 }
647 }
648 }
649 CHECK(*symbol_table != NULL);
650 SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
651 if (it == (*symbol_table)->end()) {
652 return NULL;
653 }
654 return it->second;
655 }
656
657 // Fall back to linear search
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000658 Elf32_Shdr* symbol_section = FindSectionByType(section_type);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800659 CHECK(symbol_section != NULL) << file_->GetPath();
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000660 Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800661 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000662 Elf32_Sym& symbol = GetSymbol(section_type, i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800663 const char* name = GetString(string_section, symbol.st_name);
664 if (name == NULL) {
665 continue;
666 }
667 if (symbol_name == name) {
668 return &symbol;
669 }
670 }
671 return NULL;
672}
673
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000674Elf32_Addr ElfFile::FindSymbolAddress(Elf32_Word section_type,
Brian Carlstromc1409452014-02-26 14:06:23 -0800675 const std::string& symbol_name,
676 bool build_map) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000677 Elf32_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800678 if (symbol == NULL) {
679 return 0;
680 }
681 return symbol->st_value;
682}
683
Brian Carlstromc1409452014-02-26 14:06:23 -0800684const char* ElfFile::GetString(Elf32_Shdr& string_section, Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800685 CHECK(!program_header_only_) << file_->GetPath();
686 // TODO: remove this static_cast from enum when using -std=gnu++0x
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000687 CHECK_EQ(static_cast<Elf32_Word>(SHT_STRTAB), string_section.sh_type) << file_->GetPath();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800688 CHECK_LT(i, string_section.sh_size) << file_->GetPath();
689 if (i == 0) {
690 return NULL;
691 }
692 byte* strings = Begin() + string_section.sh_offset;
693 byte* string = strings + i;
694 CHECK_LT(string, End()) << file_->GetPath();
Brian Carlstrom265091e2013-01-30 14:08:26 -0800695 return reinterpret_cast<const char*>(string);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800696}
697
Brian Carlstromc1409452014-02-26 14:06:23 -0800698Elf32_Word ElfFile::GetDynamicNum() const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000699 return GetDynamicProgramHeader().p_filesz / sizeof(Elf32_Dyn);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800700}
701
Brian Carlstromc1409452014-02-26 14:06:23 -0800702Elf32_Dyn& ElfFile::GetDynamic(Elf32_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800703 CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
704 return *(GetDynamicSectionStart() + i);
705}
706
Brian Carlstromc1409452014-02-26 14:06:23 -0800707Elf32_Word ElfFile::FindDynamicValueByType(Elf32_Sword type) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000708 for (Elf32_Word i = 0; i < GetDynamicNum(); i++) {
709 Elf32_Dyn& elf_dyn = GetDynamic(i);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800710 if (elf_dyn.d_tag == type) {
711 return elf_dyn.d_un.d_val;
712 }
713 }
714 return 0;
715}
716
Brian Carlstromc1409452014-02-26 14:06:23 -0800717Elf32_Rel* ElfFile::GetRelSectionStart(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000718 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
719 return reinterpret_cast<Elf32_Rel*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800720}
721
Brian Carlstromc1409452014-02-26 14:06:23 -0800722Elf32_Word ElfFile::GetRelNum(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000723 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800724 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
725 return section_header.sh_size / section_header.sh_entsize;
726}
727
Brian Carlstromc1409452014-02-26 14:06:23 -0800728Elf32_Rel& ElfFile::GetRel(Elf32_Shdr& section_header, Elf32_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000729 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800730 CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
731 return *(GetRelSectionStart(section_header) + i);
732}
733
Brian Carlstromc1409452014-02-26 14:06:23 -0800734Elf32_Rela* ElfFile::GetRelaSectionStart(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000735 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
736 return reinterpret_cast<Elf32_Rela*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800737}
738
Brian Carlstromc1409452014-02-26 14:06:23 -0800739Elf32_Word ElfFile::GetRelaNum(Elf32_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000740 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800741 return section_header.sh_size / section_header.sh_entsize;
742}
743
Brian Carlstromc1409452014-02-26 14:06:23 -0800744Elf32_Rela& ElfFile::GetRela(Elf32_Shdr& section_header, Elf32_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000745 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800746 CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
747 return *(GetRelaSectionStart(section_header) + i);
748}
749
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800750// Base on bionic phdr_table_get_load_size
Brian Carlstromc1409452014-02-26 14:06:23 -0800751size_t ElfFile::GetLoadedSize() const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000752 Elf32_Addr min_vaddr = 0xFFFFFFFFu;
753 Elf32_Addr max_vaddr = 0x00000000u;
754 for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
755 Elf32_Phdr& program_header = GetProgramHeader(i);
756 if (program_header.p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800757 continue;
758 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000759 Elf32_Addr begin_vaddr = program_header.p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800760 if (begin_vaddr < min_vaddr) {
761 min_vaddr = begin_vaddr;
762 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000763 Elf32_Addr end_vaddr = program_header.p_vaddr + program_header.p_memsz;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800764 if (end_vaddr > max_vaddr) {
765 max_vaddr = end_vaddr;
766 }
767 }
768 min_vaddr = RoundDown(min_vaddr, kPageSize);
769 max_vaddr = RoundUp(max_vaddr, kPageSize);
770 CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
771 size_t loaded_size = max_vaddr - min_vaddr;
772 return loaded_size;
773}
774
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700775bool ElfFile::Load(bool executable, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800776 CHECK(program_header_only_) << file_->GetPath();
Andreas Gampe91268c12014-04-03 17:50:24 -0700777
778 if (executable) {
779 InstructionSet elf_ISA = kNone;
780 switch (GetHeader().e_machine) {
781 case EM_ARM: {
782 elf_ISA = kArm;
783 break;
784 }
785 case EM_AARCH64: {
786 elf_ISA = kArm64;
787 break;
788 }
789 case EM_386: {
790 elf_ISA = kX86;
791 break;
792 }
793 case EM_X86_64: {
794 elf_ISA = kX86_64;
795 break;
796 }
797 case EM_MIPS: {
798 elf_ISA = kMips;
799 break;
800 }
801 }
802
803 if (elf_ISA != kRuntimeISA) {
804 std::ostringstream oss;
805 oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
806 *error_msg = oss.str();
807 return false;
808 }
809 }
810
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000811 for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
812 Elf32_Phdr& program_header = GetProgramHeader(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800813
814 // Record .dynamic header information for later use
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000815 if (program_header.p_type == PT_DYNAMIC) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800816 dynamic_program_header_ = &program_header;
817 continue;
818 }
819
820 // Not something to load, move on.
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000821 if (program_header.p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800822 continue;
823 }
824
825 // Found something to load.
826
827 // If p_vaddr is zero, it must be the first loadable segment,
828 // since they must be in order. Since it is zero, there isn't a
829 // specific address requested, so first request a contiguous chunk
830 // of required size for all segments, but with no
831 // permissions. We'll then carve that up with the proper
832 // permissions as we load the actual segments. If p_vaddr is
833 // non-zero, the segments require the specific address specified,
834 // which either was specified in the file because we already set
835 // base_address_ after the first zero segment).
Ian Rogerscdfcf372014-01-23 20:38:36 -0800836 int64_t temp_file_length = file_->GetLength();
837 if (temp_file_length < 0) {
838 errno = -temp_file_length;
839 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
840 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
841 return false;
842 }
843 size_t file_length = static_cast<size_t>(temp_file_length);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800844 if (program_header.p_vaddr == 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700845 std::string reservation_name("ElfFile reservation for ");
846 reservation_name += file_->GetPath();
847 UniquePtr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800848 NULL, GetLoadedSize(), PROT_NONE, false,
Brian Carlstromc1409452014-02-26 14:06:23 -0800849 error_msg));
850 if (reserve.get() == nullptr) {
851 *error_msg = StringPrintf("Failed to allocate %s: %s",
852 reservation_name.c_str(), error_msg->c_str());
853 return false;
854 }
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700855 base_address_ = reserve->Begin();
856 segments_.push_back(reserve.release());
857 }
858 // empty segment, nothing to map
859 if (program_header.p_memsz == 0) {
860 continue;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800861 }
862 byte* p_vaddr = base_address_ + program_header.p_vaddr;
863 int prot = 0;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000864 if (executable && ((program_header.p_flags & PF_X) != 0)) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700865 prot |= PROT_EXEC;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800866 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000867 if ((program_header.p_flags & PF_W) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700868 prot |= PROT_WRITE;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800869 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000870 if ((program_header.p_flags & PF_R) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -0700871 prot |= PROT_READ;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800872 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700873 int flags = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800874 if (writable_) {
875 prot |= PROT_WRITE;
876 flags |= MAP_SHARED;
877 } else {
878 flags |= MAP_PRIVATE;
879 }
Brian Carlstrom3a223612013-10-10 17:18:24 -0700880 if (file_length < (program_header.p_offset + program_header.p_memsz)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800881 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700882 "%d of %d bytes: '%s'", file_length, i,
883 program_header.p_offset + program_header.p_memsz,
884 file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700885 return false;
886 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800887 UniquePtr<MemMap> segment(MemMap::MapFileAtAddress(p_vaddr,
888 program_header.p_memsz,
889 prot, flags, file_->Fd(),
890 program_header.p_offset,
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700891 true, // implies MAP_FIXED
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700892 file_->GetPath().c_str(),
893 error_msg));
Brian Carlstromc1409452014-02-26 14:06:23 -0800894 if (segment.get() == nullptr) {
895 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
896 i, file_->GetPath().c_str(), error_msg->c_str());
897 return false;
898 }
899 if (segment->Begin() != p_vaddr) {
900 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
901 "instead mapped to %p",
902 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
903 return false;
904 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800905 segments_.push_back(segment.release());
906 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800907
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800908 // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
909 dynamic_section_start_
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000910 = reinterpret_cast<Elf32_Dyn*>(base_address_ + GetDynamicProgramHeader().p_vaddr);
911 for (Elf32_Word i = 0; i < GetDynamicNum(); i++) {
912 Elf32_Dyn& elf_dyn = GetDynamic(i);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800913 byte* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
914 switch (elf_dyn.d_tag) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000915 case DT_HASH: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800916 if (!ValidPointer(d_ptr)) {
917 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
918 d_ptr, file_->GetPath().c_str());
919 return false;
920 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000921 hash_section_start_ = reinterpret_cast<Elf32_Word*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800922 break;
923 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000924 case DT_STRTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800925 if (!ValidPointer(d_ptr)) {
926 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
927 d_ptr, file_->GetPath().c_str());
928 return false;
929 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800930 dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
931 break;
932 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000933 case DT_SYMTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800934 if (!ValidPointer(d_ptr)) {
935 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
936 d_ptr, file_->GetPath().c_str());
937 return false;
938 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000939 dynsym_section_start_ = reinterpret_cast<Elf32_Sym*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800940 break;
941 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000942 case DT_NULL: {
Brian Carlstromc1409452014-02-26 14:06:23 -0800943 if (GetDynamicNum() != i+1) {
944 *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
945 "expected %d as implied by size of PT_DYNAMIC segment in %s",
946 i + 1, GetDynamicNum(), file_->GetPath().c_str());
947 return false;
948 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800949 break;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800950 }
951 }
952 }
953
Mark Mendellae9fd932014-02-10 16:14:35 -0800954 // Use GDB JIT support to do stack backtrace, etc.
955 if (executable) {
956 GdbJITSupport();
957 }
958
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800959 return true;
960}
961
Brian Carlstromc1409452014-02-26 14:06:23 -0800962bool ElfFile::ValidPointer(const byte* start) const {
963 for (size_t i = 0; i < segments_.size(); ++i) {
964 const MemMap* segment = segments_[i];
965 if (segment->Begin() <= start && start < segment->End()) {
966 return true;
967 }
968 }
969 return false;
970}
971
Mark Mendellae9fd932014-02-10 16:14:35 -0800972static bool check_section_name(ElfFile& file, int section_num, const char *name) {
973 Elf32_Shdr& section_header = file.GetSectionHeader(section_num);
974 const char *section_name = file.GetString(SHT_SYMTAB, section_header.sh_name);
975 return strcmp(name, section_name) == 0;
976}
977
978static void IncrementUint32(byte *p, uint32_t increment) {
979 uint32_t *u = reinterpret_cast<uint32_t *>(p);
980 *u += increment;
981}
982
983static void RoundAndClear(byte *image, uint32_t& offset, int pwr2) {
984 uint32_t mask = pwr2 - 1;
985 while (offset & mask) {
986 image[offset++] = 0;
987 }
988}
989
990// Simple macro to bump a point to a section header to the next one.
991#define BUMP_SHENT(sp) \
992 sp = reinterpret_cast<Elf32_Shdr *> (\
993 reinterpret_cast<byte*>(sp) + elf_hdr.e_shentsize);\
994 offset += elf_hdr.e_shentsize
995
996void ElfFile::GdbJITSupport() {
997 // We only get here if we only are mapping the program header.
998 DCHECK(program_header_only_);
999
1000 // Well, we need the whole file to do this.
1001 std::string error_msg;
1002 UniquePtr<ElfFile> ptr(Open(const_cast<File*>(file_), false, false, &error_msg));
1003 ElfFile& all = *ptr;
1004
1005 // Do we have interesting sections?
1006 // Is this an OAT file with interesting sections?
1007 if (all.GetSectionHeaderNum() != kExpectedSectionsInOATFile) {
1008 return;
1009 }
1010 if (!check_section_name(all, 8, ".debug_info") ||
1011 !check_section_name(all, 9, ".debug_abbrev") ||
1012 !check_section_name(all, 10, ".debug_frame") ||
1013 !check_section_name(all, 11, ".debug_str")) {
1014 return;
1015 }
Ian Rogers1a570662014-03-12 01:02:21 -07001016#ifdef __LP64__
1017 if (true) {
1018 return; // No ELF debug support in 64bit.
1019 }
1020#endif
Kenny Root6243e0e2014-03-03 13:33:48 -08001021 // This is not needed if we have no .text segment.
1022 uint32_t text_start_addr = 0;
1023 for (uint32_t i = 0; i < segments_.size(); i++) {
1024 if (segments_[i]->GetProtect() & PROT_EXEC) {
1025 // We found the .text section.
1026 text_start_addr = PointerToLowMemUInt32(segments_[i]->Begin());
1027 break;
1028 }
1029 }
1030 if (text_start_addr == 0U) {
1031 return;
1032 }
1033
Mark Mendellae9fd932014-02-10 16:14:35 -08001034 // Okay, we are good enough. Fake up an ELF image and tell GDB about it.
1035 // We need some extra space for the debug and string sections, the ELF header, and the
1036 // section header.
1037 uint32_t needed_size = KB;
1038
1039 for (Elf32_Word i = 1; i < all.GetSectionHeaderNum(); i++) {
1040 Elf32_Shdr& section_header = all.GetSectionHeader(i);
1041 if (section_header.sh_addr == 0 && section_header.sh_type != SHT_DYNSYM) {
1042 // Debug section: we need it.
1043 needed_size += section_header.sh_size;
1044 } else if (section_header.sh_type == SHT_STRTAB &&
1045 strcmp(".shstrtab",
1046 all.GetString(SHT_SYMTAB, section_header.sh_name)) == 0) {
1047 // We also need the shared string table.
1048 needed_size += section_header.sh_size;
1049
1050 // We also need the extra strings .symtab\0.strtab\0
1051 needed_size += 16;
1052 }
1053 }
1054
1055 // Start creating our image.
1056 jit_elf_image_ = new byte[needed_size];
1057
1058 // Create the Elf Header by copying the old one
1059 Elf32_Ehdr& elf_hdr =
1060 *reinterpret_cast<Elf32_Ehdr*>(jit_elf_image_);
1061
1062 elf_hdr = all.GetHeader();
1063 elf_hdr.e_entry = 0;
1064 elf_hdr.e_phoff = 0;
1065 elf_hdr.e_phnum = 0;
1066 elf_hdr.e_phentsize = 0;
1067 elf_hdr.e_type = ET_EXEC;
1068
1069 uint32_t offset = sizeof(Elf32_Ehdr);
1070
1071 // Copy the debug sections and string table.
1072 uint32_t debug_offsets[kExpectedSectionsInOATFile];
1073 memset(debug_offsets, '\0', sizeof debug_offsets);
1074 Elf32_Shdr *text_header = nullptr;
1075 int extra_shstrtab_entries = -1;
1076 int text_section_index = -1;
1077 int section_index = 1;
1078 for (Elf32_Word i = 1; i < kExpectedSectionsInOATFile; i++) {
1079 Elf32_Shdr& section_header = all.GetSectionHeader(i);
1080 // Round up to multiple of 4, ensuring zero fill.
1081 RoundAndClear(jit_elf_image_, offset, 4);
1082 if (section_header.sh_addr == 0 && section_header.sh_type != SHT_DYNSYM) {
1083 // Debug section: we need it. Unfortunately, it wasn't mapped in.
1084 debug_offsets[i] = offset;
1085 // Read it from the file.
1086 lseek(file_->Fd(), section_header.sh_offset, SEEK_SET);
1087 read(file_->Fd(), jit_elf_image_ + offset, section_header.sh_size);
1088 offset += section_header.sh_size;
1089 section_index++;
1090 offset += 16;
1091 } else if (section_header.sh_type == SHT_STRTAB &&
1092 strcmp(".shstrtab",
1093 all.GetString(SHT_SYMTAB, section_header.sh_name)) == 0) {
1094 // We also need the shared string table.
1095 debug_offsets[i] = offset;
1096 // Read it from the file.
1097 lseek(file_->Fd(), section_header.sh_offset, SEEK_SET);
1098 read(file_->Fd(), jit_elf_image_ + offset, section_header.sh_size);
1099 offset += section_header.sh_size;
1100 // We also need the extra strings .symtab\0.strtab\0
1101 extra_shstrtab_entries = section_header.sh_size;
1102 memcpy(jit_elf_image_+offset, ".symtab\0.strtab\0", 16);
1103 offset += 16;
1104 section_index++;
1105 } else if (section_header.sh_flags & SHF_EXECINSTR) {
1106 DCHECK(strcmp(".text", all.GetString(SHT_SYMTAB,
1107 section_header.sh_name)) == 0);
1108 text_header = &section_header;
1109 text_section_index = section_index++;
1110 }
1111 }
1112 DCHECK(text_header != nullptr);
1113 DCHECK_NE(extra_shstrtab_entries, -1);
1114
1115 // We now need to update the addresses for debug_info and debug_frame to get to the
1116 // correct offset within the .text section.
Mark Mendellae9fd932014-02-10 16:14:35 -08001117 byte *p = jit_elf_image_+debug_offsets[8];
1118 byte *end = p + all.GetSectionHeader(8).sh_size;
1119
1120 // For debug_info; patch compilation using low_pc @ offset 13, high_pc at offset 17.
1121 IncrementUint32(p + 13, text_start_addr);
1122 IncrementUint32(p + 17, text_start_addr);
1123
1124 // Now fix the low_pc, high_pc for each method address.
1125 // First method starts at offset 0x15, each subsequent method is 1+3*4 bytes further.
1126 for (p += 0x15; p < end; p += 1 /* attr# */ + 3 * sizeof(uint32_t) /* addresses */) {
1127 IncrementUint32(p + 1 + sizeof(uint32_t), text_start_addr);
1128 IncrementUint32(p + 1 + 2 * sizeof(uint32_t), text_start_addr);
1129 }
1130
1131 // Now we have to handle the debug_frame method start addresses
1132 p = jit_elf_image_+debug_offsets[10];
1133 end = p + all.GetSectionHeader(10).sh_size;
1134
1135 // Skip past the CIE.
1136 p += *reinterpret_cast<uint32_t *>(p) + 4;
1137
1138 // And walk the FDEs.
1139 for (; p < end; p += *reinterpret_cast<uint32_t *>(p) + sizeof(uint32_t)) {
1140 IncrementUint32(p + 2 * sizeof(uint32_t), text_start_addr);
1141 }
1142
1143 // Create the data for the symbol table.
1144 const int kSymbtabAlignment = 16;
1145 RoundAndClear(jit_elf_image_, offset, kSymbtabAlignment);
1146 uint32_t symtab_offset = offset;
1147
1148 // First entry is empty.
1149 memset(jit_elf_image_+offset, 0, sizeof(Elf32_Sym));
1150 offset += sizeof(Elf32_Sym);
1151
1152 // Symbol 1 is the real .text section.
1153 Elf32_Sym& sym_ent = *reinterpret_cast<Elf32_Sym*>(jit_elf_image_+offset);
1154 sym_ent.st_name = 1; /* .text */
1155 sym_ent.st_value = text_start_addr;
1156 sym_ent.st_size = text_header->sh_size;
1157 SetBindingAndType(&sym_ent, STB_LOCAL, STT_SECTION);
1158 sym_ent.st_other = 0;
1159 sym_ent.st_shndx = text_section_index;
1160 offset += sizeof(Elf32_Sym);
1161
1162 // Create the data for the string table.
1163 RoundAndClear(jit_elf_image_, offset, kSymbtabAlignment);
1164 const int kTextStringSize = 7;
1165 uint32_t strtab_offset = offset;
1166 memcpy(jit_elf_image_+offset, "\0.text", kTextStringSize);
1167 offset += kTextStringSize;
1168
1169 // Create the section header table.
1170 // Round up to multiple of kSymbtabAlignment, ensuring zero fill.
1171 RoundAndClear(jit_elf_image_, offset, kSymbtabAlignment);
1172 elf_hdr.e_shoff = offset;
1173 Elf32_Shdr *sp =
1174 reinterpret_cast<Elf32_Shdr *>(jit_elf_image_ + offset);
1175
1176 // Copy the first empty index.
1177 *sp = all.GetSectionHeader(0);
1178 BUMP_SHENT(sp);
1179
1180 elf_hdr.e_shnum = 1;
1181 for (Elf32_Word i = 1; i < kExpectedSectionsInOATFile; i++) {
1182 Elf32_Shdr& section_header = all.GetSectionHeader(i);
1183 if (section_header.sh_addr == 0 && section_header.sh_type != SHT_DYNSYM) {
1184 // Debug section: we need it.
1185 *sp = section_header;
1186 sp->sh_offset = debug_offsets[i];
1187 sp->sh_addr = 0;
1188 elf_hdr.e_shnum++;
1189 BUMP_SHENT(sp);
1190 } else if (section_header.sh_type == SHT_STRTAB &&
1191 strcmp(".shstrtab",
1192 all.GetString(SHT_SYMTAB, section_header.sh_name)) == 0) {
1193 // We also need the shared string table.
1194 *sp = section_header;
1195 sp->sh_offset = debug_offsets[i];
1196 sp->sh_size += 16; /* sizeof ".symtab\0.strtab\0" */
1197 sp->sh_addr = 0;
1198 elf_hdr.e_shstrndx = elf_hdr.e_shnum;
1199 elf_hdr.e_shnum++;
1200 BUMP_SHENT(sp);
1201 }
1202 }
1203
1204 // Add a .text section for the matching code section.
1205 *sp = *text_header;
1206 sp->sh_type = SHT_NOBITS;
1207 sp->sh_offset = 0;
1208 sp->sh_addr = text_start_addr;
1209 elf_hdr.e_shnum++;
1210 BUMP_SHENT(sp);
1211
1212 // .symtab section: Need an empty index and the .text entry
1213 sp->sh_name = extra_shstrtab_entries;
1214 sp->sh_type = SHT_SYMTAB;
1215 sp->sh_flags = 0;
1216 sp->sh_addr = 0;
1217 sp->sh_offset = symtab_offset;
1218 sp->sh_size = 2 * sizeof(Elf32_Sym);
1219 sp->sh_link = elf_hdr.e_shnum + 1; // Link to .strtab section.
1220 sp->sh_info = 0;
1221 sp->sh_addralign = 16;
1222 sp->sh_entsize = sizeof(Elf32_Sym);
1223 elf_hdr.e_shnum++;
1224 BUMP_SHENT(sp);
1225
1226 // .strtab section: Enough for .text\0.
1227 sp->sh_name = extra_shstrtab_entries + 8;
1228 sp->sh_type = SHT_STRTAB;
1229 sp->sh_flags = 0;
1230 sp->sh_addr = 0;
1231 sp->sh_offset = strtab_offset;
1232 sp->sh_size = kTextStringSize;
1233 sp->sh_link = 0;
1234 sp->sh_info = 0;
1235 sp->sh_addralign = 16;
1236 sp->sh_entsize = 0;
1237 elf_hdr.e_shnum++;
1238 BUMP_SHENT(sp);
1239
1240 // We now have enough information to tell GDB about our file.
1241 jit_gdb_entry_ = CreateCodeEntry(jit_elf_image_, offset);
1242}
1243
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001244} // namespace art