elf_file.cc revision ac304133ab4b988777bcc5ad12257cbb99c3871e
1/*
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
19#include <sys/types.h>
20#include <unistd.h>
21
22#include "base/logging.h"
23#include "base/stringprintf.h"
24#include "base/stl_util.h"
25#include "dwarf.h"
26#include "leb128.h"
27#include "utils.h"
28#include "instruction_set.h"
29
30namespace art {
31
32// -------------------------------------------------------------------
33// Binary GDB JIT Interface as described in
34//   http://sourceware.org/gdb/onlinedocs/gdb/Declarations.html
35extern "C" {
36  typedef enum {
37    JIT_NOACTION = 0,
38    JIT_REGISTER_FN,
39    JIT_UNREGISTER_FN
40  } JITAction;
41
42  struct JITCodeEntry {
43    JITCodeEntry* next_;
44    JITCodeEntry* prev_;
45    const byte *symfile_addr_;
46    uint64_t symfile_size_;
47  };
48
49  struct JITDescriptor {
50    uint32_t version_;
51    uint32_t action_flag_;
52    JITCodeEntry* relevant_entry_;
53    JITCodeEntry* first_entry_;
54  };
55
56  // GDB will place breakpoint into this function.
57  // To prevent GCC from inlining or removing it we place noinline attribute
58  // and inline assembler statement inside.
59  void __attribute__((noinline)) __jit_debug_register_code() {
60    __asm__("");
61  }
62
63  // GDB will inspect contents of this descriptor.
64  // Static initialization is necessary to prevent GDB from seeing
65  // uninitialized descriptor.
66  JITDescriptor __jit_debug_descriptor = { 1, JIT_NOACTION, nullptr, nullptr };
67}
68
69
70static JITCodeEntry* CreateCodeEntry(const byte *symfile_addr,
71                                     uintptr_t symfile_size) {
72  JITCodeEntry* entry = new JITCodeEntry;
73  entry->symfile_addr_ = symfile_addr;
74  entry->symfile_size_ = symfile_size;
75  entry->prev_ = nullptr;
76
77  // TODO: Do we need a lock here?
78  entry->next_ = __jit_debug_descriptor.first_entry_;
79  if (entry->next_ != nullptr) {
80    entry->next_->prev_ = entry;
81  }
82  __jit_debug_descriptor.first_entry_ = entry;
83  __jit_debug_descriptor.relevant_entry_ = entry;
84
85  __jit_debug_descriptor.action_flag_ = JIT_REGISTER_FN;
86  __jit_debug_register_code();
87  return entry;
88}
89
90
91static void UnregisterCodeEntry(JITCodeEntry* entry) {
92  // TODO: Do we need a lock here?
93  if (entry->prev_ != nullptr) {
94    entry->prev_->next_ = entry->next_;
95  } else {
96    __jit_debug_descriptor.first_entry_ = entry->next_;
97  }
98
99  if (entry->next_ != nullptr) {
100    entry->next_->prev_ = entry->prev_;
101  }
102
103  __jit_debug_descriptor.relevant_entry_ = entry;
104  __jit_debug_descriptor.action_flag_ = JIT_UNREGISTER_FN;
105  __jit_debug_register_code();
106  delete entry;
107}
108
109ElfFile::ElfFile(File* file, bool writable, bool program_header_only)
110  : file_(file),
111    writable_(writable),
112    program_header_only_(program_header_only),
113    header_(nullptr),
114    base_address_(nullptr),
115    program_headers_start_(nullptr),
116    section_headers_start_(nullptr),
117    dynamic_program_header_(nullptr),
118    dynamic_section_start_(nullptr),
119    symtab_section_start_(nullptr),
120    dynsym_section_start_(nullptr),
121    strtab_section_start_(nullptr),
122    dynstr_section_start_(nullptr),
123    hash_section_start_(nullptr),
124    symtab_symbol_table_(nullptr),
125    dynsym_symbol_table_(nullptr),
126    jit_elf_image_(nullptr),
127    jit_gdb_entry_(nullptr) {
128  CHECK(file != nullptr);
129}
130
131ElfFile* ElfFile::Open(File* file, bool writable, bool program_header_only,
132                       std::string* error_msg) {
133  std::unique_ptr<ElfFile> elf_file(new ElfFile(file, writable, program_header_only));
134  int prot;
135  int flags;
136  if (writable) {
137    prot = PROT_READ | PROT_WRITE;
138    flags = MAP_SHARED;
139  } else {
140    prot = PROT_READ;
141    flags = MAP_PRIVATE;
142  }
143  if (!elf_file->Setup(prot, flags, error_msg)) {
144    return nullptr;
145  }
146  return elf_file.release();
147}
148
149ElfFile* ElfFile::Open(File* file, int prot, int flags, std::string* error_msg) {
150  std::unique_ptr<ElfFile> elf_file(new ElfFile(file, (prot & PROT_WRITE) == PROT_WRITE, false));
151  if (!elf_file->Setup(prot, flags, error_msg)) {
152    return nullptr;
153  }
154  return elf_file.release();
155}
156
157bool ElfFile::Setup(int prot, int flags, std::string* error_msg) {
158  int64_t temp_file_length = file_->GetLength();
159  if (temp_file_length < 0) {
160    errno = -temp_file_length;
161    *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
162                              file_->GetPath().c_str(), file_->Fd(), strerror(errno));
163    return false;
164  }
165  size_t file_length = static_cast<size_t>(temp_file_length);
166  if (file_length < sizeof(Elf32_Ehdr)) {
167    *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
168                              "%zd bytes: '%s'", file_length, sizeof(Elf32_Ehdr),
169                              file_->GetPath().c_str());
170    return false;
171  }
172
173  if (program_header_only_) {
174    // first just map ELF header to get program header size information
175    size_t elf_header_size = sizeof(Elf32_Ehdr);
176    if (!SetMap(MemMap::MapFile(elf_header_size, prot, flags, file_->Fd(), 0,
177                                file_->GetPath().c_str(), error_msg),
178                error_msg)) {
179      return false;
180    }
181    // then remap to cover program header
182    size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
183    if (file_length < program_header_size) {
184      *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
185                                "header of %zd bytes: '%s'", file_length,
186                                sizeof(Elf32_Ehdr), file_->GetPath().c_str());
187      return false;
188    }
189    if (!SetMap(MemMap::MapFile(program_header_size, prot, flags, file_->Fd(), 0,
190                                file_->GetPath().c_str(), error_msg),
191                error_msg)) {
192      *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
193      return false;
194    }
195  } else {
196    // otherwise map entire file
197    if (!SetMap(MemMap::MapFile(file_->GetLength(), prot, flags, file_->Fd(), 0,
198                                file_->GetPath().c_str(), error_msg),
199                error_msg)) {
200      *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
201      return false;
202    }
203  }
204
205  // Either way, the program header is relative to the elf header
206  program_headers_start_ = Begin() + GetHeader().e_phoff;
207
208  if (!program_header_only_) {
209    // Setup section headers.
210    section_headers_start_ = Begin() + GetHeader().e_shoff;
211
212    // Find .dynamic section info from program header
213    dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
214    if (dynamic_program_header_ == nullptr) {
215      *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
216                                file_->GetPath().c_str());
217      return false;
218    }
219
220    dynamic_section_start_
221        = reinterpret_cast<Elf32_Dyn*>(Begin() + GetDynamicProgramHeader().p_offset);
222
223    // Find other sections from section headers
224    for (Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
225      Elf32_Shdr& section_header = GetSectionHeader(i);
226      byte* section_addr = Begin() + section_header.sh_offset;
227      switch (section_header.sh_type) {
228        case SHT_SYMTAB: {
229          symtab_section_start_ = reinterpret_cast<Elf32_Sym*>(section_addr);
230          break;
231        }
232        case SHT_DYNSYM: {
233          dynsym_section_start_ = reinterpret_cast<Elf32_Sym*>(section_addr);
234          break;
235        }
236        case SHT_STRTAB: {
237          // TODO: base these off of sh_link from .symtab and .dynsym above
238          if ((section_header.sh_flags & SHF_ALLOC) != 0) {
239            dynstr_section_start_ = reinterpret_cast<char*>(section_addr);
240          } else {
241            strtab_section_start_ = reinterpret_cast<char*>(section_addr);
242          }
243          break;
244        }
245        case SHT_DYNAMIC: {
246          if (reinterpret_cast<byte*>(dynamic_section_start_) != section_addr) {
247            LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
248                         << file_->GetPath() << ": " << std::hex
249                         << reinterpret_cast<void*>(dynamic_section_start_)
250                         << " != " << reinterpret_cast<void*>(section_addr);
251            return false;
252          }
253          break;
254        }
255        case SHT_HASH: {
256          hash_section_start_ = reinterpret_cast<Elf32_Word*>(section_addr);
257          break;
258        }
259      }
260    }
261  }
262  return true;
263}
264
265ElfFile::~ElfFile() {
266  STLDeleteElements(&segments_);
267  delete symtab_symbol_table_;
268  delete dynsym_symbol_table_;
269  delete jit_elf_image_;
270  if (jit_gdb_entry_) {
271    UnregisterCodeEntry(jit_gdb_entry_);
272  }
273}
274
275bool ElfFile::SetMap(MemMap* map, std::string* error_msg) {
276  if (map == nullptr) {
277    // MemMap::Open should have already set an error.
278    DCHECK(!error_msg->empty());
279    return false;
280  }
281  map_.reset(map);
282  CHECK(map_.get() != nullptr) << file_->GetPath();
283  CHECK(map_->Begin() != nullptr) << file_->GetPath();
284
285  header_ = reinterpret_cast<Elf32_Ehdr*>(map_->Begin());
286  if ((ELFMAG0 != header_->e_ident[EI_MAG0])
287      || (ELFMAG1 != header_->e_ident[EI_MAG1])
288      || (ELFMAG2 != header_->e_ident[EI_MAG2])
289      || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
290    *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
291                              ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
292                              file_->GetPath().c_str(),
293                              header_->e_ident[EI_MAG0],
294                              header_->e_ident[EI_MAG1],
295                              header_->e_ident[EI_MAG2],
296                              header_->e_ident[EI_MAG3]);
297    return false;
298  }
299  if (ELFCLASS32 != header_->e_ident[EI_CLASS]) {
300    *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
301                              ELFCLASS32,
302                              file_->GetPath().c_str(),
303                              header_->e_ident[EI_CLASS]);
304    return false;
305  }
306  if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
307    *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
308                              ELFDATA2LSB,
309                              file_->GetPath().c_str(),
310                              header_->e_ident[EI_CLASS]);
311    return false;
312  }
313  if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
314    *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
315                              EV_CURRENT,
316                              file_->GetPath().c_str(),
317                              header_->e_ident[EI_CLASS]);
318    return false;
319  }
320  if (ET_DYN != header_->e_type) {
321    *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
322                              ET_DYN,
323                              file_->GetPath().c_str(),
324                              header_->e_type);
325    return false;
326  }
327  if (EV_CURRENT != header_->e_version) {
328    *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
329                              EV_CURRENT,
330                              file_->GetPath().c_str(),
331                              header_->e_version);
332    return false;
333  }
334  if (0 != header_->e_entry) {
335    *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
336                              0,
337                              file_->GetPath().c_str(),
338                              header_->e_entry);
339    return false;
340  }
341  if (0 == header_->e_phoff) {
342    *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
343                              file_->GetPath().c_str());
344    return false;
345  }
346  if (0 == header_->e_shoff) {
347    *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
348                              file_->GetPath().c_str());
349    return false;
350  }
351  if (0 == header_->e_ehsize) {
352    *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
353                              file_->GetPath().c_str());
354    return false;
355  }
356  if (0 == header_->e_phentsize) {
357    *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
358                              file_->GetPath().c_str());
359    return false;
360  }
361  if (0 == header_->e_phnum) {
362    *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
363                              file_->GetPath().c_str());
364    return false;
365  }
366  if (0 == header_->e_shentsize) {
367    *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
368                              file_->GetPath().c_str());
369    return false;
370  }
371  if (0 == header_->e_shnum) {
372    *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
373                              file_->GetPath().c_str());
374    return false;
375  }
376  if (0 == header_->e_shstrndx) {
377    *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
378                              file_->GetPath().c_str());
379    return false;
380  }
381  if (header_->e_shstrndx >= header_->e_shnum) {
382    *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
383                              header_->e_shstrndx,
384                              header_->e_shnum,
385                              file_->GetPath().c_str());
386    return false;
387  }
388
389  if (!program_header_only_) {
390    if (header_->e_phoff >= Size()) {
391      *error_msg = StringPrintf("Failed to find e_phoff value %d less than %zd in %s",
392                                header_->e_phoff,
393                                Size(),
394                                file_->GetPath().c_str());
395      return false;
396    }
397    if (header_->e_shoff >= Size()) {
398      *error_msg = StringPrintf("Failed to find e_shoff value %d less than %zd in %s",
399                                header_->e_shoff,
400                                Size(),
401                                file_->GetPath().c_str());
402      return false;
403    }
404  }
405  return true;
406}
407
408
409Elf32_Ehdr& ElfFile::GetHeader() const {
410  CHECK(header_ != nullptr);
411  return *header_;
412}
413
414byte* ElfFile::GetProgramHeadersStart() const {
415  CHECK(program_headers_start_ != nullptr);
416  return program_headers_start_;
417}
418
419byte* ElfFile::GetSectionHeadersStart() const {
420  CHECK(section_headers_start_ != nullptr);
421  return section_headers_start_;
422}
423
424Elf32_Phdr& ElfFile::GetDynamicProgramHeader() const {
425  CHECK(dynamic_program_header_ != nullptr);
426  return *dynamic_program_header_;
427}
428
429Elf32_Dyn* ElfFile::GetDynamicSectionStart() const {
430  CHECK(dynamic_section_start_ != nullptr);
431  return dynamic_section_start_;
432}
433
434Elf32_Sym* ElfFile::GetSymbolSectionStart(Elf32_Word section_type) const {
435  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
436  Elf32_Sym* symbol_section_start;
437  switch (section_type) {
438    case SHT_SYMTAB: {
439      symbol_section_start = symtab_section_start_;
440      break;
441    }
442    case SHT_DYNSYM: {
443      symbol_section_start = dynsym_section_start_;
444      break;
445    }
446    default: {
447      LOG(FATAL) << section_type;
448      symbol_section_start = nullptr;
449    }
450  }
451  CHECK(symbol_section_start != nullptr);
452  return symbol_section_start;
453}
454
455const char* ElfFile::GetStringSectionStart(Elf32_Word section_type) const {
456  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
457  const char* string_section_start;
458  switch (section_type) {
459    case SHT_SYMTAB: {
460      string_section_start = strtab_section_start_;
461      break;
462    }
463    case SHT_DYNSYM: {
464      string_section_start = dynstr_section_start_;
465      break;
466    }
467    default: {
468      LOG(FATAL) << section_type;
469      string_section_start = nullptr;
470    }
471  }
472  CHECK(string_section_start != nullptr);
473  return string_section_start;
474}
475
476const char* ElfFile::GetString(Elf32_Word section_type, Elf32_Word i) const {
477  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
478  if (i == 0) {
479    return nullptr;
480  }
481  const char* string_section_start = GetStringSectionStart(section_type);
482  const char* string = string_section_start + i;
483  return string;
484}
485
486Elf32_Word* ElfFile::GetHashSectionStart() const {
487  CHECK(hash_section_start_ != nullptr);
488  return hash_section_start_;
489}
490
491Elf32_Word ElfFile::GetHashBucketNum() const {
492  return GetHashSectionStart()[0];
493}
494
495Elf32_Word ElfFile::GetHashChainNum() const {
496  return GetHashSectionStart()[1];
497}
498
499Elf32_Word ElfFile::GetHashBucket(size_t i) const {
500  CHECK_LT(i, GetHashBucketNum());
501  // 0 is nbucket, 1 is nchain
502  return GetHashSectionStart()[2 + i];
503}
504
505Elf32_Word ElfFile::GetHashChain(size_t i) const {
506  CHECK_LT(i, GetHashChainNum());
507  // 0 is nbucket, 1 is nchain, & chains are after buckets
508  return GetHashSectionStart()[2 + GetHashBucketNum() + i];
509}
510
511Elf32_Word ElfFile::GetProgramHeaderNum() const {
512  return GetHeader().e_phnum;
513}
514
515Elf32_Phdr& ElfFile::GetProgramHeader(Elf32_Word i) const {
516  CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath();
517  byte* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
518  CHECK_LT(program_header, End()) << file_->GetPath();
519  return *reinterpret_cast<Elf32_Phdr*>(program_header);
520}
521
522Elf32_Phdr* ElfFile::FindProgamHeaderByType(Elf32_Word type) const {
523  for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
524    Elf32_Phdr& program_header = GetProgramHeader(i);
525    if (program_header.p_type == type) {
526      return &program_header;
527    }
528  }
529  return nullptr;
530}
531
532Elf32_Word ElfFile::GetSectionHeaderNum() const {
533  return GetHeader().e_shnum;
534}
535
536Elf32_Shdr& ElfFile::GetSectionHeader(Elf32_Word i) const {
537  // Can only access arbitrary sections when we have the whole file, not just program header.
538  // Even if we Load(), it doesn't bring in all the sections.
539  CHECK(!program_header_only_) << file_->GetPath();
540  CHECK_LT(i, GetSectionHeaderNum()) << file_->GetPath();
541  byte* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
542  CHECK_LT(section_header, End()) << file_->GetPath();
543  return *reinterpret_cast<Elf32_Shdr*>(section_header);
544}
545
546Elf32_Shdr* ElfFile::FindSectionByType(Elf32_Word type) const {
547  // Can only access arbitrary sections when we have the whole file, not just program header.
548  // We could change this to switch on known types if they were detected during loading.
549  CHECK(!program_header_only_) << file_->GetPath();
550  for (Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
551    Elf32_Shdr& section_header = GetSectionHeader(i);
552    if (section_header.sh_type == type) {
553      return &section_header;
554    }
555  }
556  return nullptr;
557}
558
559// from bionic
560static unsigned elfhash(const char *_name) {
561  const unsigned char *name = (const unsigned char *) _name;
562  unsigned h = 0, g;
563
564  while (*name) {
565    h = (h << 4) + *name++;
566    g = h & 0xf0000000;
567    h ^= g;
568    h ^= g >> 24;
569  }
570  return h;
571}
572
573Elf32_Shdr& ElfFile::GetSectionNameStringSection() const {
574  return GetSectionHeader(GetHeader().e_shstrndx);
575}
576
577const byte* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
578  const Elf32_Sym* sym = FindDynamicSymbol(symbol_name);
579  if (sym != nullptr) {
580    return base_address_ + sym->st_value;
581  } else {
582    return nullptr;
583  }
584}
585
586const Elf32_Sym* ElfFile::FindDynamicSymbol(const std::string& symbol_name) const {
587  Elf32_Word hash = elfhash(symbol_name.c_str());
588  Elf32_Word bucket_index = hash % GetHashBucketNum();
589  Elf32_Word symbol_and_chain_index = GetHashBucket(bucket_index);
590  while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
591    Elf32_Sym& symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
592    const char* name = GetString(SHT_DYNSYM, symbol.st_name);
593    if (symbol_name == name) {
594      return &symbol;
595    }
596    symbol_and_chain_index = GetHashChain(symbol_and_chain_index);
597  }
598  return nullptr;
599}
600
601bool ElfFile::IsSymbolSectionType(Elf32_Word section_type) {
602  return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
603}
604
605Elf32_Word ElfFile::GetSymbolNum(Elf32_Shdr& section_header) const {
606  CHECK(IsSymbolSectionType(section_header.sh_type))
607      << file_->GetPath() << " " << section_header.sh_type;
608  CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
609  return section_header.sh_size / section_header.sh_entsize;
610}
611
612Elf32_Sym& ElfFile::GetSymbol(Elf32_Word section_type,
613                              Elf32_Word i) const {
614  return *(GetSymbolSectionStart(section_type) + i);
615}
616
617ElfFile::SymbolTable** ElfFile::GetSymbolTable(Elf32_Word section_type) {
618  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
619  switch (section_type) {
620    case SHT_SYMTAB: {
621      return &symtab_symbol_table_;
622    }
623    case SHT_DYNSYM: {
624      return &dynsym_symbol_table_;
625    }
626    default: {
627      LOG(FATAL) << section_type;
628      return nullptr;
629    }
630  }
631}
632
633Elf32_Sym* ElfFile::FindSymbolByName(Elf32_Word section_type,
634                                     const std::string& symbol_name,
635                                     bool build_map) {
636  CHECK(!program_header_only_) << file_->GetPath();
637  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
638
639  SymbolTable** symbol_table = GetSymbolTable(section_type);
640  if (*symbol_table != nullptr || build_map) {
641    if (*symbol_table == nullptr) {
642      DCHECK(build_map);
643      *symbol_table = new SymbolTable;
644      Elf32_Shdr* symbol_section = FindSectionByType(section_type);
645      CHECK(symbol_section != nullptr) << file_->GetPath();
646      Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
647      for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
648        Elf32_Sym& symbol = GetSymbol(section_type, i);
649        unsigned char type = ELF32_ST_TYPE(symbol.st_info);
650        if (type == STT_NOTYPE) {
651          continue;
652        }
653        const char* name = GetString(string_section, symbol.st_name);
654        if (name == nullptr) {
655          continue;
656        }
657        std::pair<SymbolTable::iterator, bool> result =
658            (*symbol_table)->insert(std::make_pair(name, &symbol));
659        if (!result.second) {
660          // If a duplicate, make sure it has the same logical value. Seen on x86.
661          CHECK_EQ(symbol.st_value, result.first->second->st_value);
662          CHECK_EQ(symbol.st_size, result.first->second->st_size);
663          CHECK_EQ(symbol.st_info, result.first->second->st_info);
664          CHECK_EQ(symbol.st_other, result.first->second->st_other);
665          CHECK_EQ(symbol.st_shndx, result.first->second->st_shndx);
666        }
667      }
668    }
669    CHECK(*symbol_table != nullptr);
670    SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
671    if (it == (*symbol_table)->end()) {
672      return nullptr;
673    }
674    return it->second;
675  }
676
677  // Fall back to linear search
678  Elf32_Shdr* symbol_section = FindSectionByType(section_type);
679  CHECK(symbol_section != nullptr) << file_->GetPath();
680  Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
681  for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
682    Elf32_Sym& symbol = GetSymbol(section_type, i);
683    const char* name = GetString(string_section, symbol.st_name);
684    if (name == nullptr) {
685      continue;
686    }
687    if (symbol_name == name) {
688      return &symbol;
689    }
690  }
691  return nullptr;
692}
693
694Elf32_Addr ElfFile::FindSymbolAddress(Elf32_Word section_type,
695                                      const std::string& symbol_name,
696                                      bool build_map) {
697  Elf32_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
698  if (symbol == nullptr) {
699    return 0;
700  }
701  return symbol->st_value;
702}
703
704const char* ElfFile::GetString(Elf32_Shdr& string_section, Elf32_Word i) const {
705  CHECK(!program_header_only_) << file_->GetPath();
706  // TODO: remove this static_cast from enum when using -std=gnu++0x
707  CHECK_EQ(static_cast<Elf32_Word>(SHT_STRTAB), string_section.sh_type) << file_->GetPath();
708  CHECK_LT(i, string_section.sh_size) << file_->GetPath();
709  if (i == 0) {
710    return nullptr;
711  }
712  byte* strings = Begin() + string_section.sh_offset;
713  byte* string = strings + i;
714  CHECK_LT(string, End()) << file_->GetPath();
715  return reinterpret_cast<const char*>(string);
716}
717
718Elf32_Word ElfFile::GetDynamicNum() const {
719  return GetDynamicProgramHeader().p_filesz / sizeof(Elf32_Dyn);
720}
721
722Elf32_Dyn& ElfFile::GetDynamic(Elf32_Word i) const {
723  CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
724  return *(GetDynamicSectionStart() + i);
725}
726
727Elf32_Dyn* ElfFile::FindDynamicByType(Elf32_Sword type) const {
728  for (Elf32_Word i = 0; i < GetDynamicNum(); i++) {
729    Elf32_Dyn* dyn = &GetDynamic(i);
730    if (dyn->d_tag == type) {
731      return dyn;
732    }
733  }
734  return NULL;
735}
736
737Elf32_Word ElfFile::FindDynamicValueByType(Elf32_Sword type) const {
738  Elf32_Dyn* dyn = FindDynamicByType(type);
739  if (dyn == NULL) {
740    return 0;
741  } else {
742    return dyn->d_un.d_val;
743  }
744}
745
746Elf32_Rel* ElfFile::GetRelSectionStart(Elf32_Shdr& section_header) const {
747  CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
748  return reinterpret_cast<Elf32_Rel*>(Begin() + section_header.sh_offset);
749}
750
751Elf32_Word ElfFile::GetRelNum(Elf32_Shdr& section_header) const {
752  CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
753  CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
754  return section_header.sh_size / section_header.sh_entsize;
755}
756
757Elf32_Rel& ElfFile::GetRel(Elf32_Shdr& section_header, Elf32_Word i) const {
758  CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
759  CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
760  return *(GetRelSectionStart(section_header) + i);
761}
762
763Elf32_Rela* ElfFile::GetRelaSectionStart(Elf32_Shdr& section_header) const {
764  CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
765  return reinterpret_cast<Elf32_Rela*>(Begin() + section_header.sh_offset);
766}
767
768Elf32_Word ElfFile::GetRelaNum(Elf32_Shdr& section_header) const {
769  CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
770  return section_header.sh_size / section_header.sh_entsize;
771}
772
773Elf32_Rela& ElfFile::GetRela(Elf32_Shdr& section_header, Elf32_Word i) const {
774  CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
775  CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
776  return *(GetRelaSectionStart(section_header) + i);
777}
778
779// Base on bionic phdr_table_get_load_size
780size_t ElfFile::GetLoadedSize() const {
781  Elf32_Addr min_vaddr = 0xFFFFFFFFu;
782  Elf32_Addr max_vaddr = 0x00000000u;
783  for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
784    Elf32_Phdr& program_header = GetProgramHeader(i);
785    if (program_header.p_type != PT_LOAD) {
786      continue;
787    }
788    Elf32_Addr begin_vaddr = program_header.p_vaddr;
789    if (begin_vaddr < min_vaddr) {
790       min_vaddr = begin_vaddr;
791    }
792    Elf32_Addr end_vaddr = program_header.p_vaddr + program_header.p_memsz;
793    if (end_vaddr > max_vaddr) {
794      max_vaddr = end_vaddr;
795    }
796  }
797  min_vaddr = RoundDown(min_vaddr, kPageSize);
798  max_vaddr = RoundUp(max_vaddr, kPageSize);
799  CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
800  size_t loaded_size = max_vaddr - min_vaddr;
801  return loaded_size;
802}
803
804bool ElfFile::Load(bool executable, std::string* error_msg) {
805  CHECK(program_header_only_) << file_->GetPath();
806
807  if (executable) {
808    InstructionSet elf_ISA = kNone;
809    switch (GetHeader().e_machine) {
810      case EM_ARM: {
811        elf_ISA = kArm;
812        break;
813      }
814      case EM_AARCH64: {
815        elf_ISA = kArm64;
816        break;
817      }
818      case EM_386: {
819        elf_ISA = kX86;
820        break;
821      }
822      case EM_X86_64: {
823        elf_ISA = kX86_64;
824        break;
825      }
826      case EM_MIPS: {
827        elf_ISA = kMips;
828        break;
829      }
830    }
831
832    if (elf_ISA != kRuntimeISA) {
833      std::ostringstream oss;
834      oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
835      *error_msg = oss.str();
836      return false;
837    }
838  }
839
840  bool reserved = false;
841  for (Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
842    Elf32_Phdr& program_header = GetProgramHeader(i);
843
844    // Record .dynamic header information for later use
845    if (program_header.p_type == PT_DYNAMIC) {
846      dynamic_program_header_ = &program_header;
847      continue;
848    }
849
850    // Not something to load, move on.
851    if (program_header.p_type != PT_LOAD) {
852      continue;
853    }
854
855    // Found something to load.
856
857    // Before load the actual segments, reserve a contiguous chunk
858    // of required size and address for all segments, but with no
859    // permissions. We'll then carve that up with the proper
860    // permissions as we load the actual segments. If p_vaddr is
861    // non-zero, the segments require the specific address specified,
862    // which either was specified in the file because we already set
863    // base_address_ after the first zero segment).
864    int64_t temp_file_length = file_->GetLength();
865    if (temp_file_length < 0) {
866      errno = -temp_file_length;
867      *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
868                                file_->GetPath().c_str(), file_->Fd(), strerror(errno));
869      return false;
870    }
871    size_t file_length = static_cast<size_t>(temp_file_length);
872    if (!reserved) {
873      byte* reserve_base = ((program_header.p_vaddr != 0) ?
874                            reinterpret_cast<byte*>(program_header.p_vaddr) : nullptr);
875      std::string reservation_name("ElfFile reservation for ");
876      reservation_name += file_->GetPath();
877      std::unique_ptr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
878                                                           reserve_base,
879                                                           GetLoadedSize(), PROT_NONE, false,
880                                                           error_msg));
881      if (reserve.get() == nullptr) {
882        *error_msg = StringPrintf("Failed to allocate %s: %s",
883                                  reservation_name.c_str(), error_msg->c_str());
884        return false;
885      }
886      reserved = true;
887      if (reserve_base == nullptr) {
888        base_address_ = reserve->Begin();
889      }
890      segments_.push_back(reserve.release());
891    }
892    // empty segment, nothing to map
893    if (program_header.p_memsz == 0) {
894      continue;
895    }
896    byte* p_vaddr = base_address_ + program_header.p_vaddr;
897    int prot = 0;
898    if (executable && ((program_header.p_flags & PF_X) != 0)) {
899      prot |= PROT_EXEC;
900    }
901    if ((program_header.p_flags & PF_W) != 0) {
902      prot |= PROT_WRITE;
903    }
904    if ((program_header.p_flags & PF_R) != 0) {
905      prot |= PROT_READ;
906    }
907    int flags = 0;
908    if (writable_) {
909      prot |= PROT_WRITE;
910      flags |= MAP_SHARED;
911    } else {
912      flags |= MAP_PRIVATE;
913    }
914    if (file_length < (program_header.p_offset + program_header.p_memsz)) {
915      *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
916                                "%d of %d bytes: '%s'", file_length, i,
917                                program_header.p_offset + program_header.p_memsz,
918                                file_->GetPath().c_str());
919      return false;
920    }
921    std::unique_ptr<MemMap> segment(MemMap::MapFileAtAddress(p_vaddr,
922                                                       program_header.p_memsz,
923                                                       prot, flags, file_->Fd(),
924                                                       program_header.p_offset,
925                                                       true,  // implies MAP_FIXED
926                                                       file_->GetPath().c_str(),
927                                                       error_msg));
928    if (segment.get() == nullptr) {
929      *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
930                                i, file_->GetPath().c_str(), error_msg->c_str());
931      return false;
932    }
933    if (segment->Begin() != p_vaddr) {
934      *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
935                                "instead mapped to %p",
936                                i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
937      return false;
938    }
939    segments_.push_back(segment.release());
940  }
941
942  // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
943  dynamic_section_start_
944      = reinterpret_cast<Elf32_Dyn*>(base_address_ + GetDynamicProgramHeader().p_vaddr);
945  for (Elf32_Word i = 0; i < GetDynamicNum(); i++) {
946    Elf32_Dyn& elf_dyn = GetDynamic(i);
947    byte* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
948    switch (elf_dyn.d_tag) {
949      case DT_HASH: {
950        if (!ValidPointer(d_ptr)) {
951          *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
952                                    d_ptr, file_->GetPath().c_str());
953          return false;
954        }
955        hash_section_start_ = reinterpret_cast<Elf32_Word*>(d_ptr);
956        break;
957      }
958      case DT_STRTAB: {
959        if (!ValidPointer(d_ptr)) {
960          *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
961                                    d_ptr, file_->GetPath().c_str());
962          return false;
963        }
964        dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
965        break;
966      }
967      case DT_SYMTAB: {
968        if (!ValidPointer(d_ptr)) {
969          *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
970                                    d_ptr, file_->GetPath().c_str());
971          return false;
972        }
973        dynsym_section_start_ = reinterpret_cast<Elf32_Sym*>(d_ptr);
974        break;
975      }
976      case DT_NULL: {
977        if (GetDynamicNum() != i+1) {
978          *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
979                                    "expected %d as implied by size of PT_DYNAMIC segment in %s",
980                                    i + 1, GetDynamicNum(), file_->GetPath().c_str());
981          return false;
982        }
983        break;
984      }
985    }
986  }
987
988  // Use GDB JIT support to do stack backtrace, etc.
989  if (executable) {
990    GdbJITSupport();
991  }
992
993  return true;
994}
995
996bool ElfFile::ValidPointer(const byte* start) const {
997  for (size_t i = 0; i < segments_.size(); ++i) {
998    const MemMap* segment = segments_[i];
999    if (segment->Begin() <= start && start < segment->End()) {
1000      return true;
1001    }
1002  }
1003  return false;
1004}
1005
1006
1007Elf32_Shdr* ElfFile::FindSectionByName(const std::string& name) const {
1008  CHECK(!program_header_only_);
1009  Elf32_Shdr& shstrtab_sec = GetSectionNameStringSection();
1010  for (uint32_t i = 0; i < GetSectionHeaderNum(); i++) {
1011    Elf32_Shdr& shdr = GetSectionHeader(i);
1012    const char* sec_name = GetString(shstrtab_sec, shdr.sh_name);
1013    if (sec_name == nullptr) {
1014      continue;
1015    }
1016    if (name == sec_name) {
1017      return &shdr;
1018    }
1019  }
1020  return nullptr;
1021}
1022
1023struct PACKED(1) FDE {
1024  uint32_t raw_length_;
1025  uint32_t GetLength() {
1026    return raw_length_ + sizeof(raw_length_);
1027  }
1028  uint32_t CIE_pointer;
1029  uint32_t initial_location;
1030  uint32_t address_range;
1031  uint8_t instructions[0];
1032};
1033
1034static FDE* NextFDE(FDE* frame) {
1035  byte* fde_bytes = reinterpret_cast<byte*>(frame);
1036  fde_bytes += frame->GetLength();
1037  return reinterpret_cast<FDE*>(fde_bytes);
1038}
1039
1040static bool IsFDE(FDE* frame) {
1041  // TODO This seems to be the constant everyone uses (for the .debug_frame
1042  // section at least), however we should investigate this further.
1043  const uint32_t kDwarfCIE_id = 0xffffffff;
1044  const uint32_t kReservedLengths[] = {0xffffffff, 0xfffffff0};
1045  return frame->CIE_pointer != kDwarfCIE_id &&
1046      frame->raw_length_ != kReservedLengths[0] && frame->raw_length_ != kReservedLengths[1];
1047}
1048
1049// TODO This only works for 32-bit Elf Files.
1050static bool FixupDebugFrame(uintptr_t text_start, byte* dbg_frame, size_t dbg_frame_size) {
1051  FDE* last_frame = reinterpret_cast<FDE*>(dbg_frame + dbg_frame_size);
1052  FDE* frame = NextFDE(reinterpret_cast<FDE*>(dbg_frame));
1053  for (; frame < last_frame; frame = NextFDE(frame)) {
1054    if (!IsFDE(frame)) {
1055      return false;
1056    }
1057    frame->initial_location += text_start;
1058  }
1059  return true;
1060}
1061
1062struct PACKED(1) DebugInfoHeader {
1063  uint32_t unit_length;  // TODO 32-bit specific size
1064  uint16_t version;
1065  uint32_t debug_abbrev_offset;  // TODO 32-bit specific size
1066  uint8_t  address_size;
1067};
1068
1069// Returns -1 if it is variable length, which we will just disallow for now.
1070static int32_t FormLength(uint32_t att) {
1071  switch (att) {
1072    case DW_FORM_data1:
1073    case DW_FORM_flag:
1074    case DW_FORM_flag_present:
1075    case DW_FORM_ref1:
1076      return 1;
1077
1078    case DW_FORM_data2:
1079    case DW_FORM_ref2:
1080      return 2;
1081
1082    case DW_FORM_addr:        // TODO 32-bit only
1083    case DW_FORM_ref_addr:    // TODO 32-bit only
1084    case DW_FORM_sec_offset:  // TODO 32-bit only
1085    case DW_FORM_strp:        // TODO 32-bit only
1086    case DW_FORM_data4:
1087    case DW_FORM_ref4:
1088      return 4;
1089
1090    case DW_FORM_data8:
1091    case DW_FORM_ref8:
1092    case DW_FORM_ref_sig8:
1093      return 8;
1094
1095    case DW_FORM_block:
1096    case DW_FORM_block1:
1097    case DW_FORM_block2:
1098    case DW_FORM_block4:
1099    case DW_FORM_exprloc:
1100    case DW_FORM_indirect:
1101    case DW_FORM_ref_udata:
1102    case DW_FORM_sdata:
1103    case DW_FORM_string:
1104    case DW_FORM_udata:
1105    default:
1106      return -1;
1107  }
1108}
1109
1110class DebugTag {
1111 public:
1112  const uint32_t index_;
1113  ~DebugTag() {}
1114  // Creates a new tag and moves data pointer up to the start of the next one.
1115  // nullptr means error.
1116  static DebugTag* Create(const byte** data_pointer) {
1117    const byte* data = *data_pointer;
1118    uint32_t index = DecodeUnsignedLeb128(&data);
1119    std::unique_ptr<DebugTag> tag(new DebugTag(index));
1120    tag->size_ = static_cast<uint32_t>(
1121        reinterpret_cast<uintptr_t>(data) - reinterpret_cast<uintptr_t>(*data_pointer));
1122    // skip the abbrev
1123    tag->tag_ = DecodeUnsignedLeb128(&data);
1124    tag->has_child_ = (*data == 0);
1125    data++;
1126    while (true) {
1127      uint32_t attr = DecodeUnsignedLeb128(&data);
1128      uint32_t form = DecodeUnsignedLeb128(&data);
1129      if (attr == 0 && form == 0) {
1130        break;
1131      } else if (attr == 0 || form == 0) {
1132        // Bad abbrev.
1133        return nullptr;
1134      }
1135      int32_t size = FormLength(form);
1136      if (size == -1) {
1137        return nullptr;
1138      }
1139      tag->AddAttribute(attr, static_cast<uint32_t>(size));
1140    }
1141    *data_pointer = data;
1142    return tag.release();
1143  }
1144
1145  uint32_t GetSize() const {
1146    return size_;
1147  }
1148
1149  bool HasChild() {
1150    return has_child_;
1151  }
1152
1153  uint32_t GetTagNumber() {
1154    return tag_;
1155  }
1156
1157  // Gets the offset of a particular attribute in this tag structure.
1158  // Interpretation of the data is left to the consumer. 0 is returned if the
1159  // tag does not contain the attribute.
1160  uint32_t GetOffsetOf(uint32_t dwarf_attribute) const {
1161    auto it = off_map_.find(dwarf_attribute);
1162    if (it == off_map_.end()) {
1163      return 0;
1164    } else {
1165      return it->second;
1166    }
1167  }
1168
1169  // Gets the size of attribute
1170  uint32_t GetAttrSize(uint32_t dwarf_attribute) const {
1171    auto it = size_map_.find(dwarf_attribute);
1172    if (it == size_map_.end()) {
1173      return 0;
1174    } else {
1175      return it->second;
1176    }
1177  }
1178
1179 private:
1180  explicit DebugTag(uint32_t index) : index_(index) {}
1181  void AddAttribute(uint32_t type, uint32_t attr_size) {
1182    off_map_.insert(std::pair<uint32_t, uint32_t>(type, size_));
1183    size_map_.insert(std::pair<uint32_t, uint32_t>(type, attr_size));
1184    size_ += attr_size;
1185  }
1186  std::map<uint32_t, uint32_t> off_map_;
1187  std::map<uint32_t, uint32_t> size_map_;
1188  uint32_t size_;
1189  uint32_t tag_;
1190  bool has_child_;
1191};
1192
1193class DebugAbbrev {
1194 public:
1195  ~DebugAbbrev() {}
1196  static DebugAbbrev* Create(const byte* dbg_abbrev, size_t dbg_abbrev_size) {
1197    std::unique_ptr<DebugAbbrev> abbrev(new DebugAbbrev);
1198    const byte* last = dbg_abbrev + dbg_abbrev_size;
1199    while (dbg_abbrev < last) {
1200      std::unique_ptr<DebugTag> tag(DebugTag::Create(&dbg_abbrev));
1201      if (tag.get() == nullptr) {
1202        return nullptr;
1203      } else {
1204        abbrev->tags_.insert(std::pair<uint32_t, uint32_t>(tag->index_, abbrev->tag_list_.size()));
1205        abbrev->tag_list_.push_back(std::move(tag));
1206      }
1207    }
1208    return abbrev.release();
1209  }
1210
1211  DebugTag* ReadTag(const byte* entry) {
1212    uint32_t tag_num = DecodeUnsignedLeb128(&entry);
1213    auto it = tags_.find(tag_num);
1214    if (it == tags_.end()) {
1215      return nullptr;
1216    } else {
1217      CHECK_GT(tag_list_.size(), it->second);
1218      return tag_list_.at(it->second).get();
1219    }
1220  }
1221
1222 private:
1223  DebugAbbrev() {}
1224  std::map<uint32_t, uint32_t> tags_;
1225  std::vector<std::unique_ptr<DebugTag>> tag_list_;
1226};
1227
1228class DebugInfoIterator {
1229 public:
1230  static DebugInfoIterator* Create(DebugInfoHeader* header, size_t frame_size,
1231                                   DebugAbbrev* abbrev) {
1232    std::unique_ptr<DebugInfoIterator> iter(new DebugInfoIterator(header, frame_size, abbrev));
1233    if (iter->GetCurrentTag() == nullptr) {
1234      return nullptr;
1235    } else {
1236      return iter.release();
1237    }
1238  }
1239  ~DebugInfoIterator() {}
1240
1241  // Moves to the next DIE. Returns false if at last entry.
1242  // TODO Handle variable length attributes.
1243  bool next() {
1244    if (current_entry_ == nullptr || current_tag_ == nullptr) {
1245      return false;
1246    }
1247    current_entry_ += current_tag_->GetSize();
1248    if (current_entry_ >= last_entry_) {
1249      current_entry_ = nullptr;
1250      return false;
1251    }
1252    current_tag_ = abbrev_->ReadTag(current_entry_);
1253    if (current_tag_ == nullptr) {
1254      current_entry_ = nullptr;
1255      return false;
1256    } else {
1257      return true;
1258    }
1259  }
1260
1261  const DebugTag* GetCurrentTag() {
1262    return const_cast<DebugTag*>(current_tag_);
1263  }
1264  byte* GetPointerToField(uint8_t dwarf_field) {
1265    if (current_tag_ == nullptr || current_entry_ == nullptr || current_entry_ >= last_entry_) {
1266      return nullptr;
1267    }
1268    uint32_t off = current_tag_->GetOffsetOf(dwarf_field);
1269    if (off == 0) {
1270      // tag does not have that field.
1271      return nullptr;
1272    } else {
1273      DCHECK_LT(off, current_tag_->GetSize());
1274      return current_entry_ + off;
1275    }
1276  }
1277
1278 private:
1279  DebugInfoIterator(DebugInfoHeader* header, size_t frame_size, DebugAbbrev* abbrev)
1280      : abbrev_(abbrev),
1281        last_entry_(reinterpret_cast<byte*>(header) + frame_size),
1282        current_entry_(reinterpret_cast<byte*>(header) + sizeof(DebugInfoHeader)),
1283        current_tag_(abbrev_->ReadTag(current_entry_)) {}
1284  DebugAbbrev* abbrev_;
1285  byte* last_entry_;
1286  byte* current_entry_;
1287  DebugTag* current_tag_;
1288};
1289
1290static bool FixupDebugInfo(uint32_t text_start, DebugInfoIterator* iter) {
1291  do {
1292    if (iter->GetCurrentTag()->GetAttrSize(DW_AT_low_pc) != sizeof(int32_t) ||
1293        iter->GetCurrentTag()->GetAttrSize(DW_AT_high_pc) != sizeof(int32_t)) {
1294      return false;
1295    }
1296    uint32_t* PC_low = reinterpret_cast<uint32_t*>(iter->GetPointerToField(DW_AT_low_pc));
1297    uint32_t* PC_high = reinterpret_cast<uint32_t*>(iter->GetPointerToField(DW_AT_high_pc));
1298    if (PC_low != nullptr && PC_high != nullptr) {
1299      *PC_low  += text_start;
1300      *PC_high += text_start;
1301    }
1302  } while (iter->next());
1303  return true;
1304}
1305
1306static bool FixupDebugSections(const byte* dbg_abbrev, size_t dbg_abbrev_size,
1307                               uintptr_t text_start,
1308                               byte* dbg_info, size_t dbg_info_size,
1309                               byte* dbg_frame, size_t dbg_frame_size) {
1310  std::unique_ptr<DebugAbbrev> abbrev(DebugAbbrev::Create(dbg_abbrev, dbg_abbrev_size));
1311  if (abbrev.get() == nullptr) {
1312    return false;
1313  }
1314  std::unique_ptr<DebugInfoIterator> iter(
1315      DebugInfoIterator::Create(reinterpret_cast<DebugInfoHeader*>(dbg_info),
1316                                dbg_info_size, abbrev.get()));
1317  if (iter.get() == nullptr) {
1318    return false;
1319  }
1320  return FixupDebugInfo(text_start, iter.get())
1321      && FixupDebugFrame(text_start, dbg_frame, dbg_frame_size);
1322}
1323
1324void ElfFile::GdbJITSupport() {
1325  // We only get here if we only are mapping the program header.
1326  DCHECK(program_header_only_);
1327
1328  // Well, we need the whole file to do this.
1329  std::string error_msg;
1330  // Make it MAP_PRIVATE so we can just give it to gdb if all the necessary
1331  // sections are there.
1332  std::unique_ptr<ElfFile> all_ptr(Open(const_cast<File*>(file_), PROT_READ | PROT_WRITE,
1333                                        MAP_PRIVATE, &error_msg));
1334  if (all_ptr.get() == nullptr) {
1335    return;
1336  }
1337  ElfFile& all = *all_ptr;
1338
1339  // Do we have interesting sections?
1340  const Elf32_Shdr* debug_info = all.FindSectionByName(".debug_info");
1341  const Elf32_Shdr* debug_abbrev = all.FindSectionByName(".debug_abbrev");
1342  const Elf32_Shdr* debug_frame = all.FindSectionByName(".debug_frame");
1343  const Elf32_Shdr* debug_str = all.FindSectionByName(".debug_str");
1344  const Elf32_Shdr* strtab_sec = all.FindSectionByName(".strtab");
1345  const Elf32_Shdr* symtab_sec = all.FindSectionByName(".symtab");
1346  Elf32_Shdr* text_sec = all.FindSectionByName(".text");
1347  if (debug_info == nullptr || debug_abbrev == nullptr || debug_frame == nullptr ||
1348      debug_str == nullptr || text_sec == nullptr || strtab_sec == nullptr ||
1349      symtab_sec == nullptr) {
1350    return;
1351  }
1352#ifdef __LP64__
1353  if (true) {
1354    return;  // No ELF debug support in 64bit.
1355  }
1356#endif
1357  // We need to add in a strtab and symtab to the image.
1358  // all is MAP_PRIVATE so it can be written to freely.
1359  // We also already have strtab and symtab so we are fine there.
1360  Elf32_Ehdr& elf_hdr = all.GetHeader();
1361  elf_hdr.e_entry = 0;
1362  elf_hdr.e_phoff = 0;
1363  elf_hdr.e_phnum = 0;
1364  elf_hdr.e_phentsize = 0;
1365  elf_hdr.e_type = ET_EXEC;
1366
1367  text_sec->sh_type = SHT_NOBITS;
1368  text_sec->sh_offset = 0;
1369
1370  if (!FixupDebugSections(
1371        all.Begin() + debug_abbrev->sh_offset, debug_abbrev->sh_size, text_sec->sh_addr,
1372        all.Begin() + debug_info->sh_offset, debug_info->sh_size,
1373        all.Begin() + debug_frame->sh_offset, debug_frame->sh_size)) {
1374    LOG(ERROR) << "Failed to load GDB data";
1375    return;
1376  }
1377
1378  jit_gdb_entry_ = CreateCodeEntry(all.Begin(), all.Size());
1379  gdb_file_mapping_.reset(all_ptr.release());
1380}
1381
1382}  // namespace art
1383