elf_file.cc revision 8d31bbd3d6536de12bc20e3d29cfe03fe848f9da
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 "base/logging.h"
20#include "base/stl_util.h"
21#include "utils.h"
22
23namespace art {
24
25ElfFile::ElfFile()
26  : file_(NULL),
27    writable_(false),
28    program_header_only_(false),
29    header_(NULL),
30    base_address_(NULL),
31    program_headers_start_(NULL),
32    section_headers_start_(NULL),
33    dynamic_program_header_(NULL),
34    dynamic_section_start_(NULL),
35    symtab_section_start_(NULL),
36    dynsym_section_start_(NULL),
37    strtab_section_start_(NULL),
38    dynstr_section_start_(NULL),
39    hash_section_start_(NULL),
40    symtab_symbol_table_(NULL),
41    dynsym_symbol_table_(NULL) {}
42
43ElfFile* ElfFile::Open(File* file, bool writable, bool program_header_only,
44                       std::string* error_msg) {
45  UniquePtr<ElfFile> elf_file(new ElfFile());
46  if (!elf_file->Setup(file, writable, program_header_only, error_msg)) {
47    return nullptr;
48  }
49  return elf_file.release();
50}
51
52bool ElfFile::Setup(File* file, bool writable, bool program_header_only, std::string* error_msg) {
53  CHECK(file != NULL);
54  file_ = file;
55  writable_ = writable;
56  program_header_only_ = program_header_only;
57
58  int prot;
59  int flags;
60  if (writable_) {
61    prot = PROT_READ | PROT_WRITE;
62    flags = MAP_SHARED;
63  } else {
64    prot = PROT_READ;
65    flags = MAP_PRIVATE;
66  }
67  int64_t file_length = file_->GetLength();
68  if (file_length < 0) {
69    errno = -file_length;
70    *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
71                              file_->GetPath().c_str(), file_->Fd(), strerror(errno));
72    return false;
73  }
74  if (file_length < sizeof(llvm::ELF::Elf32_Ehdr)) {
75    *error_msg = StringPrintf("File size of %lld bytes not large enough to contain ELF header of "
76                              "%zd bytes: '%s'", file_length, sizeof(llvm::ELF::Elf32_Ehdr),
77                              file_->GetPath().c_str());
78    return false;
79  }
80
81  if (program_header_only) {
82    // first just map ELF header to get program header size information
83    size_t elf_header_size = sizeof(llvm::ELF::Elf32_Ehdr);
84    if (!SetMap(MemMap::MapFile(elf_header_size, prot, flags, file_->Fd(), 0,
85                                file_->GetPath().c_str(), error_msg))) {
86      return false;
87    }
88    // then remap to cover program header
89    size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
90    if (file_length < program_header_size) {
91      *error_msg = StringPrintf("File size of %lld bytes not large enough to contain ELF program "
92                                "header of %zd bytes: '%s'", file_length,
93                                sizeof(llvm::ELF::Elf32_Ehdr), file_->GetPath().c_str());
94      return false;
95    }
96    if (!SetMap(MemMap::MapFile(program_header_size, prot, flags, file_->Fd(), 0,
97                                file_->GetPath().c_str(), error_msg))) {
98      *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
99      return false;
100    }
101  } else {
102    // otherwise map entire file
103    if (!SetMap(MemMap::MapFile(file_->GetLength(), prot, flags, file_->Fd(), 0,
104                                file_->GetPath().c_str(), error_msg))) {
105      *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
106      return false;
107    }
108  }
109
110  // Either way, the program header is relative to the elf header
111  program_headers_start_ = Begin() + GetHeader().e_phoff;
112
113  if (!program_header_only) {
114    // Setup section headers.
115    section_headers_start_ = Begin() + GetHeader().e_shoff;
116
117    // Find .dynamic section info from program header
118    dynamic_program_header_ = FindProgamHeaderByType(llvm::ELF::PT_DYNAMIC);
119    if (dynamic_program_header_ == NULL) {
120      *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
121                                file_->GetPath().c_str());
122      return false;
123    }
124
125    dynamic_section_start_
126        = reinterpret_cast<llvm::ELF::Elf32_Dyn*>(Begin() + GetDynamicProgramHeader().p_offset);
127
128    // Find other sections from section headers
129    for (llvm::ELF::Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
130      llvm::ELF::Elf32_Shdr& section_header = GetSectionHeader(i);
131      byte* section_addr = Begin() + section_header.sh_offset;
132      switch (section_header.sh_type) {
133        case llvm::ELF::SHT_SYMTAB: {
134          symtab_section_start_ = reinterpret_cast<llvm::ELF::Elf32_Sym*>(section_addr);
135          break;
136        }
137        case llvm::ELF::SHT_DYNSYM: {
138          dynsym_section_start_ = reinterpret_cast<llvm::ELF::Elf32_Sym*>(section_addr);
139          break;
140        }
141        case llvm::ELF::SHT_STRTAB: {
142          // TODO: base these off of sh_link from .symtab and .dynsym above
143          if ((section_header.sh_flags & llvm::ELF::SHF_ALLOC) != 0) {
144            dynstr_section_start_ = reinterpret_cast<char*>(section_addr);
145          } else {
146            strtab_section_start_ = reinterpret_cast<char*>(section_addr);
147          }
148          break;
149        }
150        case llvm::ELF::SHT_DYNAMIC: {
151          if (reinterpret_cast<byte*>(dynamic_section_start_) != section_addr) {
152            LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
153                         << file_->GetPath() << ": " << std::hex
154                         << reinterpret_cast<void*>(dynamic_section_start_)
155                         << " != " << reinterpret_cast<void*>(section_addr);
156            return false;
157          }
158          break;
159        }
160        case llvm::ELF::SHT_HASH: {
161          hash_section_start_ = reinterpret_cast<llvm::ELF::Elf32_Word*>(section_addr);
162          break;
163        }
164      }
165    }
166  }
167  return true;
168}
169
170ElfFile::~ElfFile() {
171  STLDeleteElements(&segments_);
172  delete symtab_symbol_table_;
173  delete dynsym_symbol_table_;
174}
175
176bool ElfFile::SetMap(MemMap* map) {
177  if (map == NULL) {
178    // MemMap::Open should have already logged
179    return false;
180  }
181  map_.reset(map);
182  CHECK(map_.get() != NULL) << file_->GetPath();
183  CHECK(map_->Begin() != NULL) << file_->GetPath();
184
185  header_ = reinterpret_cast<llvm::ELF::Elf32_Ehdr*>(map_->Begin());
186  if ((llvm::ELF::ElfMagic[0] != header_->e_ident[llvm::ELF::EI_MAG0])
187      || (llvm::ELF::ElfMagic[1] != header_->e_ident[llvm::ELF::EI_MAG1])
188      || (llvm::ELF::ElfMagic[2] != header_->e_ident[llvm::ELF::EI_MAG2])
189      || (llvm::ELF::ElfMagic[3] != header_->e_ident[llvm::ELF::EI_MAG3])) {
190    LOG(WARNING) << "Failed to find ELF magic in " << file_->GetPath()
191                 << ": " << std::hex
192                 << static_cast<uint8_t>(header_->e_ident[llvm::ELF::EI_MAG0])
193                 << static_cast<uint8_t>(header_->e_ident[llvm::ELF::EI_MAG1])
194                 << static_cast<uint8_t>(header_->e_ident[llvm::ELF::EI_MAG2])
195                 << static_cast<uint8_t>(header_->e_ident[llvm::ELF::EI_MAG3]);
196    return false;
197  }
198
199
200  // TODO: remove these static_casts from enum when using -std=gnu++0x
201  CHECK_EQ(static_cast<unsigned char>(llvm::ELF::ELFCLASS32),  header_->e_ident[llvm::ELF::EI_CLASS])   << file_->GetPath();
202  CHECK_EQ(static_cast<unsigned char>(llvm::ELF::ELFDATA2LSB), header_->e_ident[llvm::ELF::EI_DATA])    << file_->GetPath();
203  CHECK_EQ(static_cast<unsigned char>(llvm::ELF::EV_CURRENT),  header_->e_ident[llvm::ELF::EI_VERSION]) << file_->GetPath();
204
205  // TODO: remove these static_casts from enum when using -std=gnu++0x
206  CHECK_EQ(static_cast<llvm::ELF::Elf32_Half>(llvm::ELF::ET_DYN), header_->e_type) << file_->GetPath();
207  CHECK_EQ(static_cast<llvm::ELF::Elf32_Word>(llvm::ELF::EV_CURRENT), header_->e_version) << file_->GetPath();
208  CHECK_EQ(0U, header_->e_entry) << file_->GetPath();
209
210  CHECK_NE(0U, header_->e_phoff) << file_->GetPath();
211  CHECK_NE(0U, header_->e_shoff) << file_->GetPath();
212  CHECK_NE(0U, header_->e_ehsize) << file_->GetPath();
213  CHECK_NE(0U, header_->e_phentsize) << file_->GetPath();
214  CHECK_NE(0U, header_->e_phnum) << file_->GetPath();
215  CHECK_NE(0U, header_->e_shentsize) << file_->GetPath();
216  CHECK_NE(0U, header_->e_shnum) << file_->GetPath();
217  CHECK_NE(0U, header_->e_shstrndx) << file_->GetPath();
218  CHECK_GE(header_->e_shnum, header_->e_shstrndx) << file_->GetPath();
219  if (!program_header_only_) {
220    CHECK_GT(Size(), header_->e_phoff) << file_->GetPath();
221    CHECK_GT(Size(), header_->e_shoff) << file_->GetPath();
222  }
223  return true;
224}
225
226
227llvm::ELF::Elf32_Ehdr& ElfFile::GetHeader() {
228  CHECK(header_ != NULL);
229  return *header_;
230}
231
232byte* ElfFile::GetProgramHeadersStart() {
233  CHECK(program_headers_start_ != NULL);
234  return program_headers_start_;
235}
236
237byte* ElfFile::GetSectionHeadersStart() {
238  CHECK(section_headers_start_ != NULL);
239  return section_headers_start_;
240}
241
242llvm::ELF::Elf32_Phdr& ElfFile::GetDynamicProgramHeader() {
243  CHECK(dynamic_program_header_ != NULL);
244  return *dynamic_program_header_;
245}
246
247llvm::ELF::Elf32_Dyn* ElfFile::GetDynamicSectionStart() {
248  CHECK(dynamic_section_start_ != NULL);
249  return dynamic_section_start_;
250}
251
252llvm::ELF::Elf32_Sym* ElfFile::GetSymbolSectionStart(llvm::ELF::Elf32_Word section_type) {
253  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
254  llvm::ELF::Elf32_Sym* symbol_section_start;
255  switch (section_type) {
256    case llvm::ELF::SHT_SYMTAB: {
257      symbol_section_start = symtab_section_start_;
258      break;
259    }
260    case llvm::ELF::SHT_DYNSYM: {
261      symbol_section_start = dynsym_section_start_;
262      break;
263    }
264    default: {
265      LOG(FATAL) << section_type;
266      symbol_section_start = NULL;
267    }
268  }
269  CHECK(symbol_section_start != NULL);
270  return symbol_section_start;
271}
272
273const char* ElfFile::GetStringSectionStart(llvm::ELF::Elf32_Word section_type) {
274  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
275  const char* string_section_start;
276  switch (section_type) {
277    case llvm::ELF::SHT_SYMTAB: {
278      string_section_start = strtab_section_start_;
279      break;
280    }
281    case llvm::ELF::SHT_DYNSYM: {
282      string_section_start = dynstr_section_start_;
283      break;
284    }
285    default: {
286      LOG(FATAL) << section_type;
287      string_section_start = NULL;
288    }
289  }
290  CHECK(string_section_start != NULL);
291  return string_section_start;
292}
293
294const char* ElfFile::GetString(llvm::ELF::Elf32_Word section_type, llvm::ELF::Elf32_Word i) {
295  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
296  if (i == 0) {
297    return NULL;
298  }
299  const char* string_section_start = GetStringSectionStart(section_type);
300  const char* string = string_section_start + i;
301  return string;
302}
303
304llvm::ELF::Elf32_Word* ElfFile::GetHashSectionStart() {
305  CHECK(hash_section_start_ != NULL);
306  return hash_section_start_;
307}
308
309llvm::ELF::Elf32_Word ElfFile::GetHashBucketNum() {
310  return GetHashSectionStart()[0];
311}
312
313llvm::ELF::Elf32_Word ElfFile::GetHashChainNum() {
314  return GetHashSectionStart()[1];
315}
316
317llvm::ELF::Elf32_Word ElfFile::GetHashBucket(size_t i) {
318  CHECK_LT(i, GetHashBucketNum());
319  // 0 is nbucket, 1 is nchain
320  return GetHashSectionStart()[2 + i];
321}
322
323llvm::ELF::Elf32_Word ElfFile::GetHashChain(size_t i) {
324  CHECK_LT(i, GetHashChainNum());
325  // 0 is nbucket, 1 is nchain, & chains are after buckets
326  return GetHashSectionStart()[2 + GetHashBucketNum() + i];
327}
328
329llvm::ELF::Elf32_Word ElfFile::GetProgramHeaderNum() {
330  return GetHeader().e_phnum;
331}
332
333llvm::ELF::Elf32_Phdr& ElfFile::GetProgramHeader(llvm::ELF::Elf32_Word i) {
334  CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath();
335  byte* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
336  CHECK_LT(program_header, End()) << file_->GetPath();
337  return *reinterpret_cast<llvm::ELF::Elf32_Phdr*>(program_header);
338}
339
340llvm::ELF::Elf32_Phdr* ElfFile::FindProgamHeaderByType(llvm::ELF::Elf32_Word type) {
341  for (llvm::ELF::Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
342    llvm::ELF::Elf32_Phdr& program_header = GetProgramHeader(i);
343    if (program_header.p_type == type) {
344      return &program_header;
345    }
346  }
347  return NULL;
348}
349
350llvm::ELF::Elf32_Word ElfFile::GetSectionHeaderNum() {
351  return GetHeader().e_shnum;
352}
353
354llvm::ELF::Elf32_Shdr& ElfFile::GetSectionHeader(llvm::ELF::Elf32_Word i) {
355  // Can only access arbitrary sections when we have the whole file, not just program header.
356  // Even if we Load(), it doesn't bring in all the sections.
357  CHECK(!program_header_only_) << file_->GetPath();
358  CHECK_LT(i, GetSectionHeaderNum()) << file_->GetPath();
359  byte* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
360  CHECK_LT(section_header, End()) << file_->GetPath();
361  return *reinterpret_cast<llvm::ELF::Elf32_Shdr*>(section_header);
362}
363
364llvm::ELF::Elf32_Shdr* ElfFile::FindSectionByType(llvm::ELF::Elf32_Word type) {
365  // Can only access arbitrary sections when we have the whole file, not just program header.
366  // We could change this to switch on known types if they were detected during loading.
367  CHECK(!program_header_only_) << file_->GetPath();
368  for (llvm::ELF::Elf32_Word i = 0; i < GetSectionHeaderNum(); i++) {
369    llvm::ELF::Elf32_Shdr& section_header = GetSectionHeader(i);
370    if (section_header.sh_type == type) {
371      return &section_header;
372    }
373  }
374  return NULL;
375}
376
377// from bionic
378static unsigned elfhash(const char *_name) {
379  const unsigned char *name = (const unsigned char *) _name;
380  unsigned h = 0, g;
381
382  while (*name) {
383    h = (h << 4) + *name++;
384    g = h & 0xf0000000;
385    h ^= g;
386    h ^= g >> 24;
387  }
388  return h;
389}
390
391llvm::ELF::Elf32_Shdr& ElfFile::GetSectionNameStringSection() {
392  return GetSectionHeader(GetHeader().e_shstrndx);
393}
394
395byte* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) {
396  llvm::ELF::Elf32_Word hash = elfhash(symbol_name.c_str());
397  llvm::ELF::Elf32_Word bucket_index = hash % GetHashBucketNum();
398  llvm::ELF::Elf32_Word symbol_and_chain_index = GetHashBucket(bucket_index);
399  while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
400    llvm::ELF::Elf32_Sym& symbol = GetSymbol(llvm::ELF::SHT_DYNSYM, symbol_and_chain_index);
401    const char* name = GetString(llvm::ELF::SHT_DYNSYM, symbol.st_name);
402    if (symbol_name == name) {
403      return base_address_ + symbol.st_value;
404    }
405    symbol_and_chain_index = GetHashChain(symbol_and_chain_index);
406  }
407  return NULL;
408}
409
410bool ElfFile::IsSymbolSectionType(llvm::ELF::Elf32_Word section_type) {
411  return ((section_type == llvm::ELF::SHT_SYMTAB) || (section_type == llvm::ELF::SHT_DYNSYM));
412}
413
414llvm::ELF::Elf32_Word ElfFile::GetSymbolNum(llvm::ELF::Elf32_Shdr& section_header) {
415  CHECK(IsSymbolSectionType(section_header.sh_type)) << file_->GetPath() << " " << section_header.sh_type;
416  CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
417  return section_header.sh_size / section_header.sh_entsize;
418}
419
420llvm::ELF::Elf32_Sym& ElfFile::GetSymbol(llvm::ELF::Elf32_Word section_type,
421                                         llvm::ELF::Elf32_Word i) {
422  return *(GetSymbolSectionStart(section_type) + i);
423}
424
425ElfFile::SymbolTable** ElfFile::GetSymbolTable(llvm::ELF::Elf32_Word section_type) {
426  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
427  switch (section_type) {
428    case llvm::ELF::SHT_SYMTAB: {
429      return &symtab_symbol_table_;
430    }
431    case llvm::ELF::SHT_DYNSYM: {
432      return &dynsym_symbol_table_;
433    }
434    default: {
435      LOG(FATAL) << section_type;
436      return NULL;
437    }
438  }
439}
440
441llvm::ELF::Elf32_Sym* ElfFile::FindSymbolByName(llvm::ELF::Elf32_Word section_type,
442                                                const std::string& symbol_name,
443                                                bool build_map) {
444  CHECK(!program_header_only_) << file_->GetPath();
445  CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
446
447  SymbolTable** symbol_table = GetSymbolTable(section_type);
448  if (*symbol_table != NULL || build_map) {
449    if (*symbol_table == NULL) {
450      DCHECK(build_map);
451      *symbol_table = new SymbolTable;
452      llvm::ELF::Elf32_Shdr* symbol_section = FindSectionByType(section_type);
453      CHECK(symbol_section != NULL) << file_->GetPath();
454      llvm::ELF::Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
455      for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
456        llvm::ELF::Elf32_Sym& symbol = GetSymbol(section_type, i);
457        unsigned char type = symbol.getType();
458        if (type == llvm::ELF::STT_NOTYPE) {
459          continue;
460        }
461        const char* name = GetString(string_section, symbol.st_name);
462        if (name == NULL) {
463          continue;
464        }
465        std::pair<SymbolTable::iterator, bool> result = (*symbol_table)->insert(std::make_pair(name, &symbol));
466        if (!result.second) {
467          // If a duplicate, make sure it has the same logical value. Seen on x86.
468          CHECK_EQ(symbol.st_value, result.first->second->st_value);
469          CHECK_EQ(symbol.st_size, result.first->second->st_size);
470          CHECK_EQ(symbol.st_info, result.first->second->st_info);
471          CHECK_EQ(symbol.st_other, result.first->second->st_other);
472          CHECK_EQ(symbol.st_shndx, result.first->second->st_shndx);
473        }
474      }
475    }
476    CHECK(*symbol_table != NULL);
477    SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
478    if (it == (*symbol_table)->end()) {
479      return NULL;
480    }
481    return it->second;
482  }
483
484  // Fall back to linear search
485  llvm::ELF::Elf32_Shdr* symbol_section = FindSectionByType(section_type);
486  CHECK(symbol_section != NULL) << file_->GetPath();
487  llvm::ELF::Elf32_Shdr& string_section = GetSectionHeader(symbol_section->sh_link);
488  for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
489    llvm::ELF::Elf32_Sym& symbol = GetSymbol(section_type, i);
490    const char* name = GetString(string_section, symbol.st_name);
491    if (name == NULL) {
492      continue;
493    }
494    if (symbol_name == name) {
495      return &symbol;
496    }
497  }
498  return NULL;
499}
500
501llvm::ELF::Elf32_Addr ElfFile::FindSymbolAddress(llvm::ELF::Elf32_Word section_type,
502                                                 const std::string& symbol_name,
503                                                 bool build_map) {
504  llvm::ELF::Elf32_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
505  if (symbol == NULL) {
506    return 0;
507  }
508  return symbol->st_value;
509}
510
511const char* ElfFile::GetString(llvm::ELF::Elf32_Shdr& string_section, llvm::ELF::Elf32_Word i) {
512  CHECK(!program_header_only_) << file_->GetPath();
513  // TODO: remove this static_cast from enum when using -std=gnu++0x
514  CHECK_EQ(static_cast<llvm::ELF::Elf32_Word>(llvm::ELF::SHT_STRTAB), string_section.sh_type) << file_->GetPath();
515  CHECK_LT(i, string_section.sh_size) << file_->GetPath();
516  if (i == 0) {
517    return NULL;
518  }
519  byte* strings = Begin() + string_section.sh_offset;
520  byte* string = strings + i;
521  CHECK_LT(string, End()) << file_->GetPath();
522  return reinterpret_cast<const char*>(string);
523}
524
525llvm::ELF::Elf32_Word ElfFile::GetDynamicNum() {
526  return GetDynamicProgramHeader().p_filesz / sizeof(llvm::ELF::Elf32_Dyn);
527}
528
529llvm::ELF::Elf32_Dyn& ElfFile::GetDynamic(llvm::ELF::Elf32_Word i) {
530  CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
531  return *(GetDynamicSectionStart() + i);
532}
533
534llvm::ELF::Elf32_Word ElfFile::FindDynamicValueByType(llvm::ELF::Elf32_Sword type) {
535  for (llvm::ELF::Elf32_Word i = 0; i < GetDynamicNum(); i++) {
536    llvm::ELF::Elf32_Dyn& elf_dyn = GetDynamic(i);
537    if (elf_dyn.d_tag == type) {
538      return elf_dyn.d_un.d_val;
539    }
540  }
541  return 0;
542}
543
544llvm::ELF::Elf32_Rel* ElfFile::GetRelSectionStart(llvm::ELF::Elf32_Shdr& section_header) {
545  CHECK(llvm::ELF::SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
546  return reinterpret_cast<llvm::ELF::Elf32_Rel*>(Begin() + section_header.sh_offset);
547}
548
549llvm::ELF::Elf32_Word ElfFile::GetRelNum(llvm::ELF::Elf32_Shdr& section_header) {
550  CHECK(llvm::ELF::SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
551  CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
552  return section_header.sh_size / section_header.sh_entsize;
553}
554
555llvm::ELF::Elf32_Rel& ElfFile::GetRel(llvm::ELF::Elf32_Shdr& section_header, llvm::ELF::Elf32_Word i) {
556  CHECK(llvm::ELF::SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
557  CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
558  return *(GetRelSectionStart(section_header) + i);
559}
560
561llvm::ELF::Elf32_Rela* ElfFile::GetRelaSectionStart(llvm::ELF::Elf32_Shdr& section_header) {
562  CHECK(llvm::ELF::SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
563  return reinterpret_cast<llvm::ELF::Elf32_Rela*>(Begin() + section_header.sh_offset);
564}
565
566llvm::ELF::Elf32_Word ElfFile::GetRelaNum(llvm::ELF::Elf32_Shdr& section_header) {
567  CHECK(llvm::ELF::SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
568  return section_header.sh_size / section_header.sh_entsize;
569}
570
571llvm::ELF::Elf32_Rela& ElfFile::GetRela(llvm::ELF::Elf32_Shdr& section_header,
572                                        llvm::ELF::Elf32_Word i) {
573  CHECK(llvm::ELF::SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
574  CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
575  return *(GetRelaSectionStart(section_header) + i);
576}
577
578// Base on bionic phdr_table_get_load_size
579size_t ElfFile::GetLoadedSize() {
580  llvm::ELF::Elf32_Addr min_vaddr = 0xFFFFFFFFu;
581  llvm::ELF::Elf32_Addr max_vaddr = 0x00000000u;
582  for (llvm::ELF::Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
583    llvm::ELF::Elf32_Phdr& program_header = GetProgramHeader(i);
584    if (program_header.p_type != llvm::ELF::PT_LOAD) {
585      continue;
586    }
587    llvm::ELF::Elf32_Addr begin_vaddr = program_header.p_vaddr;
588    if (begin_vaddr < min_vaddr) {
589       min_vaddr = begin_vaddr;
590    }
591    llvm::ELF::Elf32_Addr end_vaddr = program_header.p_vaddr + program_header.p_memsz;
592    if (end_vaddr > max_vaddr) {
593      max_vaddr = end_vaddr;
594    }
595  }
596  min_vaddr = RoundDown(min_vaddr, kPageSize);
597  max_vaddr = RoundUp(max_vaddr, kPageSize);
598  CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
599  size_t loaded_size = max_vaddr - min_vaddr;
600  return loaded_size;
601}
602
603bool ElfFile::Load(bool executable, std::string* error_msg) {
604  // TODO: actually return false error
605  CHECK(program_header_only_) << file_->GetPath();
606  for (llvm::ELF::Elf32_Word i = 0; i < GetProgramHeaderNum(); i++) {
607    llvm::ELF::Elf32_Phdr& program_header = GetProgramHeader(i);
608
609    // Record .dynamic header information for later use
610    if (program_header.p_type == llvm::ELF::PT_DYNAMIC) {
611      dynamic_program_header_ = &program_header;
612      continue;
613    }
614
615    // Not something to load, move on.
616    if (program_header.p_type != llvm::ELF::PT_LOAD) {
617      continue;
618    }
619
620    // Found something to load.
621
622    // If p_vaddr is zero, it must be the first loadable segment,
623    // since they must be in order.  Since it is zero, there isn't a
624    // specific address requested, so first request a contiguous chunk
625    // of required size for all segments, but with no
626    // permissions. We'll then carve that up with the proper
627    // permissions as we load the actual segments. If p_vaddr is
628    // non-zero, the segments require the specific address specified,
629    // which either was specified in the file because we already set
630    // base_address_ after the first zero segment).
631    int64_t file_length = file_->GetLength();
632    if (program_header.p_vaddr == 0) {
633      std::string reservation_name("ElfFile reservation for ");
634      reservation_name += file_->GetPath();
635      std::string error_msg;
636      UniquePtr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
637                                                     NULL, GetLoadedSize(), PROT_NONE, &error_msg));
638      CHECK(reserve.get() != NULL) << file_->GetPath() << ": " << error_msg;
639      base_address_ = reserve->Begin();
640      segments_.push_back(reserve.release());
641    }
642    // empty segment, nothing to map
643    if (program_header.p_memsz == 0) {
644      continue;
645    }
646    byte* p_vaddr = base_address_ + program_header.p_vaddr;
647    int prot = 0;
648    if (executable && ((program_header.p_flags & llvm::ELF::PF_X) != 0)) {
649      prot |= PROT_EXEC;
650    }
651    if ((program_header.p_flags & llvm::ELF::PF_W) != 0) {
652      prot |= PROT_WRITE;
653    }
654    if ((program_header.p_flags & llvm::ELF::PF_R) != 0) {
655      prot |= PROT_READ;
656    }
657    int flags = MAP_FIXED;
658    if (writable_) {
659      prot |= PROT_WRITE;
660      flags |= MAP_SHARED;
661    } else {
662      flags |= MAP_PRIVATE;
663    }
664    if (file_length < (program_header.p_offset + program_header.p_memsz)) {
665      *error_msg = StringPrintf("File size of %lld bytes not large enough to contain ELF segment "
666                                "%d of %d bytes: '%s'", file_length, i,
667                                program_header.p_offset + program_header.p_memsz,
668                                file_->GetPath().c_str());
669      return false;
670    }
671    UniquePtr<MemMap> segment(MemMap::MapFileAtAddress(p_vaddr,
672                                                       program_header.p_memsz,
673                                                       prot, flags, file_->Fd(),
674                                                       program_header.p_offset,
675                                                       true,
676                                                       file_->GetPath().c_str(),
677                                                       error_msg));
678    CHECK(segment.get() != nullptr) << *error_msg;
679    CHECK_EQ(segment->Begin(), p_vaddr) << file_->GetPath();
680    segments_.push_back(segment.release());
681  }
682
683  // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
684  dynamic_section_start_
685      = reinterpret_cast<llvm::ELF::Elf32_Dyn*>(base_address_ + GetDynamicProgramHeader().p_vaddr);
686  for (llvm::ELF::Elf32_Word i = 0; i < GetDynamicNum(); i++) {
687    llvm::ELF::Elf32_Dyn& elf_dyn = GetDynamic(i);
688    byte* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
689    switch (elf_dyn.d_tag) {
690      case llvm::ELF::DT_HASH: {
691        hash_section_start_ = reinterpret_cast<llvm::ELF::Elf32_Word*>(d_ptr);
692        break;
693      }
694      case llvm::ELF::DT_STRTAB: {
695        dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
696        break;
697      }
698      case llvm::ELF::DT_SYMTAB: {
699        dynsym_section_start_ = reinterpret_cast<llvm::ELF::Elf32_Sym*>(d_ptr);
700        break;
701      }
702      case llvm::ELF::DT_NULL: {
703        CHECK_EQ(GetDynamicNum(), i+1);
704        break;
705      }
706    }
707  }
708
709  return true;
710}
711
712}  // namespace art
713