blob: 52da28bb500d8188358f6c1f159311ae2d3b2ff3 [file] [log] [blame]
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "elf_file.h"
18
Tong Shen62d1ca32014-09-03 17:24:56 -070019#include <inttypes.h>
Nicolas Geoffraya7f198c2014-03-10 11:12:54 +000020#include <sys/types.h>
21#include <unistd.h>
22
Ian Rogersd582fa42014-11-05 23:46:43 -080023#include "arch/instruction_set.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080024#include "base/logging.h"
Ian Rogers576ca0c2014-06-06 15:58:22 -070025#include "base/stringprintf.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080026#include "base/stl_util.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070027#include "base/unix_file/fd_file.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070028#include "elf_file_impl.h"
29#include "elf_utils.h"
Alex Light3470ab42014-06-18 10:35:45 -070030#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080031#include "utils.h"
32
33namespace art {
34
David Srbecky533c2072015-04-22 12:20:22 +010035template <typename ElfTypes>
36ElfFileImpl<ElfTypes>::ElfFileImpl(File* file, bool writable,
37 bool program_header_only,
38 uint8_t* requested_base)
Brian Carlstromc1409452014-02-26 14:06:23 -080039 : file_(file),
40 writable_(writable),
41 program_header_only_(program_header_only),
Alex Light3470ab42014-06-18 10:35:45 -070042 header_(nullptr),
43 base_address_(nullptr),
44 program_headers_start_(nullptr),
45 section_headers_start_(nullptr),
46 dynamic_program_header_(nullptr),
47 dynamic_section_start_(nullptr),
48 symtab_section_start_(nullptr),
49 dynsym_section_start_(nullptr),
50 strtab_section_start_(nullptr),
51 dynstr_section_start_(nullptr),
52 hash_section_start_(nullptr),
53 symtab_symbol_table_(nullptr),
54 dynsym_symbol_table_(nullptr),
Igor Murashkin46774762014-10-22 11:37:02 -070055 requested_base_(requested_base) {
Alex Light3470ab42014-06-18 10:35:45 -070056 CHECK(file != nullptr);
Brian Carlstromc1409452014-02-26 14:06:23 -080057}
Brian Carlstrom700c8d32012-11-05 10:42:02 -080058
David Srbecky533c2072015-04-22 12:20:22 +010059template <typename ElfTypes>
60ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(
61 File* file, bool writable, bool program_header_only,
62 std::string* error_msg, uint8_t* requested_base) {
63 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
64 (file, writable, program_header_only, requested_base));
Brian Carlstrom700c8d32012-11-05 10:42:02 -080065 int prot;
66 int flags;
Alex Light3470ab42014-06-18 10:35:45 -070067 if (writable) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -080068 prot = PROT_READ | PROT_WRITE;
69 flags = MAP_SHARED;
70 } else {
71 prot = PROT_READ;
72 flags = MAP_PRIVATE;
73 }
Alex Light3470ab42014-06-18 10:35:45 -070074 if (!elf_file->Setup(prot, flags, error_msg)) {
75 return nullptr;
76 }
77 return elf_file.release();
78}
79
David Srbecky533c2072015-04-22 12:20:22 +010080template <typename ElfTypes>
81ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(
82 File* file, int prot, int flags, std::string* error_msg) {
83 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
84 (file, (prot & PROT_WRITE) == PROT_WRITE, /*program_header_only*/false,
85 /*requested_base*/nullptr));
Alex Light3470ab42014-06-18 10:35:45 -070086 if (!elf_file->Setup(prot, flags, error_msg)) {
87 return nullptr;
88 }
89 return elf_file.release();
90}
91
David Srbecky533c2072015-04-22 12:20:22 +010092template <typename ElfTypes>
93bool ElfFileImpl<ElfTypes>::Setup(int prot, int flags, std::string* error_msg) {
Ian Rogerscdfcf372014-01-23 20:38:36 -080094 int64_t temp_file_length = file_->GetLength();
95 if (temp_file_length < 0) {
96 errno = -temp_file_length;
Ian Rogers8d31bbd2013-10-13 10:44:14 -070097 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
98 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
Brian Carlstrom265091e2013-01-30 14:08:26 -080099 return false;
100 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800101 size_t file_length = static_cast<size_t>(temp_file_length);
Tong Shen62d1ca32014-09-03 17:24:56 -0700102 if (file_length < sizeof(Elf_Ehdr)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800103 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
Tong Shen62d1ca32014-09-03 17:24:56 -0700104 "%zd bytes: '%s'", file_length, sizeof(Elf_Ehdr),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700105 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800106 return false;
107 }
108
Brian Carlstromc1409452014-02-26 14:06:23 -0800109 if (program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800110 // first just map ELF header to get program header size information
Tong Shen62d1ca32014-09-03 17:24:56 -0700111 size_t elf_header_size = sizeof(Elf_Ehdr);
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800112 if (!SetMap(MemMap::MapFile(elf_header_size,
113 prot,
114 flags,
115 file_->Fd(),
116 0,
117 /*low4_gb*/false,
118 file_->GetPath().c_str(),
119 error_msg),
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800120 error_msg)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800121 return false;
122 }
123 // then remap to cover program header
124 size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
Brian Carlstrom3a223612013-10-10 17:18:24 -0700125 if (file_length < program_header_size) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800126 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700127 "header of %zd bytes: '%s'", file_length,
Tong Shen62d1ca32014-09-03 17:24:56 -0700128 sizeof(Elf_Ehdr), file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700129 return false;
130 }
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800131 if (!SetMap(MemMap::MapFile(program_header_size,
132 prot,
133 flags,
134 file_->Fd(),
135 0,
136 /*low4_gb*/false,
137 file_->GetPath().c_str(),
138 error_msg),
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800139 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700140 *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800141 return false;
142 }
143 } else {
144 // otherwise map entire file
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800145 if (!SetMap(MemMap::MapFile(file_->GetLength(),
146 prot,
147 flags,
148 file_->Fd(),
149 0,
150 /*low4_gb*/false,
151 file_->GetPath().c_str(),
152 error_msg),
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800153 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700154 *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800155 return false;
156 }
157 }
158
Andreas Gampedaab38c2014-09-12 18:38:24 -0700159 if (program_header_only_) {
160 program_headers_start_ = Begin() + GetHeader().e_phoff;
161 } else {
162 if (!CheckAndSet(GetHeader().e_phoff, "program headers", &program_headers_start_, error_msg)) {
163 return false;
164 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800165
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800166 // Setup section headers.
Andreas Gampedaab38c2014-09-12 18:38:24 -0700167 if (!CheckAndSet(GetHeader().e_shoff, "section headers", &section_headers_start_, error_msg)) {
168 return false;
169 }
170
171 // Find shstrtab.
Tong Shen62d1ca32014-09-03 17:24:56 -0700172 Elf_Shdr* shstrtab_section_header = GetSectionNameStringSection();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700173 if (shstrtab_section_header == nullptr) {
174 *error_msg = StringPrintf("Failed to find shstrtab section header in ELF file: '%s'",
175 file_->GetPath().c_str());
176 return false;
177 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800178
179 // Find .dynamic section info from program header
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000180 dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
Alex Light3470ab42014-06-18 10:35:45 -0700181 if (dynamic_program_header_ == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700182 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
183 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800184 return false;
185 }
186
Andreas Gampedaab38c2014-09-12 18:38:24 -0700187 if (!CheckAndSet(GetDynamicProgramHeader().p_offset, "dynamic section",
Ian Rogers13735952014-10-08 12:43:28 -0700188 reinterpret_cast<uint8_t**>(&dynamic_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700189 return false;
190 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800191
192 // Find other sections from section headers
Tong Shen62d1ca32014-09-03 17:24:56 -0700193 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
194 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700195 if (section_header == nullptr) {
196 *error_msg = StringPrintf("Failed to find section header for section %d in ELF file: '%s'",
197 i, file_->GetPath().c_str());
198 return false;
199 }
200 switch (section_header->sh_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000201 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700202 if (!CheckAndSet(section_header->sh_offset, "symtab",
Ian Rogers13735952014-10-08 12:43:28 -0700203 reinterpret_cast<uint8_t**>(&symtab_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700204 return false;
205 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800206 break;
207 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000208 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700209 if (!CheckAndSet(section_header->sh_offset, "dynsym",
Ian Rogers13735952014-10-08 12:43:28 -0700210 reinterpret_cast<uint8_t**>(&dynsym_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700211 return false;
212 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800213 break;
214 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000215 case SHT_STRTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800216 // TODO: base these off of sh_link from .symtab and .dynsym above
Andreas Gampedaab38c2014-09-12 18:38:24 -0700217 if ((section_header->sh_flags & SHF_ALLOC) != 0) {
218 // Check that this is named ".dynstr" and ignore otherwise.
219 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
220 if (strncmp(".dynstr", header_name, 8) == 0) {
221 if (!CheckAndSet(section_header->sh_offset, "dynstr",
Ian Rogers13735952014-10-08 12:43:28 -0700222 reinterpret_cast<uint8_t**>(&dynstr_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700223 return false;
224 }
225 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800226 } else {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700227 // Check that this is named ".strtab" and ignore otherwise.
228 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
229 if (strncmp(".strtab", header_name, 8) == 0) {
230 if (!CheckAndSet(section_header->sh_offset, "strtab",
Ian Rogers13735952014-10-08 12:43:28 -0700231 reinterpret_cast<uint8_t**>(&strtab_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700232 return false;
233 }
234 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800235 }
236 break;
237 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000238 case SHT_DYNAMIC: {
Ian Rogers13735952014-10-08 12:43:28 -0700239 if (reinterpret_cast<uint8_t*>(dynamic_section_start_) !=
Andreas Gampedaab38c2014-09-12 18:38:24 -0700240 Begin() + section_header->sh_offset) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800241 LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
Brian Carlstrom265091e2013-01-30 14:08:26 -0800242 << file_->GetPath() << ": " << std::hex
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800243 << reinterpret_cast<void*>(dynamic_section_start_)
Andreas Gampedaab38c2014-09-12 18:38:24 -0700244 << " != " << reinterpret_cast<void*>(Begin() + section_header->sh_offset);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800245 return false;
246 }
247 break;
248 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000249 case SHT_HASH: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700250 if (!CheckAndSet(section_header->sh_offset, "hash section",
Ian Rogers13735952014-10-08 12:43:28 -0700251 reinterpret_cast<uint8_t**>(&hash_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700252 return false;
253 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800254 break;
255 }
256 }
257 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700258
259 // Check for the existence of some sections.
260 if (!CheckSectionsExist(error_msg)) {
261 return false;
262 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800263 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700264
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800265 return true;
266}
267
David Srbecky533c2072015-04-22 12:20:22 +0100268template <typename ElfTypes>
269ElfFileImpl<ElfTypes>::~ElfFileImpl() {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800270 STLDeleteElements(&segments_);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800271 delete symtab_symbol_table_;
272 delete dynsym_symbol_table_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800273}
274
David Srbecky533c2072015-04-22 12:20:22 +0100275template <typename ElfTypes>
276bool ElfFileImpl<ElfTypes>::CheckAndSet(Elf32_Off offset, const char* label,
277 uint8_t** target, std::string* error_msg) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700278 if (Begin() + offset >= End()) {
279 *error_msg = StringPrintf("Offset %d is out of range for %s in ELF file: '%s'", offset, label,
280 file_->GetPath().c_str());
281 return false;
282 }
283 *target = Begin() + offset;
284 return true;
285}
286
David Srbecky533c2072015-04-22 12:20:22 +0100287template <typename ElfTypes>
288bool ElfFileImpl<ElfTypes>::CheckSectionsLinked(const uint8_t* source,
289 const uint8_t* target) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700290 // Only works in whole-program mode, as we need to iterate over the sections.
291 // Note that we normally can't search by type, as duplicates are allowed for most section types.
292 if (program_header_only_) {
293 return true;
294 }
295
Tong Shen62d1ca32014-09-03 17:24:56 -0700296 Elf_Shdr* source_section = nullptr;
297 Elf_Word target_index = 0;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700298 bool target_found = false;
Tong Shen62d1ca32014-09-03 17:24:56 -0700299 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
300 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700301
302 if (Begin() + section_header->sh_offset == source) {
303 // Found the source.
304 source_section = section_header;
305 if (target_index) {
306 break;
307 }
308 } else if (Begin() + section_header->sh_offset == target) {
309 target_index = i;
310 target_found = true;
311 if (source_section != nullptr) {
312 break;
313 }
314 }
315 }
316
317 return target_found && source_section != nullptr && source_section->sh_link == target_index;
318}
319
David Srbecky533c2072015-04-22 12:20:22 +0100320template <typename ElfTypes>
321bool ElfFileImpl<ElfTypes>::CheckSectionsExist(std::string* error_msg) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700322 if (!program_header_only_) {
323 // If in full mode, need section headers.
324 if (section_headers_start_ == nullptr) {
325 *error_msg = StringPrintf("No section headers in ELF file: '%s'", file_->GetPath().c_str());
326 return false;
327 }
328 }
329
330 // This is redundant, but defensive.
331 if (dynamic_program_header_ == nullptr) {
332 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
333 file_->GetPath().c_str());
334 return false;
335 }
336
337 // Need a dynamic section. This is redundant, but defensive.
338 if (dynamic_section_start_ == nullptr) {
339 *error_msg = StringPrintf("Failed to find dynamic section in ELF file: '%s'",
340 file_->GetPath().c_str());
341 return false;
342 }
343
344 // Symtab validation. These is not really a hard failure, as we are currently not using the
345 // symtab internally, but it's nice to be defensive.
346 if (symtab_section_start_ != nullptr) {
347 // When there's a symtab, there should be a strtab.
348 if (strtab_section_start_ == nullptr) {
349 *error_msg = StringPrintf("No strtab for symtab in ELF file: '%s'", file_->GetPath().c_str());
350 return false;
351 }
352
353 // The symtab should link to the strtab.
Ian Rogers13735952014-10-08 12:43:28 -0700354 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(symtab_section_start_),
355 reinterpret_cast<const uint8_t*>(strtab_section_start_))) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700356 *error_msg = StringPrintf("Symtab is not linked to the strtab in ELF file: '%s'",
357 file_->GetPath().c_str());
358 return false;
359 }
360 }
361
362 // We always need a dynstr & dynsym.
363 if (dynstr_section_start_ == nullptr) {
364 *error_msg = StringPrintf("No dynstr in ELF file: '%s'", file_->GetPath().c_str());
365 return false;
366 }
367 if (dynsym_section_start_ == nullptr) {
368 *error_msg = StringPrintf("No dynsym in ELF file: '%s'", file_->GetPath().c_str());
369 return false;
370 }
371
372 // Need a hash section for dynamic symbol lookup.
373 if (hash_section_start_ == nullptr) {
374 *error_msg = StringPrintf("Failed to find hash section in ELF file: '%s'",
375 file_->GetPath().c_str());
376 return false;
377 }
378
379 // And the hash section should be linking to the dynsym.
Ian Rogers13735952014-10-08 12:43:28 -0700380 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(hash_section_start_),
381 reinterpret_cast<const uint8_t*>(dynsym_section_start_))) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700382 *error_msg = StringPrintf("Hash section is not linked to the dynstr in ELF file: '%s'",
383 file_->GetPath().c_str());
384 return false;
385 }
386
Andreas Gampea696c0a2014-12-10 20:51:45 -0800387 // We'd also like to confirm a shstrtab in program_header_only_ mode (else Open() does this for
388 // us). This is usually the last in an oat file, and a good indicator of whether writing was
389 // successful (or the process crashed and left garbage).
390 if (program_header_only_) {
391 // It might not be mapped, but we can compare against the file size.
392 int64_t offset = static_cast<int64_t>(GetHeader().e_shoff +
393 (GetHeader().e_shstrndx * GetHeader().e_shentsize));
394 if (offset >= file_->GetLength()) {
395 *error_msg = StringPrintf("Shstrtab is not in the mapped ELF file: '%s'",
396 file_->GetPath().c_str());
397 return false;
398 }
399 }
400
Andreas Gampedaab38c2014-09-12 18:38:24 -0700401 return true;
402}
403
David Srbecky533c2072015-04-22 12:20:22 +0100404template <typename ElfTypes>
405bool ElfFileImpl<ElfTypes>::SetMap(MemMap* map, std::string* error_msg) {
Alex Light3470ab42014-06-18 10:35:45 -0700406 if (map == nullptr) {
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800407 // MemMap::Open should have already set an error.
408 DCHECK(!error_msg->empty());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800409 return false;
410 }
411 map_.reset(map);
Alex Light3470ab42014-06-18 10:35:45 -0700412 CHECK(map_.get() != nullptr) << file_->GetPath();
413 CHECK(map_->Begin() != nullptr) << file_->GetPath();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800414
Tong Shen62d1ca32014-09-03 17:24:56 -0700415 header_ = reinterpret_cast<Elf_Ehdr*>(map_->Begin());
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000416 if ((ELFMAG0 != header_->e_ident[EI_MAG0])
417 || (ELFMAG1 != header_->e_ident[EI_MAG1])
418 || (ELFMAG2 != header_->e_ident[EI_MAG2])
419 || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800420 *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
421 ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800422 file_->GetPath().c_str(),
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000423 header_->e_ident[EI_MAG0],
424 header_->e_ident[EI_MAG1],
425 header_->e_ident[EI_MAG2],
426 header_->e_ident[EI_MAG3]);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800427 return false;
428 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700429 uint8_t elf_class = (sizeof(Elf_Addr) == sizeof(Elf64_Addr)) ? ELFCLASS64 : ELFCLASS32;
430 if (elf_class != header_->e_ident[EI_CLASS]) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800431 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
Tong Shen62d1ca32014-09-03 17:24:56 -0700432 elf_class,
Brian Carlstromc1409452014-02-26 14:06:23 -0800433 file_->GetPath().c_str(),
434 header_->e_ident[EI_CLASS]);
435 return false;
436 }
437 if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
438 *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
439 ELFDATA2LSB,
440 file_->GetPath().c_str(),
441 header_->e_ident[EI_CLASS]);
442 return false;
443 }
444 if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
445 *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
446 EV_CURRENT,
447 file_->GetPath().c_str(),
448 header_->e_ident[EI_CLASS]);
449 return false;
450 }
451 if (ET_DYN != header_->e_type) {
452 *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
453 ET_DYN,
454 file_->GetPath().c_str(),
455 header_->e_type);
456 return false;
457 }
458 if (EV_CURRENT != header_->e_version) {
459 *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
460 EV_CURRENT,
461 file_->GetPath().c_str(),
462 header_->e_version);
463 return false;
464 }
465 if (0 != header_->e_entry) {
466 *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
467 0,
468 file_->GetPath().c_str(),
Tong Shen62d1ca32014-09-03 17:24:56 -0700469 static_cast<int32_t>(header_->e_entry));
Brian Carlstromc1409452014-02-26 14:06:23 -0800470 return false;
471 }
472 if (0 == header_->e_phoff) {
473 *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
474 file_->GetPath().c_str());
475 return false;
476 }
477 if (0 == header_->e_shoff) {
478 *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
479 file_->GetPath().c_str());
480 return false;
481 }
482 if (0 == header_->e_ehsize) {
483 *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
484 file_->GetPath().c_str());
485 return false;
486 }
487 if (0 == header_->e_phentsize) {
488 *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
489 file_->GetPath().c_str());
490 return false;
491 }
492 if (0 == header_->e_phnum) {
493 *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
494 file_->GetPath().c_str());
495 return false;
496 }
497 if (0 == header_->e_shentsize) {
498 *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
499 file_->GetPath().c_str());
500 return false;
501 }
502 if (0 == header_->e_shnum) {
503 *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
504 file_->GetPath().c_str());
505 return false;
506 }
507 if (0 == header_->e_shstrndx) {
508 *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
509 file_->GetPath().c_str());
510 return false;
511 }
512 if (header_->e_shstrndx >= header_->e_shnum) {
513 *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
514 header_->e_shstrndx,
515 header_->e_shnum,
516 file_->GetPath().c_str());
517 return false;
518 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800519
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800520 if (!program_header_only_) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800521 if (header_->e_phoff >= Size()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700522 *error_msg = StringPrintf("Failed to find e_phoff value %" PRIu64 " less than %zd in %s",
523 static_cast<uint64_t>(header_->e_phoff),
Brian Carlstromc1409452014-02-26 14:06:23 -0800524 Size(),
525 file_->GetPath().c_str());
526 return false;
527 }
528 if (header_->e_shoff >= Size()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700529 *error_msg = StringPrintf("Failed to find e_shoff value %" PRIu64 " less than %zd in %s",
530 static_cast<uint64_t>(header_->e_shoff),
Brian Carlstromc1409452014-02-26 14:06:23 -0800531 Size(),
532 file_->GetPath().c_str());
533 return false;
534 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800535 }
536 return true;
537}
538
David Srbecky533c2072015-04-22 12:20:22 +0100539template <typename ElfTypes>
540typename ElfTypes::Ehdr& ElfFileImpl<ElfTypes>::GetHeader() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700541 CHECK(header_ != nullptr); // Header has been checked in SetMap. This is a sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800542 return *header_;
543}
544
David Srbecky533c2072015-04-22 12:20:22 +0100545template <typename ElfTypes>
546uint8_t* ElfFileImpl<ElfTypes>::GetProgramHeadersStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700547 CHECK(program_headers_start_ != nullptr); // Header has been set in Setup. This is a sanity
548 // check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800549 return program_headers_start_;
550}
551
David Srbecky533c2072015-04-22 12:20:22 +0100552template <typename ElfTypes>
553uint8_t* ElfFileImpl<ElfTypes>::GetSectionHeadersStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700554 CHECK(!program_header_only_); // Only used in "full" mode.
555 CHECK(section_headers_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800556 return section_headers_start_;
557}
558
David Srbecky533c2072015-04-22 12:20:22 +0100559template <typename ElfTypes>
560typename ElfTypes::Phdr& ElfFileImpl<ElfTypes>::GetDynamicProgramHeader() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700561 CHECK(dynamic_program_header_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800562 return *dynamic_program_header_;
563}
564
David Srbecky533c2072015-04-22 12:20:22 +0100565template <typename ElfTypes>
566typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::GetDynamicSectionStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700567 CHECK(dynamic_section_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800568 return dynamic_section_start_;
569}
570
David Srbecky533c2072015-04-22 12:20:22 +0100571template <typename ElfTypes>
572typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbolSectionStart(
573 Elf_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800574 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800575 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000576 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700577 return symtab_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800578 break;
579 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000580 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700581 return dynsym_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800582 break;
583 }
584 default: {
585 LOG(FATAL) << section_type;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700586 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800587 }
588 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800589}
590
David Srbecky533c2072015-04-22 12:20:22 +0100591template <typename ElfTypes>
592const char* ElfFileImpl<ElfTypes>::GetStringSectionStart(
593 Elf_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800594 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800595 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000596 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700597 return strtab_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800598 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000599 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700600 return dynstr_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800601 }
602 default: {
603 LOG(FATAL) << section_type;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700604 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800605 }
606 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800607}
608
David Srbecky533c2072015-04-22 12:20:22 +0100609template <typename ElfTypes>
610const char* ElfFileImpl<ElfTypes>::GetString(Elf_Word section_type,
611 Elf_Word i) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800612 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
613 if (i == 0) {
Alex Light3470ab42014-06-18 10:35:45 -0700614 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800615 }
616 const char* string_section_start = GetStringSectionStart(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700617 if (string_section_start == nullptr) {
618 return nullptr;
619 }
620 return string_section_start + i;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800621}
622
Andreas Gampedaab38c2014-09-12 18:38:24 -0700623// WARNING: The following methods do not check for an error condition (non-existent hash section).
624// It is the caller's job to do this.
625
David Srbecky533c2072015-04-22 12:20:22 +0100626template <typename ElfTypes>
627typename ElfTypes::Word* ElfFileImpl<ElfTypes>::GetHashSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800628 return hash_section_start_;
629}
630
David Srbecky533c2072015-04-22 12:20:22 +0100631template <typename ElfTypes>
632typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucketNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800633 return GetHashSectionStart()[0];
634}
635
David Srbecky533c2072015-04-22 12:20:22 +0100636template <typename ElfTypes>
637typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChainNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800638 return GetHashSectionStart()[1];
639}
640
David Srbecky533c2072015-04-22 12:20:22 +0100641template <typename ElfTypes>
642typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucket(size_t i, bool* ok) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700643 if (i >= GetHashBucketNum()) {
644 *ok = false;
645 return 0;
646 }
647 *ok = true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800648 // 0 is nbucket, 1 is nchain
649 return GetHashSectionStart()[2 + i];
650}
651
David Srbecky533c2072015-04-22 12:20:22 +0100652template <typename ElfTypes>
653typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChain(size_t i, bool* ok) const {
Yevgeny Roubanacb01382014-11-24 13:40:56 +0600654 if (i >= GetHashChainNum()) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700655 *ok = false;
656 return 0;
657 }
658 *ok = true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800659 // 0 is nbucket, 1 is nchain, & chains are after buckets
660 return GetHashSectionStart()[2 + GetHashBucketNum() + i];
661}
662
David Srbecky533c2072015-04-22 12:20:22 +0100663template <typename ElfTypes>
664typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetProgramHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800665 return GetHeader().e_phnum;
666}
667
David Srbecky533c2072015-04-22 12:20:22 +0100668template <typename ElfTypes>
669typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::GetProgramHeader(Elf_Word i) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700670 CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath(); // Sanity check for caller.
Ian Rogers13735952014-10-08 12:43:28 -0700671 uint8_t* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700672 if (program_header >= End()) {
673 return nullptr; // Failure condition.
674 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700675 return reinterpret_cast<Elf_Phdr*>(program_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800676}
677
David Srbecky533c2072015-04-22 12:20:22 +0100678template <typename ElfTypes>
679typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::FindProgamHeaderByType(Elf_Word type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700680 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
681 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700682 if (program_header->p_type == type) {
683 return program_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800684 }
685 }
Alex Light3470ab42014-06-18 10:35:45 -0700686 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800687}
688
David Srbecky533c2072015-04-22 12:20:22 +0100689template <typename ElfTypes>
690typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSectionHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800691 return GetHeader().e_shnum;
692}
693
David Srbecky533c2072015-04-22 12:20:22 +0100694template <typename ElfTypes>
695typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionHeader(Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800696 // Can only access arbitrary sections when we have the whole file, not just program header.
697 // Even if we Load(), it doesn't bring in all the sections.
698 CHECK(!program_header_only_) << file_->GetPath();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700699 if (i >= GetSectionHeaderNum()) {
700 return nullptr; // Failure condition.
701 }
Ian Rogers13735952014-10-08 12:43:28 -0700702 uint8_t* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700703 if (section_header >= End()) {
704 return nullptr; // Failure condition.
705 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700706 return reinterpret_cast<Elf_Shdr*>(section_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800707}
708
David Srbecky533c2072015-04-22 12:20:22 +0100709template <typename ElfTypes>
710typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByType(Elf_Word type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800711 // Can only access arbitrary sections when we have the whole file, not just program header.
712 // We could change this to switch on known types if they were detected during loading.
713 CHECK(!program_header_only_) << file_->GetPath();
Tong Shen62d1ca32014-09-03 17:24:56 -0700714 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
715 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700716 if (section_header->sh_type == type) {
717 return section_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800718 }
719 }
Alex Light3470ab42014-06-18 10:35:45 -0700720 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800721}
722
723// from bionic
Brian Carlstrom265091e2013-01-30 14:08:26 -0800724static unsigned elfhash(const char *_name) {
725 const unsigned char *name = (const unsigned char *) _name;
726 unsigned h = 0, g;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800727
Brian Carlstromdf629502013-07-17 22:39:56 -0700728 while (*name) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800729 h = (h << 4) + *name++;
730 g = h & 0xf0000000;
731 h ^= g;
732 h ^= g >> 24;
733 }
734 return h;
735}
736
David Srbecky533c2072015-04-22 12:20:22 +0100737template <typename ElfTypes>
738typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionNameStringSection() const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800739 return GetSectionHeader(GetHeader().e_shstrndx);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800740}
741
David Srbecky533c2072015-04-22 12:20:22 +0100742template <typename ElfTypes>
743const uint8_t* ElfFileImpl<ElfTypes>::FindDynamicSymbolAddress(
744 const std::string& symbol_name) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700745 // Check that we have a hash section.
746 if (GetHashSectionStart() == nullptr) {
747 return nullptr; // Failure condition.
748 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700749 const Elf_Sym* sym = FindDynamicSymbol(symbol_name);
Alex Light3470ab42014-06-18 10:35:45 -0700750 if (sym != nullptr) {
Igor Murashkin46774762014-10-22 11:37:02 -0700751 // TODO: we need to change this to calculate base_address_ in ::Open,
752 // otherwise it will be wrongly 0 if ::Load has not yet been called.
Alex Light3470ab42014-06-18 10:35:45 -0700753 return base_address_ + sym->st_value;
754 } else {
755 return nullptr;
756 }
757}
758
Andreas Gampedaab38c2014-09-12 18:38:24 -0700759// WARNING: Only called from FindDynamicSymbolAddress. Elides check for hash section.
David Srbecky533c2072015-04-22 12:20:22 +0100760template <typename ElfTypes>
761const typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindDynamicSymbol(
762 const std::string& symbol_name) const {
Andreas Gampec48b2062014-09-08 23:39:45 -0700763 if (GetHashBucketNum() == 0) {
764 // No dynamic symbols at all.
765 return nullptr;
766 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700767 Elf_Word hash = elfhash(symbol_name.c_str());
768 Elf_Word bucket_index = hash % GetHashBucketNum();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700769 bool ok;
Tong Shen62d1ca32014-09-03 17:24:56 -0700770 Elf_Word symbol_and_chain_index = GetHashBucket(bucket_index, &ok);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700771 if (!ok) {
772 return nullptr;
773 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800774 while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700775 Elf_Sym* symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700776 if (symbol == nullptr) {
777 return nullptr; // Failure condition.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800778 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700779 const char* name = GetString(SHT_DYNSYM, symbol->st_name);
780 if (symbol_name == name) {
781 return symbol;
782 }
783 symbol_and_chain_index = GetHashChain(symbol_and_chain_index, &ok);
784 if (!ok) {
785 return nullptr;
786 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800787 }
Alex Light3470ab42014-06-18 10:35:45 -0700788 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800789}
790
David Srbecky533c2072015-04-22 12:20:22 +0100791template <typename ElfTypes>
792bool ElfFileImpl<ElfTypes>::IsSymbolSectionType(Elf_Word section_type) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700793 return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
794}
795
David Srbecky533c2072015-04-22 12:20:22 +0100796template <typename ElfTypes>
797typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSymbolNum(Elf_Shdr& section_header) const {
Brian Carlstromc1409452014-02-26 14:06:23 -0800798 CHECK(IsSymbolSectionType(section_header.sh_type))
799 << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800800 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
801 return section_header.sh_size / section_header.sh_entsize;
802}
803
David Srbecky533c2072015-04-22 12:20:22 +0100804template <typename ElfTypes>
805typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbol(Elf_Word section_type, Elf_Word i) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700806 Elf_Sym* sym_start = GetSymbolSectionStart(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700807 if (sym_start == nullptr) {
808 return nullptr;
809 }
810 return sym_start + i;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800811}
812
David Srbecky533c2072015-04-22 12:20:22 +0100813template <typename ElfTypes>
814typename ElfFileImpl<ElfTypes>::SymbolTable**
815ElfFileImpl<ElfTypes>::GetSymbolTable(Elf_Word section_type) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800816 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
817 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000818 case SHT_SYMTAB: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800819 return &symtab_symbol_table_;
820 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000821 case SHT_DYNSYM: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800822 return &dynsym_symbol_table_;
823 }
824 default: {
825 LOG(FATAL) << section_type;
Alex Light3470ab42014-06-18 10:35:45 -0700826 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800827 }
828 }
829}
830
David Srbecky533c2072015-04-22 12:20:22 +0100831template <typename ElfTypes>
832typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindSymbolByName(
833 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800834 CHECK(!program_header_only_) << file_->GetPath();
835 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800836
837 SymbolTable** symbol_table = GetSymbolTable(section_type);
Alex Light3470ab42014-06-18 10:35:45 -0700838 if (*symbol_table != nullptr || build_map) {
839 if (*symbol_table == nullptr) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800840 DCHECK(build_map);
841 *symbol_table = new SymbolTable;
Tong Shen62d1ca32014-09-03 17:24:56 -0700842 Elf_Shdr* symbol_section = FindSectionByType(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700843 if (symbol_section == nullptr) {
844 return nullptr; // Failure condition.
845 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700846 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700847 if (string_section == nullptr) {
848 return nullptr; // Failure condition.
849 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800850 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700851 Elf_Sym* symbol = GetSymbol(section_type, i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700852 if (symbol == nullptr) {
853 return nullptr; // Failure condition.
854 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700855 unsigned char type = (sizeof(Elf_Addr) == sizeof(Elf64_Addr))
856 ? ELF64_ST_TYPE(symbol->st_info)
857 : ELF32_ST_TYPE(symbol->st_info);
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000858 if (type == STT_NOTYPE) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800859 continue;
860 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700861 const char* name = GetString(*string_section, symbol->st_name);
Alex Light3470ab42014-06-18 10:35:45 -0700862 if (name == nullptr) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800863 continue;
864 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700865 std::pair<typename SymbolTable::iterator, bool> result =
Andreas Gampedaab38c2014-09-12 18:38:24 -0700866 (*symbol_table)->insert(std::make_pair(name, symbol));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800867 if (!result.second) {
868 // If a duplicate, make sure it has the same logical value. Seen on x86.
Andreas Gampedaab38c2014-09-12 18:38:24 -0700869 if ((symbol->st_value != result.first->second->st_value) ||
870 (symbol->st_size != result.first->second->st_size) ||
871 (symbol->st_info != result.first->second->st_info) ||
872 (symbol->st_other != result.first->second->st_other) ||
873 (symbol->st_shndx != result.first->second->st_shndx)) {
874 return nullptr; // Failure condition.
875 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800876 }
877 }
878 }
Alex Light3470ab42014-06-18 10:35:45 -0700879 CHECK(*symbol_table != nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -0700880 typename SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800881 if (it == (*symbol_table)->end()) {
Alex Light3470ab42014-06-18 10:35:45 -0700882 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800883 }
884 return it->second;
885 }
886
887 // Fall back to linear search
Tong Shen62d1ca32014-09-03 17:24:56 -0700888 Elf_Shdr* symbol_section = FindSectionByType(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700889 if (symbol_section == nullptr) {
890 return nullptr;
891 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700892 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700893 if (string_section == nullptr) {
894 return nullptr;
895 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800896 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700897 Elf_Sym* symbol = GetSymbol(section_type, i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700898 if (symbol == nullptr) {
899 return nullptr; // Failure condition.
900 }
901 const char* name = GetString(*string_section, symbol->st_name);
Alex Light3470ab42014-06-18 10:35:45 -0700902 if (name == nullptr) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800903 continue;
904 }
905 if (symbol_name == name) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700906 return symbol;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800907 }
908 }
Alex Light3470ab42014-06-18 10:35:45 -0700909 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800910}
911
David Srbecky533c2072015-04-22 12:20:22 +0100912template <typename ElfTypes>
913typename ElfTypes::Addr ElfFileImpl<ElfTypes>::FindSymbolAddress(
914 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700915 Elf_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
Alex Light3470ab42014-06-18 10:35:45 -0700916 if (symbol == nullptr) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800917 return 0;
918 }
919 return symbol->st_value;
920}
921
David Srbecky533c2072015-04-22 12:20:22 +0100922template <typename ElfTypes>
923const char* ElfFileImpl<ElfTypes>::GetString(Elf_Shdr& string_section,
924 Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800925 CHECK(!program_header_only_) << file_->GetPath();
926 // TODO: remove this static_cast from enum when using -std=gnu++0x
Tong Shen62d1ca32014-09-03 17:24:56 -0700927 if (static_cast<Elf_Word>(SHT_STRTAB) != string_section.sh_type) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700928 return nullptr; // Failure condition.
929 }
930 if (i >= string_section.sh_size) {
931 return nullptr;
932 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800933 if (i == 0) {
Alex Light3470ab42014-06-18 10:35:45 -0700934 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800935 }
Ian Rogers13735952014-10-08 12:43:28 -0700936 uint8_t* strings = Begin() + string_section.sh_offset;
937 uint8_t* string = strings + i;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700938 if (string >= End()) {
939 return nullptr;
940 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800941 return reinterpret_cast<const char*>(string);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800942}
943
David Srbecky533c2072015-04-22 12:20:22 +0100944template <typename ElfTypes>
945typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetDynamicNum() const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700946 return GetDynamicProgramHeader().p_filesz / sizeof(Elf_Dyn);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800947}
948
David Srbecky533c2072015-04-22 12:20:22 +0100949template <typename ElfTypes>
950typename ElfTypes::Dyn& ElfFileImpl<ElfTypes>::GetDynamic(Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800951 CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
952 return *(GetDynamicSectionStart() + i);
953}
954
David Srbecky533c2072015-04-22 12:20:22 +0100955template <typename ElfTypes>
956typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::FindDynamicByType(Elf_Sword type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700957 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
958 Elf_Dyn* dyn = &GetDynamic(i);
Alex Light53cb16b2014-06-12 11:26:29 -0700959 if (dyn->d_tag == type) {
960 return dyn;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800961 }
962 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700963 return nullptr;
Alex Light53cb16b2014-06-12 11:26:29 -0700964}
965
David Srbecky533c2072015-04-22 12:20:22 +0100966template <typename ElfTypes>
967typename ElfTypes::Word ElfFileImpl<ElfTypes>::FindDynamicValueByType(Elf_Sword type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700968 Elf_Dyn* dyn = FindDynamicByType(type);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700969 if (dyn == nullptr) {
Alex Light53cb16b2014-06-12 11:26:29 -0700970 return 0;
971 } else {
972 return dyn->d_un.d_val;
973 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800974}
975
David Srbecky533c2072015-04-22 12:20:22 +0100976template <typename ElfTypes>
977typename ElfTypes::Rel* ElfFileImpl<ElfTypes>::GetRelSectionStart(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000978 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Tong Shen62d1ca32014-09-03 17:24:56 -0700979 return reinterpret_cast<Elf_Rel*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800980}
981
David Srbecky533c2072015-04-22 12:20:22 +0100982template <typename ElfTypes>
983typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelNum(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000984 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800985 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
986 return section_header.sh_size / section_header.sh_entsize;
987}
988
David Srbecky533c2072015-04-22 12:20:22 +0100989template <typename ElfTypes>
990typename ElfTypes::Rel& ElfFileImpl<ElfTypes>::GetRel(Elf_Shdr& section_header, Elf_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000991 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800992 CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
993 return *(GetRelSectionStart(section_header) + i);
994}
995
David Srbecky533c2072015-04-22 12:20:22 +0100996template <typename ElfTypes>
997typename ElfTypes::Rela* ElfFileImpl<ElfTypes>::GetRelaSectionStart(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000998 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Tong Shen62d1ca32014-09-03 17:24:56 -0700999 return reinterpret_cast<Elf_Rela*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001000}
1001
David Srbecky533c2072015-04-22 12:20:22 +01001002template <typename ElfTypes>
1003typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelaNum(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001004 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001005 return section_header.sh_size / section_header.sh_entsize;
1006}
1007
David Srbecky533c2072015-04-22 12:20:22 +01001008template <typename ElfTypes>
1009typename ElfTypes::Rela& ElfFileImpl<ElfTypes>::GetRela(Elf_Shdr& section_header, Elf_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001010 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001011 CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
1012 return *(GetRelaSectionStart(section_header) + i);
1013}
1014
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001015// Base on bionic phdr_table_get_load_size
David Srbecky533c2072015-04-22 12:20:22 +01001016template <typename ElfTypes>
Vladimir Marko3fc99032015-05-13 19:06:30 +01001017bool ElfFileImpl<ElfTypes>::GetLoadedSize(size_t* size, std::string* error_msg) const {
1018 Elf_Addr min_vaddr = static_cast<Elf_Addr>(-1);
1019 Elf_Addr max_vaddr = 0u;
Tong Shen62d1ca32014-09-03 17:24:56 -07001020 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1021 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001022 if (program_header->p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001023 continue;
1024 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001025 Elf_Addr begin_vaddr = program_header->p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001026 if (begin_vaddr < min_vaddr) {
1027 min_vaddr = begin_vaddr;
1028 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001029 Elf_Addr end_vaddr = program_header->p_vaddr + program_header->p_memsz;
Vladimir Marko3fc99032015-05-13 19:06:30 +01001030 if (UNLIKELY(begin_vaddr > end_vaddr)) {
1031 std::ostringstream oss;
1032 oss << "Program header #" << i << " has overflow in p_vaddr+p_memsz: 0x" << std::hex
1033 << program_header->p_vaddr << "+0x" << program_header->p_memsz << "=0x" << end_vaddr
1034 << " in ELF file \"" << file_->GetPath() << "\"";
1035 *error_msg = oss.str();
1036 *size = static_cast<size_t>(-1);
1037 return false;
1038 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001039 if (end_vaddr > max_vaddr) {
1040 max_vaddr = end_vaddr;
1041 }
1042 }
1043 min_vaddr = RoundDown(min_vaddr, kPageSize);
1044 max_vaddr = RoundUp(max_vaddr, kPageSize);
1045 CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
Vladimir Marko3fc99032015-05-13 19:06:30 +01001046 Elf_Addr loaded_size = max_vaddr - min_vaddr;
1047 // Check that the loaded_size fits in size_t.
1048 if (UNLIKELY(loaded_size > std::numeric_limits<size_t>::max())) {
1049 std::ostringstream oss;
1050 oss << "Loaded size is 0x" << std::hex << loaded_size << " but maximum size_t is 0x"
1051 << std::numeric_limits<size_t>::max() << " for ELF file \"" << file_->GetPath() << "\"";
1052 *error_msg = oss.str();
1053 *size = static_cast<size_t>(-1);
1054 return false;
1055 }
1056 *size = loaded_size;
1057 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001058}
1059
David Srbecky533c2072015-04-22 12:20:22 +01001060template <typename ElfTypes>
1061bool ElfFileImpl<ElfTypes>::Load(bool executable, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001062 CHECK(program_header_only_) << file_->GetPath();
Andreas Gampe91268c12014-04-03 17:50:24 -07001063
1064 if (executable) {
Andreas Gampe6f611412015-01-21 22:25:24 -08001065 InstructionSet elf_ISA = GetInstructionSetFromELF(GetHeader().e_machine, GetHeader().e_flags);
Andreas Gampe91268c12014-04-03 17:50:24 -07001066 if (elf_ISA != kRuntimeISA) {
1067 std::ostringstream oss;
1068 oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
1069 *error_msg = oss.str();
1070 return false;
1071 }
1072 }
1073
Jim_Guoa62a5882014-04-28 11:11:57 +08001074 bool reserved = false;
Tong Shen62d1ca32014-09-03 17:24:56 -07001075 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1076 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001077 if (program_header == nullptr) {
1078 *error_msg = StringPrintf("No program header for entry %d in ELF file %s.",
1079 i, file_->GetPath().c_str());
1080 return false;
1081 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001082
1083 // Record .dynamic header information for later use
Andreas Gampedaab38c2014-09-12 18:38:24 -07001084 if (program_header->p_type == PT_DYNAMIC) {
1085 dynamic_program_header_ = program_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001086 continue;
1087 }
1088
1089 // Not something to load, move on.
Andreas Gampedaab38c2014-09-12 18:38:24 -07001090 if (program_header->p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001091 continue;
1092 }
1093
1094 // Found something to load.
1095
Jim_Guoa62a5882014-04-28 11:11:57 +08001096 // Before load the actual segments, reserve a contiguous chunk
1097 // of required size and address for all segments, but with no
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001098 // permissions. We'll then carve that up with the proper
1099 // permissions as we load the actual segments. If p_vaddr is
1100 // non-zero, the segments require the specific address specified,
1101 // which either was specified in the file because we already set
1102 // base_address_ after the first zero segment).
Ian Rogerscdfcf372014-01-23 20:38:36 -08001103 int64_t temp_file_length = file_->GetLength();
1104 if (temp_file_length < 0) {
1105 errno = -temp_file_length;
1106 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
1107 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
1108 return false;
1109 }
1110 size_t file_length = static_cast<size_t>(temp_file_length);
Jim_Guoa62a5882014-04-28 11:11:57 +08001111 if (!reserved) {
Igor Murashkin46774762014-10-22 11:37:02 -07001112 uint8_t* reserve_base = reinterpret_cast<uint8_t*>(program_header->p_vaddr);
1113 uint8_t* reserve_base_override = reserve_base;
1114 // Override the base (e.g. when compiling with --compile-pic)
1115 if (requested_base_ != nullptr) {
1116 reserve_base_override = requested_base_;
1117 }
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001118 std::string reservation_name("ElfFile reservation for ");
1119 reservation_name += file_->GetPath();
Vladimir Marko3fc99032015-05-13 19:06:30 +01001120 size_t loaded_size;
1121 if (!GetLoadedSize(&loaded_size, error_msg)) {
1122 DCHECK(!error_msg->empty());
1123 return false;
1124 }
Ian Rogers700a4022014-05-19 16:49:03 -07001125 std::unique_ptr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
Igor Murashkin46774762014-10-22 11:37:02 -07001126 reserve_base_override,
Vladimir Marko3fc99032015-05-13 19:06:30 +01001127 loaded_size, PROT_NONE, false, false,
Jim_Guoa62a5882014-04-28 11:11:57 +08001128 error_msg));
Brian Carlstromc1409452014-02-26 14:06:23 -08001129 if (reserve.get() == nullptr) {
1130 *error_msg = StringPrintf("Failed to allocate %s: %s",
1131 reservation_name.c_str(), error_msg->c_str());
1132 return false;
1133 }
Jim_Guoa62a5882014-04-28 11:11:57 +08001134 reserved = true;
Igor Murashkin46774762014-10-22 11:37:02 -07001135
1136 // Base address is the difference of actual mapped location and the p_vaddr
1137 base_address_ = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(reserve->Begin())
1138 - reinterpret_cast<uintptr_t>(reserve_base));
1139 // By adding the p_vaddr of a section/symbol to base_address_ we will always get the
1140 // dynamic memory address of where that object is actually mapped
1141 //
1142 // TODO: base_address_ needs to be calculated in ::Open, otherwise
1143 // FindDynamicSymbolAddress returns the wrong values until Load is called.
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001144 segments_.push_back(reserve.release());
1145 }
1146 // empty segment, nothing to map
Andreas Gampedaab38c2014-09-12 18:38:24 -07001147 if (program_header->p_memsz == 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001148 continue;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001149 }
Ian Rogers13735952014-10-08 12:43:28 -07001150 uint8_t* p_vaddr = base_address_ + program_header->p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001151 int prot = 0;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001152 if (executable && ((program_header->p_flags & PF_X) != 0)) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001153 prot |= PROT_EXEC;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001154 }
Andreas Gampedaab38c2014-09-12 18:38:24 -07001155 if ((program_header->p_flags & PF_W) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001156 prot |= PROT_WRITE;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001157 }
Andreas Gampedaab38c2014-09-12 18:38:24 -07001158 if ((program_header->p_flags & PF_R) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001159 prot |= PROT_READ;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001160 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -07001161 int flags = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001162 if (writable_) {
1163 prot |= PROT_WRITE;
1164 flags |= MAP_SHARED;
1165 } else {
1166 flags |= MAP_PRIVATE;
1167 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001168 if (program_header->p_filesz > program_header->p_memsz) {
1169 *error_msg = StringPrintf("Invalid p_filesz > p_memsz (%" PRIu64 " > %" PRIu64 "): %s",
1170 static_cast<uint64_t>(program_header->p_filesz),
1171 static_cast<uint64_t>(program_header->p_memsz),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001172 file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -07001173 return false;
1174 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001175 if (program_header->p_filesz < program_header->p_memsz &&
1176 !IsAligned<kPageSize>(program_header->p_filesz)) {
1177 *error_msg = StringPrintf("Unsupported unaligned p_filesz < p_memsz (%" PRIu64
1178 " < %" PRIu64 "): %s",
1179 static_cast<uint64_t>(program_header->p_filesz),
1180 static_cast<uint64_t>(program_header->p_memsz),
1181 file_->GetPath().c_str());
Brian Carlstromc1409452014-02-26 14:06:23 -08001182 return false;
1183 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001184 if (file_length < (program_header->p_offset + program_header->p_filesz)) {
1185 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
1186 "%d of %" PRIu64 " bytes: '%s'", file_length, i,
1187 static_cast<uint64_t>(program_header->p_offset + program_header->p_filesz),
1188 file_->GetPath().c_str());
Brian Carlstromc1409452014-02-26 14:06:23 -08001189 return false;
1190 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001191 if (program_header->p_filesz != 0u) {
1192 std::unique_ptr<MemMap> segment(
1193 MemMap::MapFileAtAddress(p_vaddr,
1194 program_header->p_filesz,
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001195 prot,
1196 flags,
1197 file_->Fd(),
Vladimir Marko5c42c292015-02-25 12:02:49 +00001198 program_header->p_offset,
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001199 /*low4_gb*/false,
1200 /*reuse*/true, // implies MAP_FIXED
Vladimir Marko5c42c292015-02-25 12:02:49 +00001201 file_->GetPath().c_str(),
1202 error_msg));
1203 if (segment.get() == nullptr) {
1204 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
1205 i, file_->GetPath().c_str(), error_msg->c_str());
1206 return false;
1207 }
1208 if (segment->Begin() != p_vaddr) {
1209 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
1210 "instead mapped to %p",
1211 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
1212 return false;
1213 }
1214 segments_.push_back(segment.release());
1215 }
1216 if (program_header->p_filesz < program_header->p_memsz) {
1217 std::string name = StringPrintf("Zero-initialized segment %" PRIu64 " of ELF file %s",
1218 static_cast<uint64_t>(i), file_->GetPath().c_str());
1219 std::unique_ptr<MemMap> segment(
1220 MemMap::MapAnonymous(name.c_str(),
1221 p_vaddr + program_header->p_filesz,
1222 program_header->p_memsz - program_header->p_filesz,
1223 prot, false, true /* reuse */, error_msg));
1224 if (segment == nullptr) {
1225 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s: %s",
1226 i, file_->GetPath().c_str(), error_msg->c_str());
1227 return false;
1228 }
1229 if (segment->Begin() != p_vaddr) {
1230 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s "
1231 "at expected address %p, instead mapped to %p",
1232 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
1233 return false;
1234 }
1235 segments_.push_back(segment.release());
1236 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001237 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001238
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001239 // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
Ian Rogers13735952014-10-08 12:43:28 -07001240 uint8_t* dsptr = base_address_ + GetDynamicProgramHeader().p_vaddr;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001241 if ((dsptr < Begin() || dsptr >= End()) && !ValidPointer(dsptr)) {
1242 *error_msg = StringPrintf("dynamic section address invalid in ELF file %s",
1243 file_->GetPath().c_str());
1244 return false;
1245 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001246 dynamic_section_start_ = reinterpret_cast<Elf_Dyn*>(dsptr);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001247
Tong Shen62d1ca32014-09-03 17:24:56 -07001248 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1249 Elf_Dyn& elf_dyn = GetDynamic(i);
Ian Rogers13735952014-10-08 12:43:28 -07001250 uint8_t* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001251 switch (elf_dyn.d_tag) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001252 case DT_HASH: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001253 if (!ValidPointer(d_ptr)) {
1254 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1255 d_ptr, file_->GetPath().c_str());
1256 return false;
1257 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001258 hash_section_start_ = reinterpret_cast<Elf_Word*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001259 break;
1260 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001261 case DT_STRTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001262 if (!ValidPointer(d_ptr)) {
1263 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1264 d_ptr, file_->GetPath().c_str());
1265 return false;
1266 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001267 dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
1268 break;
1269 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001270 case DT_SYMTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001271 if (!ValidPointer(d_ptr)) {
1272 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1273 d_ptr, file_->GetPath().c_str());
1274 return false;
1275 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001276 dynsym_section_start_ = reinterpret_cast<Elf_Sym*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001277 break;
1278 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001279 case DT_NULL: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001280 if (GetDynamicNum() != i+1) {
1281 *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
1282 "expected %d as implied by size of PT_DYNAMIC segment in %s",
1283 i + 1, GetDynamicNum(), file_->GetPath().c_str());
1284 return false;
1285 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001286 break;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001287 }
1288 }
1289 }
1290
Andreas Gampedaab38c2014-09-12 18:38:24 -07001291 // Check for the existence of some sections.
1292 if (!CheckSectionsExist(error_msg)) {
1293 return false;
1294 }
1295
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001296 return true;
1297}
1298
David Srbecky533c2072015-04-22 12:20:22 +01001299template <typename ElfTypes>
1300bool ElfFileImpl<ElfTypes>::ValidPointer(const uint8_t* start) const {
Brian Carlstromc1409452014-02-26 14:06:23 -08001301 for (size_t i = 0; i < segments_.size(); ++i) {
1302 const MemMap* segment = segments_[i];
1303 if (segment->Begin() <= start && start < segment->End()) {
1304 return true;
1305 }
1306 }
1307 return false;
1308}
1309
Alex Light3470ab42014-06-18 10:35:45 -07001310
David Srbecky533c2072015-04-22 12:20:22 +01001311template <typename ElfTypes>
1312typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByName(
1313 const std::string& name) const {
Alex Light3470ab42014-06-18 10:35:45 -07001314 CHECK(!program_header_only_);
Tong Shen62d1ca32014-09-03 17:24:56 -07001315 Elf_Shdr* shstrtab_sec = GetSectionNameStringSection();
Andreas Gampedaab38c2014-09-12 18:38:24 -07001316 if (shstrtab_sec == nullptr) {
1317 return nullptr;
1318 }
Alex Light3470ab42014-06-18 10:35:45 -07001319 for (uint32_t i = 0; i < GetSectionHeaderNum(); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001320 Elf_Shdr* shdr = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001321 if (shdr == nullptr) {
1322 return nullptr;
1323 }
1324 const char* sec_name = GetString(*shstrtab_sec, shdr->sh_name);
Alex Light3470ab42014-06-18 10:35:45 -07001325 if (sec_name == nullptr) {
1326 continue;
1327 }
1328 if (name == sec_name) {
Andreas Gampedaab38c2014-09-12 18:38:24 -07001329 return shdr;
Alex Light3470ab42014-06-18 10:35:45 -07001330 }
1331 }
1332 return nullptr;
Mark Mendellae9fd932014-02-10 16:14:35 -08001333}
1334
David Srbecky533c2072015-04-22 12:20:22 +01001335template <typename ElfTypes>
David Srbeckyf8980872015-05-22 17:04:47 +01001336bool ElfFileImpl<ElfTypes>::FixupDebugSections(Elf_Addr base_address_delta) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001337 if (base_address_delta == 0) {
1338 return true;
1339 }
David Srbeckyf8980872015-05-22 17:04:47 +01001340 return ApplyOatPatchesTo(".debug_frame", base_address_delta) &&
1341 ApplyOatPatchesTo(".debug_info", base_address_delta) &&
1342 ApplyOatPatchesTo(".debug_line", base_address_delta);
David Srbecky2f6cdb02015-04-11 00:17:53 +01001343}
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001344
David Srbecky533c2072015-04-22 12:20:22 +01001345template <typename ElfTypes>
1346bool ElfFileImpl<ElfTypes>::ApplyOatPatchesTo(
David Srbeckyf8980872015-05-22 17:04:47 +01001347 const char* target_section_name, Elf_Addr delta) {
1348 auto target_section = FindSectionByName(target_section_name);
1349 if (target_section == nullptr) {
1350 return true;
1351 }
1352 std::string patches_name = target_section_name + std::string(".oat_patches");
1353 auto patches_section = FindSectionByName(patches_name.c_str());
David Srbecky2f6cdb02015-04-11 00:17:53 +01001354 if (patches_section == nullptr) {
David Srbeckyf8980872015-05-22 17:04:47 +01001355 LOG(ERROR) << patches_name << " section not found.";
Alex Light3470ab42014-06-18 10:35:45 -07001356 return false;
1357 }
David Srbecky2f6cdb02015-04-11 00:17:53 +01001358 if (patches_section->sh_type != SHT_OAT_PATCH) {
David Srbeckyf8980872015-05-22 17:04:47 +01001359 LOG(ERROR) << "Unexpected type of " << patches_name;
Alex Light3470ab42014-06-18 10:35:45 -07001360 return false;
1361 }
David Srbeckyf8980872015-05-22 17:04:47 +01001362 ApplyOatPatches(
David Srbecky2f6cdb02015-04-11 00:17:53 +01001363 Begin() + patches_section->sh_offset,
1364 Begin() + patches_section->sh_offset + patches_section->sh_size,
David Srbeckyf8980872015-05-22 17:04:47 +01001365 delta,
David Srbecky2f6cdb02015-04-11 00:17:53 +01001366 Begin() + target_section->sh_offset,
David Srbeckyf8980872015-05-22 17:04:47 +01001367 Begin() + target_section->sh_offset + target_section->sh_size);
David Srbecky2f6cdb02015-04-11 00:17:53 +01001368 return true;
1369}
1370
David Srbeckyf8980872015-05-22 17:04:47 +01001371// Apply LEB128 encoded patches to given section.
David Srbecky533c2072015-04-22 12:20:22 +01001372template <typename ElfTypes>
David Srbeckyf8980872015-05-22 17:04:47 +01001373void ElfFileImpl<ElfTypes>::ApplyOatPatches(
1374 const uint8_t* patches, const uint8_t* patches_end, Elf_Addr delta,
David Srbecky533c2072015-04-22 12:20:22 +01001375 uint8_t* to_patch, const uint8_t* to_patch_end) {
David Srbeckyf8980872015-05-22 17:04:47 +01001376 typedef __attribute__((__aligned__(1))) Elf_Addr UnalignedAddress;
1377 while (patches < patches_end) {
1378 to_patch += DecodeUnsignedLeb128(&patches);
1379 DCHECK_LE(patches, patches_end) << "Unexpected end of patch list.";
1380 DCHECK_LT(to_patch, to_patch_end) << "Patch past the end of section.";
1381 *reinterpret_cast<UnalignedAddress*>(to_patch) += delta;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001382 }
Alex Light3470ab42014-06-18 10:35:45 -07001383}
Mark Mendellae9fd932014-02-10 16:14:35 -08001384
David Srbecky533c2072015-04-22 12:20:22 +01001385template <typename ElfTypes>
David Srbecky533c2072015-04-22 12:20:22 +01001386bool ElfFileImpl<ElfTypes>::Strip(std::string* error_msg) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001387 // ELF files produced by MCLinker look roughly like this
1388 //
1389 // +------------+
1390 // | Elf_Ehdr | contains number of Elf_Shdr and offset to first
1391 // +------------+
1392 // | Elf_Phdr | program headers
1393 // | Elf_Phdr |
1394 // | ... |
1395 // | Elf_Phdr |
1396 // +------------+
1397 // | section | mixture of needed and unneeded sections
1398 // +------------+
1399 // | section |
1400 // +------------+
1401 // | ... |
1402 // +------------+
1403 // | section |
1404 // +------------+
1405 // | Elf_Shdr | section headers
1406 // | Elf_Shdr |
1407 // | ... | contains offset to section start
1408 // | Elf_Shdr |
1409 // +------------+
1410 //
1411 // To strip:
1412 // - leave the Elf_Ehdr and Elf_Phdr values in place.
1413 // - walk the sections making a new set of Elf_Shdr section headers for what we want to keep
1414 // - move the sections are keeping up to fill in gaps of sections we want to strip
1415 // - write new Elf_Shdr section headers to end of file, updating Elf_Ehdr
1416 // - truncate rest of file
1417 //
1418
1419 std::vector<Elf_Shdr> section_headers;
1420 std::vector<Elf_Word> section_headers_original_indexes;
1421 section_headers.reserve(GetSectionHeaderNum());
1422
1423
1424 Elf_Shdr* string_section = GetSectionNameStringSection();
1425 CHECK(string_section != nullptr);
1426 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1427 Elf_Shdr* sh = GetSectionHeader(i);
1428 CHECK(sh != nullptr);
1429 const char* name = GetString(*string_section, sh->sh_name);
1430 if (name == nullptr) {
1431 CHECK_EQ(0U, i);
1432 section_headers.push_back(*sh);
1433 section_headers_original_indexes.push_back(0);
1434 continue;
1435 }
1436 if (StartsWith(name, ".debug")
1437 || (strcmp(name, ".strtab") == 0)
1438 || (strcmp(name, ".symtab") == 0)) {
1439 continue;
1440 }
1441 section_headers.push_back(*sh);
1442 section_headers_original_indexes.push_back(i);
1443 }
1444 CHECK_NE(0U, section_headers.size());
1445 CHECK_EQ(section_headers.size(), section_headers_original_indexes.size());
1446
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001447 // section 0 is the null section, sections start at offset of first section
Tong Shen62d1ca32014-09-03 17:24:56 -07001448 CHECK(GetSectionHeader(1) != nullptr);
1449 Elf_Off offset = GetSectionHeader(1)->sh_offset;
1450 for (size_t i = 1; i < section_headers.size(); i++) {
1451 Elf_Shdr& new_sh = section_headers[i];
1452 Elf_Shdr* old_sh = GetSectionHeader(section_headers_original_indexes[i]);
1453 CHECK(old_sh != nullptr);
1454 CHECK_EQ(new_sh.sh_name, old_sh->sh_name);
1455 if (old_sh->sh_addralign > 1) {
1456 offset = RoundUp(offset, old_sh->sh_addralign);
1457 }
1458 if (old_sh->sh_offset == offset) {
1459 // already in place
1460 offset += old_sh->sh_size;
1461 continue;
1462 }
1463 // shift section earlier
1464 memmove(Begin() + offset,
1465 Begin() + old_sh->sh_offset,
1466 old_sh->sh_size);
1467 new_sh.sh_offset = offset;
1468 offset += old_sh->sh_size;
1469 }
1470
1471 Elf_Off shoff = offset;
1472 size_t section_headers_size_in_bytes = section_headers.size() * sizeof(Elf_Shdr);
1473 memcpy(Begin() + offset, &section_headers[0], section_headers_size_in_bytes);
1474 offset += section_headers_size_in_bytes;
1475
1476 GetHeader().e_shnum = section_headers.size();
1477 GetHeader().e_shoff = shoff;
1478 int result = ftruncate(file_->Fd(), offset);
1479 if (result != 0) {
1480 *error_msg = StringPrintf("Failed to truncate while stripping ELF file: '%s': %s",
1481 file_->GetPath().c_str(), strerror(errno));
1482 return false;
1483 }
1484 return true;
1485}
1486
1487static const bool DEBUG_FIXUP = false;
1488
David Srbecky533c2072015-04-22 12:20:22 +01001489template <typename ElfTypes>
1490bool ElfFileImpl<ElfTypes>::Fixup(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001491 if (!FixupDynamic(base_address)) {
1492 LOG(WARNING) << "Failed to fixup .dynamic in " << file_->GetPath();
1493 return false;
1494 }
1495 if (!FixupSectionHeaders(base_address)) {
1496 LOG(WARNING) << "Failed to fixup section headers in " << file_->GetPath();
1497 return false;
1498 }
1499 if (!FixupProgramHeaders(base_address)) {
1500 LOG(WARNING) << "Failed to fixup program headers in " << file_->GetPath();
1501 return false;
1502 }
1503 if (!FixupSymbols(base_address, true)) {
1504 LOG(WARNING) << "Failed to fixup .dynsym in " << file_->GetPath();
1505 return false;
1506 }
1507 if (!FixupSymbols(base_address, false)) {
1508 LOG(WARNING) << "Failed to fixup .symtab in " << file_->GetPath();
1509 return false;
1510 }
1511 if (!FixupRelocations(base_address)) {
1512 LOG(WARNING) << "Failed to fixup .rel.dyn in " << file_->GetPath();
1513 return false;
1514 }
Andreas Gampe3c54b002015-04-07 16:09:30 -07001515 static_assert(sizeof(Elf_Off) >= sizeof(base_address), "Potentially losing precision.");
1516 if (!FixupDebugSections(static_cast<Elf_Off>(base_address))) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001517 LOG(WARNING) << "Failed to fixup debug sections in " << file_->GetPath();
1518 return false;
1519 }
1520 return true;
1521}
1522
David Srbecky533c2072015-04-22 12:20:22 +01001523template <typename ElfTypes>
1524bool ElfFileImpl<ElfTypes>::FixupDynamic(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001525 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1526 Elf_Dyn& elf_dyn = GetDynamic(i);
1527 Elf_Word d_tag = elf_dyn.d_tag;
1528 if (IsDynamicSectionPointer(d_tag, GetHeader().e_machine)) {
1529 Elf_Addr d_ptr = elf_dyn.d_un.d_ptr;
1530 if (DEBUG_FIXUP) {
1531 LOG(INFO) << StringPrintf("In %s moving Elf_Dyn[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1532 GetFile().GetPath().c_str(), i,
1533 static_cast<uint64_t>(d_ptr),
1534 static_cast<uint64_t>(d_ptr + base_address));
1535 }
1536 d_ptr += base_address;
1537 elf_dyn.d_un.d_ptr = d_ptr;
1538 }
1539 }
1540 return true;
1541}
1542
David Srbecky533c2072015-04-22 12:20:22 +01001543template <typename ElfTypes>
1544bool ElfFileImpl<ElfTypes>::FixupSectionHeaders(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001545 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1546 Elf_Shdr* sh = GetSectionHeader(i);
1547 CHECK(sh != nullptr);
1548 // 0 implies that the section will not exist in the memory of the process
1549 if (sh->sh_addr == 0) {
1550 continue;
1551 }
1552 if (DEBUG_FIXUP) {
1553 LOG(INFO) << StringPrintf("In %s moving Elf_Shdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1554 GetFile().GetPath().c_str(), i,
1555 static_cast<uint64_t>(sh->sh_addr),
1556 static_cast<uint64_t>(sh->sh_addr + base_address));
1557 }
1558 sh->sh_addr += base_address;
1559 }
1560 return true;
1561}
1562
David Srbecky533c2072015-04-22 12:20:22 +01001563template <typename ElfTypes>
1564bool ElfFileImpl<ElfTypes>::FixupProgramHeaders(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001565 // TODO: ELFObjectFile doesn't have give to Elf_Phdr, so we do that ourselves for now.
1566 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1567 Elf_Phdr* ph = GetProgramHeader(i);
1568 CHECK(ph != nullptr);
1569 CHECK_EQ(ph->p_vaddr, ph->p_paddr) << GetFile().GetPath() << " i=" << i;
1570 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1571 << GetFile().GetPath() << " i=" << i;
1572 if (DEBUG_FIXUP) {
1573 LOG(INFO) << StringPrintf("In %s moving Elf_Phdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1574 GetFile().GetPath().c_str(), i,
1575 static_cast<uint64_t>(ph->p_vaddr),
1576 static_cast<uint64_t>(ph->p_vaddr + base_address));
1577 }
1578 ph->p_vaddr += base_address;
1579 ph->p_paddr += base_address;
1580 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1581 << GetFile().GetPath() << " i=" << i;
1582 }
1583 return true;
1584}
1585
David Srbecky533c2072015-04-22 12:20:22 +01001586template <typename ElfTypes>
1587bool ElfFileImpl<ElfTypes>::FixupSymbols(Elf_Addr base_address, bool dynamic) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001588 Elf_Word section_type = dynamic ? SHT_DYNSYM : SHT_SYMTAB;
1589 // TODO: Unfortunate ELFObjectFile has protected symbol access, so use ElfFile
1590 Elf_Shdr* symbol_section = FindSectionByType(section_type);
1591 if (symbol_section == nullptr) {
1592 // file is missing optional .symtab
1593 CHECK(!dynamic) << GetFile().GetPath();
1594 return true;
1595 }
1596 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
1597 Elf_Sym* symbol = GetSymbol(section_type, i);
1598 CHECK(symbol != nullptr);
1599 if (symbol->st_value != 0) {
1600 if (DEBUG_FIXUP) {
1601 LOG(INFO) << StringPrintf("In %s moving Elf_Sym[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1602 GetFile().GetPath().c_str(), i,
1603 static_cast<uint64_t>(symbol->st_value),
1604 static_cast<uint64_t>(symbol->st_value + base_address));
1605 }
1606 symbol->st_value += base_address;
1607 }
1608 }
1609 return true;
1610}
1611
David Srbecky533c2072015-04-22 12:20:22 +01001612template <typename ElfTypes>
1613bool ElfFileImpl<ElfTypes>::FixupRelocations(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001614 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1615 Elf_Shdr* sh = GetSectionHeader(i);
1616 CHECK(sh != nullptr);
1617 if (sh->sh_type == SHT_REL) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001618 for (uint32_t j = 0; j < GetRelNum(*sh); j++) {
1619 Elf_Rel& rel = GetRel(*sh, j);
Tong Shen62d1ca32014-09-03 17:24:56 -07001620 if (DEBUG_FIXUP) {
1621 LOG(INFO) << StringPrintf("In %s moving Elf_Rel[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001622 GetFile().GetPath().c_str(), j,
Tong Shen62d1ca32014-09-03 17:24:56 -07001623 static_cast<uint64_t>(rel.r_offset),
1624 static_cast<uint64_t>(rel.r_offset + base_address));
1625 }
1626 rel.r_offset += base_address;
1627 }
1628 } else if (sh->sh_type == SHT_RELA) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001629 for (uint32_t j = 0; j < GetRelaNum(*sh); j++) {
1630 Elf_Rela& rela = GetRela(*sh, j);
Tong Shen62d1ca32014-09-03 17:24:56 -07001631 if (DEBUG_FIXUP) {
1632 LOG(INFO) << StringPrintf("In %s moving Elf_Rela[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001633 GetFile().GetPath().c_str(), j,
Tong Shen62d1ca32014-09-03 17:24:56 -07001634 static_cast<uint64_t>(rela.r_offset),
1635 static_cast<uint64_t>(rela.r_offset + base_address));
1636 }
1637 rela.r_offset += base_address;
1638 }
1639 }
1640 }
1641 return true;
1642}
1643
1644// Explicit instantiations
David Srbecky533c2072015-04-22 12:20:22 +01001645template class ElfFileImpl<ElfTypes32>;
1646template class ElfFileImpl<ElfTypes64>;
Tong Shen62d1ca32014-09-03 17:24:56 -07001647
Ian Rogersd4c4d952014-10-16 20:31:53 -07001648ElfFile::ElfFile(ElfFileImpl32* elf32) : elf32_(elf32), elf64_(nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001649}
1650
Ian Rogersd4c4d952014-10-16 20:31:53 -07001651ElfFile::ElfFile(ElfFileImpl64* elf64) : elf32_(nullptr), elf64_(elf64) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001652}
1653
1654ElfFile::~ElfFile() {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001655 // Should never have 32 and 64-bit impls.
1656 CHECK_NE(elf32_.get() == nullptr, elf64_.get() == nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -07001657}
1658
Igor Murashkin46774762014-10-22 11:37:02 -07001659ElfFile* ElfFile::Open(File* file, bool writable, bool program_header_only, std::string* error_msg,
1660 uint8_t* requested_base) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001661 if (file->GetLength() < EI_NIDENT) {
1662 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1663 file->GetPath().c_str());
1664 return nullptr;
1665 }
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001666 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT,
1667 PROT_READ,
1668 MAP_PRIVATE,
1669 file->Fd(),
1670 0,
1671 /*low4_gb*/false,
1672 file->GetPath().c_str(),
1673 error_msg));
Tong Shen62d1ca32014-09-03 17:24:56 -07001674 if (map == nullptr && map->Size() != EI_NIDENT) {
1675 return nullptr;
1676 }
Ian Rogers13735952014-10-08 12:43:28 -07001677 uint8_t* header = map->Begin();
Tong Shen62d1ca32014-09-03 17:24:56 -07001678 if (header[EI_CLASS] == ELFCLASS64) {
Igor Murashkin46774762014-10-22 11:37:02 -07001679 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file, writable, program_header_only,
1680 error_msg, requested_base);
Tong Shen62d1ca32014-09-03 17:24:56 -07001681 if (elf_file_impl == nullptr)
1682 return nullptr;
1683 return new ElfFile(elf_file_impl);
1684 } else if (header[EI_CLASS] == ELFCLASS32) {
Igor Murashkin46774762014-10-22 11:37:02 -07001685 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file, writable, program_header_only,
1686 error_msg, requested_base);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001687 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001688 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001689 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001690 return new ElfFile(elf_file_impl);
1691 } else {
1692 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1693 ELFCLASS32, ELFCLASS64,
1694 file->GetPath().c_str(),
1695 header[EI_CLASS]);
1696 return nullptr;
1697 }
1698}
1699
1700ElfFile* ElfFile::Open(File* file, int mmap_prot, int mmap_flags, std::string* error_msg) {
1701 if (file->GetLength() < EI_NIDENT) {
1702 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1703 file->GetPath().c_str());
1704 return nullptr;
1705 }
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001706 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT,
1707 PROT_READ,
1708 MAP_PRIVATE,
1709 file->Fd(),
1710 0,
1711 /*low4_gb*/false,
1712 file->GetPath().c_str(),
1713 error_msg));
Tong Shen62d1ca32014-09-03 17:24:56 -07001714 if (map == nullptr && map->Size() != EI_NIDENT) {
1715 return nullptr;
1716 }
Ian Rogers13735952014-10-08 12:43:28 -07001717 uint8_t* header = map->Begin();
Tong Shen62d1ca32014-09-03 17:24:56 -07001718 if (header[EI_CLASS] == ELFCLASS64) {
1719 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file, mmap_prot, mmap_flags, error_msg);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001720 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001721 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001722 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001723 return new ElfFile(elf_file_impl);
1724 } else if (header[EI_CLASS] == ELFCLASS32) {
1725 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file, mmap_prot, mmap_flags, error_msg);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001726 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001727 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001728 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001729 return new ElfFile(elf_file_impl);
1730 } else {
1731 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1732 ELFCLASS32, ELFCLASS64,
1733 file->GetPath().c_str(),
1734 header[EI_CLASS]);
1735 return nullptr;
1736 }
1737}
1738
1739#define DELEGATE_TO_IMPL(func, ...) \
Ian Rogersd4c4d952014-10-16 20:31:53 -07001740 if (elf64_.get() != nullptr) { \
1741 return elf64_->func(__VA_ARGS__); \
Tong Shen62d1ca32014-09-03 17:24:56 -07001742 } else { \
Ian Rogersd4c4d952014-10-16 20:31:53 -07001743 DCHECK(elf32_.get() != nullptr); \
1744 return elf32_->func(__VA_ARGS__); \
Tong Shen62d1ca32014-09-03 17:24:56 -07001745 }
1746
1747bool ElfFile::Load(bool executable, std::string* error_msg) {
1748 DELEGATE_TO_IMPL(Load, executable, error_msg);
1749}
1750
Ian Rogers13735952014-10-08 12:43:28 -07001751const uint8_t* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001752 DELEGATE_TO_IMPL(FindDynamicSymbolAddress, symbol_name);
1753}
1754
1755size_t ElfFile::Size() const {
1756 DELEGATE_TO_IMPL(Size);
1757}
1758
Ian Rogers13735952014-10-08 12:43:28 -07001759uint8_t* ElfFile::Begin() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001760 DELEGATE_TO_IMPL(Begin);
1761}
1762
Ian Rogers13735952014-10-08 12:43:28 -07001763uint8_t* ElfFile::End() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001764 DELEGATE_TO_IMPL(End);
1765}
1766
1767const File& ElfFile::GetFile() const {
1768 DELEGATE_TO_IMPL(GetFile);
1769}
1770
Alex Light0eb76d22015-08-11 18:03:47 -07001771bool ElfFile::GetSectionOffsetAndSize(const char* section_name, uint64_t* offset,
1772 uint64_t* size) const {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001773 if (elf32_.get() == nullptr) {
1774 CHECK(elf64_.get() != nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -07001775
Ian Rogersd4c4d952014-10-16 20:31:53 -07001776 Elf64_Shdr *shdr = elf64_->FindSectionByName(section_name);
1777 if (shdr == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001778 return false;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001779 }
1780 if (offset != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001781 *offset = shdr->sh_offset;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001782 }
1783 if (size != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001784 *size = shdr->sh_size;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001785 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001786 return true;
1787 } else {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001788 Elf32_Shdr *shdr = elf32_->FindSectionByName(section_name);
1789 if (shdr == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001790 return false;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001791 }
1792 if (offset != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001793 *offset = shdr->sh_offset;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001794 }
1795 if (size != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001796 *size = shdr->sh_size;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001797 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001798 return true;
1799 }
1800}
1801
1802uint64_t ElfFile::FindSymbolAddress(unsigned section_type,
1803 const std::string& symbol_name,
1804 bool build_map) {
1805 DELEGATE_TO_IMPL(FindSymbolAddress, section_type, symbol_name, build_map);
1806}
1807
Vladimir Marko3fc99032015-05-13 19:06:30 +01001808bool ElfFile::GetLoadedSize(size_t* size, std::string* error_msg) const {
1809 DELEGATE_TO_IMPL(GetLoadedSize, size, error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001810}
1811
1812bool ElfFile::Strip(File* file, std::string* error_msg) {
1813 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file, true, false, error_msg));
1814 if (elf_file.get() == nullptr) {
1815 return false;
1816 }
1817
Ian Rogersd4c4d952014-10-16 20:31:53 -07001818 if (elf_file->elf64_.get() != nullptr)
1819 return elf_file->elf64_->Strip(error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001820 else
Ian Rogersd4c4d952014-10-16 20:31:53 -07001821 return elf_file->elf32_->Strip(error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001822}
1823
Andreas Gampe3c54b002015-04-07 16:09:30 -07001824bool ElfFile::Fixup(uint64_t base_address) {
1825 if (elf64_.get() != nullptr) {
1826 return elf64_->Fixup(static_cast<Elf64_Addr>(base_address));
1827 } else {
1828 DCHECK(elf32_.get() != nullptr);
1829 CHECK(IsUint<32>(base_address)) << std::hex << base_address;
1830 return elf32_->Fixup(static_cast<Elf32_Addr>(base_address));
1831 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001832 DELEGATE_TO_IMPL(Fixup, base_address);
1833}
1834
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001835} // namespace art