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