blob: 096f003de3ec29295e1f8e88ea27454fb21dfe7c [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>
Mathieu Chartierbcb6a722016-03-08 16:49:58 -080060ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(File* file,
61 bool writable,
62 bool program_header_only,
63 bool low_4gb,
64 std::string* error_msg,
65 uint8_t* requested_base) {
David Srbecky533c2072015-04-22 12:20:22 +010066 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
67 (file, writable, program_header_only, requested_base));
Brian Carlstrom700c8d32012-11-05 10:42:02 -080068 int prot;
69 int flags;
Alex Light3470ab42014-06-18 10:35:45 -070070 if (writable) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -080071 prot = PROT_READ | PROT_WRITE;
72 flags = MAP_SHARED;
73 } else {
74 prot = PROT_READ;
75 flags = MAP_PRIVATE;
76 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -080077 if (!elf_file->Setup(prot, flags, low_4gb, error_msg)) {
Alex Light3470ab42014-06-18 10:35:45 -070078 return nullptr;
79 }
80 return elf_file.release();
81}
82
David Srbecky533c2072015-04-22 12:20:22 +010083template <typename ElfTypes>
Mathieu Chartierbcb6a722016-03-08 16:49:58 -080084ElfFileImpl<ElfTypes>* ElfFileImpl<ElfTypes>::Open(File* file,
85 int prot,
86 int flags,
87 bool low_4gb,
88 std::string* error_msg) {
David Srbecky533c2072015-04-22 12:20:22 +010089 std::unique_ptr<ElfFileImpl<ElfTypes>> elf_file(new ElfFileImpl<ElfTypes>
90 (file, (prot & PROT_WRITE) == PROT_WRITE, /*program_header_only*/false,
91 /*requested_base*/nullptr));
Mathieu Chartierbcb6a722016-03-08 16:49:58 -080092 if (!elf_file->Setup(prot, flags, low_4gb, error_msg)) {
Alex Light3470ab42014-06-18 10:35:45 -070093 return nullptr;
94 }
95 return elf_file.release();
96}
97
David Srbecky533c2072015-04-22 12:20:22 +010098template <typename ElfTypes>
Mathieu Chartierbcb6a722016-03-08 16:49:58 -080099bool ElfFileImpl<ElfTypes>::Setup(int prot, int flags, bool low_4gb, std::string* error_msg) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800100 int64_t temp_file_length = file_->GetLength();
101 if (temp_file_length < 0) {
102 errno = -temp_file_length;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700103 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
104 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800105 return false;
106 }
Ian Rogerscdfcf372014-01-23 20:38:36 -0800107 size_t file_length = static_cast<size_t>(temp_file_length);
Tong Shen62d1ca32014-09-03 17:24:56 -0700108 if (file_length < sizeof(Elf_Ehdr)) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800109 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF header of "
Tong Shen62d1ca32014-09-03 17:24:56 -0700110 "%zd bytes: '%s'", file_length, sizeof(Elf_Ehdr),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700111 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800112 return false;
113 }
114
Brian Carlstromc1409452014-02-26 14:06:23 -0800115 if (program_header_only_) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800116 // first just map ELF header to get program header size information
Tong Shen62d1ca32014-09-03 17:24:56 -0700117 size_t elf_header_size = sizeof(Elf_Ehdr);
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800118 if (!SetMap(MemMap::MapFile(elf_header_size,
119 prot,
120 flags,
121 file_->Fd(),
122 0,
Mathieu Chartierbcb6a722016-03-08 16:49:58 -0800123 low_4gb,
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800124 file_->GetPath().c_str(),
125 error_msg),
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800126 error_msg)) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800127 return false;
128 }
129 // then remap to cover program header
130 size_t program_header_size = header_->e_phoff + (header_->e_phentsize * header_->e_phnum);
Brian Carlstrom3a223612013-10-10 17:18:24 -0700131 if (file_length < program_header_size) {
Ian Rogerscdfcf372014-01-23 20:38:36 -0800132 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF program "
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700133 "header of %zd bytes: '%s'", file_length,
Tong Shen62d1ca32014-09-03 17:24:56 -0700134 sizeof(Elf_Ehdr), file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -0700135 return false;
136 }
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800137 if (!SetMap(MemMap::MapFile(program_header_size,
138 prot,
139 flags,
140 file_->Fd(),
141 0,
Mathieu Chartierbcb6a722016-03-08 16:49:58 -0800142 low_4gb,
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800143 file_->GetPath().c_str(),
144 error_msg),
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800145 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700146 *error_msg = StringPrintf("Failed to map ELF program headers: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800147 return false;
148 }
149 } else {
150 // otherwise map entire file
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800151 if (!SetMap(MemMap::MapFile(file_->GetLength(),
152 prot,
153 flags,
154 file_->Fd(),
155 0,
Mathieu Chartierbcb6a722016-03-08 16:49:58 -0800156 low_4gb,
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800157 file_->GetPath().c_str(),
158 error_msg),
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800159 error_msg)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700160 *error_msg = StringPrintf("Failed to map ELF file: %s", error_msg->c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800161 return false;
162 }
163 }
164
Andreas Gampedaab38c2014-09-12 18:38:24 -0700165 if (program_header_only_) {
166 program_headers_start_ = Begin() + GetHeader().e_phoff;
167 } else {
168 if (!CheckAndSet(GetHeader().e_phoff, "program headers", &program_headers_start_, error_msg)) {
169 return false;
170 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800171
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800172 // Setup section headers.
Andreas Gampedaab38c2014-09-12 18:38:24 -0700173 if (!CheckAndSet(GetHeader().e_shoff, "section headers", &section_headers_start_, error_msg)) {
174 return false;
175 }
176
177 // Find shstrtab.
Tong Shen62d1ca32014-09-03 17:24:56 -0700178 Elf_Shdr* shstrtab_section_header = GetSectionNameStringSection();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700179 if (shstrtab_section_header == nullptr) {
180 *error_msg = StringPrintf("Failed to find shstrtab section header in ELF file: '%s'",
181 file_->GetPath().c_str());
182 return false;
183 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800184
185 // Find .dynamic section info from program header
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000186 dynamic_program_header_ = FindProgamHeaderByType(PT_DYNAMIC);
Alex Light3470ab42014-06-18 10:35:45 -0700187 if (dynamic_program_header_ == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700188 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
189 file_->GetPath().c_str());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800190 return false;
191 }
192
Andreas Gampedaab38c2014-09-12 18:38:24 -0700193 if (!CheckAndSet(GetDynamicProgramHeader().p_offset, "dynamic section",
Ian Rogers13735952014-10-08 12:43:28 -0700194 reinterpret_cast<uint8_t**>(&dynamic_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700195 return false;
196 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800197
198 // Find other sections from section headers
Tong Shen62d1ca32014-09-03 17:24:56 -0700199 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
200 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700201 if (section_header == nullptr) {
202 *error_msg = StringPrintf("Failed to find section header for section %d in ELF file: '%s'",
203 i, file_->GetPath().c_str());
204 return false;
205 }
206 switch (section_header->sh_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000207 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700208 if (!CheckAndSet(section_header->sh_offset, "symtab",
Ian Rogers13735952014-10-08 12:43:28 -0700209 reinterpret_cast<uint8_t**>(&symtab_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700210 return false;
211 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800212 break;
213 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000214 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700215 if (!CheckAndSet(section_header->sh_offset, "dynsym",
Ian Rogers13735952014-10-08 12:43:28 -0700216 reinterpret_cast<uint8_t**>(&dynsym_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700217 return false;
218 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800219 break;
220 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000221 case SHT_STRTAB: {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800222 // TODO: base these off of sh_link from .symtab and .dynsym above
Andreas Gampedaab38c2014-09-12 18:38:24 -0700223 if ((section_header->sh_flags & SHF_ALLOC) != 0) {
224 // Check that this is named ".dynstr" and ignore otherwise.
225 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
226 if (strncmp(".dynstr", header_name, 8) == 0) {
227 if (!CheckAndSet(section_header->sh_offset, "dynstr",
Ian Rogers13735952014-10-08 12:43:28 -0700228 reinterpret_cast<uint8_t**>(&dynstr_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700229 return false;
230 }
231 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800232 } else {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700233 // Check that this is named ".strtab" and ignore otherwise.
234 const char* header_name = GetString(*shstrtab_section_header, section_header->sh_name);
235 if (strncmp(".strtab", header_name, 8) == 0) {
236 if (!CheckAndSet(section_header->sh_offset, "strtab",
Ian Rogers13735952014-10-08 12:43:28 -0700237 reinterpret_cast<uint8_t**>(&strtab_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700238 return false;
239 }
240 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800241 }
242 break;
243 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000244 case SHT_DYNAMIC: {
Ian Rogers13735952014-10-08 12:43:28 -0700245 if (reinterpret_cast<uint8_t*>(dynamic_section_start_) !=
Andreas Gampedaab38c2014-09-12 18:38:24 -0700246 Begin() + section_header->sh_offset) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800247 LOG(WARNING) << "Failed to find matching SHT_DYNAMIC for PT_DYNAMIC in "
Brian Carlstrom265091e2013-01-30 14:08:26 -0800248 << file_->GetPath() << ": " << std::hex
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800249 << reinterpret_cast<void*>(dynamic_section_start_)
Andreas Gampedaab38c2014-09-12 18:38:24 -0700250 << " != " << reinterpret_cast<void*>(Begin() + section_header->sh_offset);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800251 return false;
252 }
253 break;
254 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000255 case SHT_HASH: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700256 if (!CheckAndSet(section_header->sh_offset, "hash section",
Ian Rogers13735952014-10-08 12:43:28 -0700257 reinterpret_cast<uint8_t**>(&hash_section_start_), error_msg)) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700258 return false;
259 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800260 break;
261 }
262 }
263 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700264
265 // Check for the existence of some sections.
266 if (!CheckSectionsExist(error_msg)) {
267 return false;
268 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800269 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700270
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800271 return true;
272}
273
David Srbecky533c2072015-04-22 12:20:22 +0100274template <typename ElfTypes>
275ElfFileImpl<ElfTypes>::~ElfFileImpl() {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800276 STLDeleteElements(&segments_);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800277 delete symtab_symbol_table_;
278 delete dynsym_symbol_table_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800279}
280
David Srbecky533c2072015-04-22 12:20:22 +0100281template <typename ElfTypes>
282bool ElfFileImpl<ElfTypes>::CheckAndSet(Elf32_Off offset, const char* label,
283 uint8_t** target, std::string* error_msg) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700284 if (Begin() + offset >= End()) {
285 *error_msg = StringPrintf("Offset %d is out of range for %s in ELF file: '%s'", offset, label,
286 file_->GetPath().c_str());
287 return false;
288 }
289 *target = Begin() + offset;
290 return true;
291}
292
David Srbecky533c2072015-04-22 12:20:22 +0100293template <typename ElfTypes>
294bool ElfFileImpl<ElfTypes>::CheckSectionsLinked(const uint8_t* source,
295 const uint8_t* target) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700296 // Only works in whole-program mode, as we need to iterate over the sections.
297 // Note that we normally can't search by type, as duplicates are allowed for most section types.
298 if (program_header_only_) {
299 return true;
300 }
301
Tong Shen62d1ca32014-09-03 17:24:56 -0700302 Elf_Shdr* source_section = nullptr;
303 Elf_Word target_index = 0;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700304 bool target_found = false;
Tong Shen62d1ca32014-09-03 17:24:56 -0700305 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
306 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700307
308 if (Begin() + section_header->sh_offset == source) {
309 // Found the source.
310 source_section = section_header;
311 if (target_index) {
312 break;
313 }
314 } else if (Begin() + section_header->sh_offset == target) {
315 target_index = i;
316 target_found = true;
317 if (source_section != nullptr) {
318 break;
319 }
320 }
321 }
322
323 return target_found && source_section != nullptr && source_section->sh_link == target_index;
324}
325
David Srbecky533c2072015-04-22 12:20:22 +0100326template <typename ElfTypes>
327bool ElfFileImpl<ElfTypes>::CheckSectionsExist(std::string* error_msg) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700328 if (!program_header_only_) {
329 // If in full mode, need section headers.
330 if (section_headers_start_ == nullptr) {
331 *error_msg = StringPrintf("No section headers in ELF file: '%s'", file_->GetPath().c_str());
332 return false;
333 }
334 }
335
336 // This is redundant, but defensive.
337 if (dynamic_program_header_ == nullptr) {
338 *error_msg = StringPrintf("Failed to find PT_DYNAMIC program header in ELF file: '%s'",
339 file_->GetPath().c_str());
340 return false;
341 }
342
343 // Need a dynamic section. This is redundant, but defensive.
344 if (dynamic_section_start_ == nullptr) {
345 *error_msg = StringPrintf("Failed to find dynamic section in ELF file: '%s'",
346 file_->GetPath().c_str());
347 return false;
348 }
349
350 // Symtab validation. These is not really a hard failure, as we are currently not using the
351 // symtab internally, but it's nice to be defensive.
352 if (symtab_section_start_ != nullptr) {
353 // When there's a symtab, there should be a strtab.
354 if (strtab_section_start_ == nullptr) {
355 *error_msg = StringPrintf("No strtab for symtab in ELF file: '%s'", file_->GetPath().c_str());
356 return false;
357 }
358
359 // The symtab should link to the strtab.
Ian Rogers13735952014-10-08 12:43:28 -0700360 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(symtab_section_start_),
361 reinterpret_cast<const uint8_t*>(strtab_section_start_))) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700362 *error_msg = StringPrintf("Symtab is not linked to the strtab in ELF file: '%s'",
363 file_->GetPath().c_str());
364 return false;
365 }
366 }
367
368 // We always need a dynstr & dynsym.
369 if (dynstr_section_start_ == nullptr) {
370 *error_msg = StringPrintf("No dynstr in ELF file: '%s'", file_->GetPath().c_str());
371 return false;
372 }
373 if (dynsym_section_start_ == nullptr) {
374 *error_msg = StringPrintf("No dynsym in ELF file: '%s'", file_->GetPath().c_str());
375 return false;
376 }
377
378 // Need a hash section for dynamic symbol lookup.
379 if (hash_section_start_ == nullptr) {
380 *error_msg = StringPrintf("Failed to find hash section in ELF file: '%s'",
381 file_->GetPath().c_str());
382 return false;
383 }
384
385 // And the hash section should be linking to the dynsym.
Ian Rogers13735952014-10-08 12:43:28 -0700386 if (!CheckSectionsLinked(reinterpret_cast<const uint8_t*>(hash_section_start_),
387 reinterpret_cast<const uint8_t*>(dynsym_section_start_))) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700388 *error_msg = StringPrintf("Hash section is not linked to the dynstr in ELF file: '%s'",
389 file_->GetPath().c_str());
390 return false;
391 }
392
Andreas Gampea696c0a2014-12-10 20:51:45 -0800393 // We'd also like to confirm a shstrtab in program_header_only_ mode (else Open() does this for
394 // us). This is usually the last in an oat file, and a good indicator of whether writing was
395 // successful (or the process crashed and left garbage).
396 if (program_header_only_) {
397 // It might not be mapped, but we can compare against the file size.
398 int64_t offset = static_cast<int64_t>(GetHeader().e_shoff +
399 (GetHeader().e_shstrndx * GetHeader().e_shentsize));
400 if (offset >= file_->GetLength()) {
401 *error_msg = StringPrintf("Shstrtab is not in the mapped ELF file: '%s'",
402 file_->GetPath().c_str());
403 return false;
404 }
405 }
406
Andreas Gampedaab38c2014-09-12 18:38:24 -0700407 return true;
408}
409
David Srbecky533c2072015-04-22 12:20:22 +0100410template <typename ElfTypes>
411bool ElfFileImpl<ElfTypes>::SetMap(MemMap* map, std::string* error_msg) {
Alex Light3470ab42014-06-18 10:35:45 -0700412 if (map == nullptr) {
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800413 // MemMap::Open should have already set an error.
414 DCHECK(!error_msg->empty());
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800415 return false;
416 }
417 map_.reset(map);
Alex Light3470ab42014-06-18 10:35:45 -0700418 CHECK(map_.get() != nullptr) << file_->GetPath();
419 CHECK(map_->Begin() != nullptr) << file_->GetPath();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800420
Tong Shen62d1ca32014-09-03 17:24:56 -0700421 header_ = reinterpret_cast<Elf_Ehdr*>(map_->Begin());
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000422 if ((ELFMAG0 != header_->e_ident[EI_MAG0])
423 || (ELFMAG1 != header_->e_ident[EI_MAG1])
424 || (ELFMAG2 != header_->e_ident[EI_MAG2])
425 || (ELFMAG3 != header_->e_ident[EI_MAG3])) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800426 *error_msg = StringPrintf("Failed to find ELF magic value %d %d %d %d in %s, found %d %d %d %d",
427 ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
Brian Carlstromd0c09dc2013-11-06 18:25:35 -0800428 file_->GetPath().c_str(),
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000429 header_->e_ident[EI_MAG0],
430 header_->e_ident[EI_MAG1],
431 header_->e_ident[EI_MAG2],
432 header_->e_ident[EI_MAG3]);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800433 return false;
434 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700435 uint8_t elf_class = (sizeof(Elf_Addr) == sizeof(Elf64_Addr)) ? ELFCLASS64 : ELFCLASS32;
436 if (elf_class != header_->e_ident[EI_CLASS]) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800437 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d in %s, found %d",
Tong Shen62d1ca32014-09-03 17:24:56 -0700438 elf_class,
Brian Carlstromc1409452014-02-26 14:06:23 -0800439 file_->GetPath().c_str(),
440 header_->e_ident[EI_CLASS]);
441 return false;
442 }
443 if (ELFDATA2LSB != header_->e_ident[EI_DATA]) {
444 *error_msg = StringPrintf("Failed to find expected EI_DATA value %d in %s, found %d",
445 ELFDATA2LSB,
446 file_->GetPath().c_str(),
447 header_->e_ident[EI_CLASS]);
448 return false;
449 }
450 if (EV_CURRENT != header_->e_ident[EI_VERSION]) {
451 *error_msg = StringPrintf("Failed to find expected EI_VERSION value %d in %s, found %d",
452 EV_CURRENT,
453 file_->GetPath().c_str(),
454 header_->e_ident[EI_CLASS]);
455 return false;
456 }
457 if (ET_DYN != header_->e_type) {
458 *error_msg = StringPrintf("Failed to find expected e_type value %d in %s, found %d",
459 ET_DYN,
460 file_->GetPath().c_str(),
461 header_->e_type);
462 return false;
463 }
464 if (EV_CURRENT != header_->e_version) {
465 *error_msg = StringPrintf("Failed to find expected e_version value %d in %s, found %d",
466 EV_CURRENT,
467 file_->GetPath().c_str(),
468 header_->e_version);
469 return false;
470 }
471 if (0 != header_->e_entry) {
472 *error_msg = StringPrintf("Failed to find expected e_entry value %d in %s, found %d",
473 0,
474 file_->GetPath().c_str(),
Tong Shen62d1ca32014-09-03 17:24:56 -0700475 static_cast<int32_t>(header_->e_entry));
Brian Carlstromc1409452014-02-26 14:06:23 -0800476 return false;
477 }
478 if (0 == header_->e_phoff) {
479 *error_msg = StringPrintf("Failed to find non-zero e_phoff value in %s",
480 file_->GetPath().c_str());
481 return false;
482 }
483 if (0 == header_->e_shoff) {
484 *error_msg = StringPrintf("Failed to find non-zero e_shoff value in %s",
485 file_->GetPath().c_str());
486 return false;
487 }
488 if (0 == header_->e_ehsize) {
489 *error_msg = StringPrintf("Failed to find non-zero e_ehsize value in %s",
490 file_->GetPath().c_str());
491 return false;
492 }
493 if (0 == header_->e_phentsize) {
494 *error_msg = StringPrintf("Failed to find non-zero e_phentsize value in %s",
495 file_->GetPath().c_str());
496 return false;
497 }
498 if (0 == header_->e_phnum) {
499 *error_msg = StringPrintf("Failed to find non-zero e_phnum value in %s",
500 file_->GetPath().c_str());
501 return false;
502 }
503 if (0 == header_->e_shentsize) {
504 *error_msg = StringPrintf("Failed to find non-zero e_shentsize value in %s",
505 file_->GetPath().c_str());
506 return false;
507 }
508 if (0 == header_->e_shnum) {
509 *error_msg = StringPrintf("Failed to find non-zero e_shnum value in %s",
510 file_->GetPath().c_str());
511 return false;
512 }
513 if (0 == header_->e_shstrndx) {
514 *error_msg = StringPrintf("Failed to find non-zero e_shstrndx value in %s",
515 file_->GetPath().c_str());
516 return false;
517 }
518 if (header_->e_shstrndx >= header_->e_shnum) {
519 *error_msg = StringPrintf("Failed to find e_shnum value %d less than %d in %s",
520 header_->e_shstrndx,
521 header_->e_shnum,
522 file_->GetPath().c_str());
523 return false;
524 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800525
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800526 if (!program_header_only_) {
Brian Carlstromc1409452014-02-26 14:06:23 -0800527 if (header_->e_phoff >= Size()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700528 *error_msg = StringPrintf("Failed to find e_phoff value %" PRIu64 " less than %zd in %s",
529 static_cast<uint64_t>(header_->e_phoff),
Brian Carlstromc1409452014-02-26 14:06:23 -0800530 Size(),
531 file_->GetPath().c_str());
532 return false;
533 }
534 if (header_->e_shoff >= Size()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700535 *error_msg = StringPrintf("Failed to find e_shoff value %" PRIu64 " less than %zd in %s",
536 static_cast<uint64_t>(header_->e_shoff),
Brian Carlstromc1409452014-02-26 14:06:23 -0800537 Size(),
538 file_->GetPath().c_str());
539 return false;
540 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800541 }
542 return true;
543}
544
David Srbecky533c2072015-04-22 12:20:22 +0100545template <typename ElfTypes>
546typename ElfTypes::Ehdr& ElfFileImpl<ElfTypes>::GetHeader() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700547 CHECK(header_ != nullptr); // Header has been checked in SetMap. This is a sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800548 return *header_;
549}
550
David Srbecky533c2072015-04-22 12:20:22 +0100551template <typename ElfTypes>
552uint8_t* ElfFileImpl<ElfTypes>::GetProgramHeadersStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700553 CHECK(program_headers_start_ != nullptr); // Header has been set in Setup. This is a sanity
554 // check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800555 return program_headers_start_;
556}
557
David Srbecky533c2072015-04-22 12:20:22 +0100558template <typename ElfTypes>
559uint8_t* ElfFileImpl<ElfTypes>::GetSectionHeadersStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700560 CHECK(!program_header_only_); // Only used in "full" mode.
561 CHECK(section_headers_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800562 return section_headers_start_;
563}
564
David Srbecky533c2072015-04-22 12:20:22 +0100565template <typename ElfTypes>
566typename ElfTypes::Phdr& ElfFileImpl<ElfTypes>::GetDynamicProgramHeader() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700567 CHECK(dynamic_program_header_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800568 return *dynamic_program_header_;
569}
570
David Srbecky533c2072015-04-22 12:20:22 +0100571template <typename ElfTypes>
572typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::GetDynamicSectionStart() const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700573 CHECK(dynamic_section_start_ != nullptr); // Is checked in CheckSectionsExist. Sanity check.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800574 return dynamic_section_start_;
575}
576
David Srbecky533c2072015-04-22 12:20:22 +0100577template <typename ElfTypes>
578typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbolSectionStart(
579 Elf_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800580 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800581 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000582 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700583 return symtab_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800584 break;
585 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000586 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700587 return dynsym_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800588 break;
589 }
590 default: {
591 LOG(FATAL) << section_type;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700592 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800593 }
594 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800595}
596
David Srbecky533c2072015-04-22 12:20:22 +0100597template <typename ElfTypes>
598const char* ElfFileImpl<ElfTypes>::GetStringSectionStart(
599 Elf_Word section_type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800600 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800601 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000602 case SHT_SYMTAB: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700603 return strtab_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800604 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000605 case SHT_DYNSYM: {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700606 return dynstr_section_start_;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800607 }
608 default: {
609 LOG(FATAL) << section_type;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700610 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800611 }
612 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800613}
614
David Srbecky533c2072015-04-22 12:20:22 +0100615template <typename ElfTypes>
616const char* ElfFileImpl<ElfTypes>::GetString(Elf_Word section_type,
617 Elf_Word i) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800618 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
619 if (i == 0) {
Alex Light3470ab42014-06-18 10:35:45 -0700620 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800621 }
622 const char* string_section_start = GetStringSectionStart(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700623 if (string_section_start == nullptr) {
624 return nullptr;
625 }
626 return string_section_start + i;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800627}
628
Andreas Gampedaab38c2014-09-12 18:38:24 -0700629// WARNING: The following methods do not check for an error condition (non-existent hash section).
630// It is the caller's job to do this.
631
David Srbecky533c2072015-04-22 12:20:22 +0100632template <typename ElfTypes>
633typename ElfTypes::Word* ElfFileImpl<ElfTypes>::GetHashSectionStart() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800634 return hash_section_start_;
635}
636
David Srbecky533c2072015-04-22 12:20:22 +0100637template <typename ElfTypes>
638typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucketNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800639 return GetHashSectionStart()[0];
640}
641
David Srbecky533c2072015-04-22 12:20:22 +0100642template <typename ElfTypes>
643typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChainNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800644 return GetHashSectionStart()[1];
645}
646
David Srbecky533c2072015-04-22 12:20:22 +0100647template <typename ElfTypes>
648typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashBucket(size_t i, bool* ok) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700649 if (i >= GetHashBucketNum()) {
650 *ok = false;
651 return 0;
652 }
653 *ok = true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800654 // 0 is nbucket, 1 is nchain
655 return GetHashSectionStart()[2 + i];
656}
657
David Srbecky533c2072015-04-22 12:20:22 +0100658template <typename ElfTypes>
659typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetHashChain(size_t i, bool* ok) const {
Yevgeny Roubanacb01382014-11-24 13:40:56 +0600660 if (i >= GetHashChainNum()) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700661 *ok = false;
662 return 0;
663 }
664 *ok = true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800665 // 0 is nbucket, 1 is nchain, & chains are after buckets
666 return GetHashSectionStart()[2 + GetHashBucketNum() + i];
667}
668
David Srbecky533c2072015-04-22 12:20:22 +0100669template <typename ElfTypes>
670typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetProgramHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800671 return GetHeader().e_phnum;
672}
673
David Srbecky533c2072015-04-22 12:20:22 +0100674template <typename ElfTypes>
675typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::GetProgramHeader(Elf_Word i) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700676 CHECK_LT(i, GetProgramHeaderNum()) << file_->GetPath(); // Sanity check for caller.
Ian Rogers13735952014-10-08 12:43:28 -0700677 uint8_t* program_header = GetProgramHeadersStart() + (i * GetHeader().e_phentsize);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700678 if (program_header >= End()) {
679 return nullptr; // Failure condition.
680 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700681 return reinterpret_cast<Elf_Phdr*>(program_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800682}
683
David Srbecky533c2072015-04-22 12:20:22 +0100684template <typename ElfTypes>
685typename ElfTypes::Phdr* ElfFileImpl<ElfTypes>::FindProgamHeaderByType(Elf_Word type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700686 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
687 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700688 if (program_header->p_type == type) {
689 return program_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800690 }
691 }
Alex Light3470ab42014-06-18 10:35:45 -0700692 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800693}
694
David Srbecky533c2072015-04-22 12:20:22 +0100695template <typename ElfTypes>
696typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSectionHeaderNum() const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800697 return GetHeader().e_shnum;
698}
699
David Srbecky533c2072015-04-22 12:20:22 +0100700template <typename ElfTypes>
701typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionHeader(Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800702 // Can only access arbitrary sections when we have the whole file, not just program header.
703 // Even if we Load(), it doesn't bring in all the sections.
704 CHECK(!program_header_only_) << file_->GetPath();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700705 if (i >= GetSectionHeaderNum()) {
706 return nullptr; // Failure condition.
707 }
Ian Rogers13735952014-10-08 12:43:28 -0700708 uint8_t* section_header = GetSectionHeadersStart() + (i * GetHeader().e_shentsize);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700709 if (section_header >= End()) {
710 return nullptr; // Failure condition.
711 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700712 return reinterpret_cast<Elf_Shdr*>(section_header);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800713}
714
David Srbecky533c2072015-04-22 12:20:22 +0100715template <typename ElfTypes>
716typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByType(Elf_Word type) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800717 // Can only access arbitrary sections when we have the whole file, not just program header.
718 // We could change this to switch on known types if they were detected during loading.
719 CHECK(!program_header_only_) << file_->GetPath();
Tong Shen62d1ca32014-09-03 17:24:56 -0700720 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
721 Elf_Shdr* section_header = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700722 if (section_header->sh_type == type) {
723 return section_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800724 }
725 }
Alex Light3470ab42014-06-18 10:35:45 -0700726 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800727}
728
729// from bionic
Brian Carlstrom265091e2013-01-30 14:08:26 -0800730static unsigned elfhash(const char *_name) {
731 const unsigned char *name = (const unsigned char *) _name;
732 unsigned h = 0, g;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800733
Brian Carlstromdf629502013-07-17 22:39:56 -0700734 while (*name) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800735 h = (h << 4) + *name++;
736 g = h & 0xf0000000;
737 h ^= g;
738 h ^= g >> 24;
739 }
740 return h;
741}
742
David Srbecky533c2072015-04-22 12:20:22 +0100743template <typename ElfTypes>
744typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::GetSectionNameStringSection() const {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800745 return GetSectionHeader(GetHeader().e_shstrndx);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800746}
747
David Srbecky533c2072015-04-22 12:20:22 +0100748template <typename ElfTypes>
749const uint8_t* ElfFileImpl<ElfTypes>::FindDynamicSymbolAddress(
750 const std::string& symbol_name) const {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700751 // Check that we have a hash section.
752 if (GetHashSectionStart() == nullptr) {
753 return nullptr; // Failure condition.
754 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700755 const Elf_Sym* sym = FindDynamicSymbol(symbol_name);
Alex Light3470ab42014-06-18 10:35:45 -0700756 if (sym != nullptr) {
Igor Murashkin46774762014-10-22 11:37:02 -0700757 // TODO: we need to change this to calculate base_address_ in ::Open,
758 // otherwise it will be wrongly 0 if ::Load has not yet been called.
Alex Light3470ab42014-06-18 10:35:45 -0700759 return base_address_ + sym->st_value;
760 } else {
761 return nullptr;
762 }
763}
764
Andreas Gampedaab38c2014-09-12 18:38:24 -0700765// WARNING: Only called from FindDynamicSymbolAddress. Elides check for hash section.
David Srbecky533c2072015-04-22 12:20:22 +0100766template <typename ElfTypes>
767const typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindDynamicSymbol(
768 const std::string& symbol_name) const {
Andreas Gampec48b2062014-09-08 23:39:45 -0700769 if (GetHashBucketNum() == 0) {
770 // No dynamic symbols at all.
771 return nullptr;
772 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700773 Elf_Word hash = elfhash(symbol_name.c_str());
774 Elf_Word bucket_index = hash % GetHashBucketNum();
Andreas Gampedaab38c2014-09-12 18:38:24 -0700775 bool ok;
Tong Shen62d1ca32014-09-03 17:24:56 -0700776 Elf_Word symbol_and_chain_index = GetHashBucket(bucket_index, &ok);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700777 if (!ok) {
778 return nullptr;
779 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800780 while (symbol_and_chain_index != 0 /* STN_UNDEF */) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700781 Elf_Sym* symbol = GetSymbol(SHT_DYNSYM, symbol_and_chain_index);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700782 if (symbol == nullptr) {
783 return nullptr; // Failure condition.
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800784 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700785 const char* name = GetString(SHT_DYNSYM, symbol->st_name);
786 if (symbol_name == name) {
787 return symbol;
788 }
789 symbol_and_chain_index = GetHashChain(symbol_and_chain_index, &ok);
790 if (!ok) {
791 return nullptr;
792 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800793 }
Alex Light3470ab42014-06-18 10:35:45 -0700794 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800795}
796
David Srbecky533c2072015-04-22 12:20:22 +0100797template <typename ElfTypes>
798bool ElfFileImpl<ElfTypes>::IsSymbolSectionType(Elf_Word section_type) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700799 return ((section_type == SHT_SYMTAB) || (section_type == SHT_DYNSYM));
800}
801
David Srbecky533c2072015-04-22 12:20:22 +0100802template <typename ElfTypes>
803typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetSymbolNum(Elf_Shdr& section_header) const {
Brian Carlstromc1409452014-02-26 14:06:23 -0800804 CHECK(IsSymbolSectionType(section_header.sh_type))
805 << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800806 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
807 return section_header.sh_size / section_header.sh_entsize;
808}
809
David Srbecky533c2072015-04-22 12:20:22 +0100810template <typename ElfTypes>
811typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::GetSymbol(Elf_Word section_type, Elf_Word i) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700812 Elf_Sym* sym_start = GetSymbolSectionStart(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700813 if (sym_start == nullptr) {
814 return nullptr;
815 }
816 return sym_start + i;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800817}
818
David Srbecky533c2072015-04-22 12:20:22 +0100819template <typename ElfTypes>
820typename ElfFileImpl<ElfTypes>::SymbolTable**
821ElfFileImpl<ElfTypes>::GetSymbolTable(Elf_Word section_type) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800822 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
823 switch (section_type) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000824 case SHT_SYMTAB: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800825 return &symtab_symbol_table_;
826 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000827 case SHT_DYNSYM: {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800828 return &dynsym_symbol_table_;
829 }
830 default: {
831 LOG(FATAL) << section_type;
Alex Light3470ab42014-06-18 10:35:45 -0700832 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800833 }
834 }
835}
836
David Srbecky533c2072015-04-22 12:20:22 +0100837template <typename ElfTypes>
838typename ElfTypes::Sym* ElfFileImpl<ElfTypes>::FindSymbolByName(
839 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800840 CHECK(!program_header_only_) << file_->GetPath();
841 CHECK(IsSymbolSectionType(section_type)) << file_->GetPath() << " " << section_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800842
843 SymbolTable** symbol_table = GetSymbolTable(section_type);
Alex Light3470ab42014-06-18 10:35:45 -0700844 if (*symbol_table != nullptr || build_map) {
845 if (*symbol_table == nullptr) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800846 DCHECK(build_map);
847 *symbol_table = new SymbolTable;
Tong Shen62d1ca32014-09-03 17:24:56 -0700848 Elf_Shdr* symbol_section = FindSectionByType(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700849 if (symbol_section == nullptr) {
850 return nullptr; // Failure condition.
851 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700852 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700853 if (string_section == nullptr) {
854 return nullptr; // Failure condition.
855 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800856 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700857 Elf_Sym* symbol = GetSymbol(section_type, i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700858 if (symbol == nullptr) {
859 return nullptr; // Failure condition.
860 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700861 unsigned char type = (sizeof(Elf_Addr) == sizeof(Elf64_Addr))
862 ? ELF64_ST_TYPE(symbol->st_info)
863 : ELF32_ST_TYPE(symbol->st_info);
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000864 if (type == STT_NOTYPE) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800865 continue;
866 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700867 const char* name = GetString(*string_section, symbol->st_name);
Alex Light3470ab42014-06-18 10:35:45 -0700868 if (name == nullptr) {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800869 continue;
870 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700871 std::pair<typename SymbolTable::iterator, bool> result =
Andreas Gampedaab38c2014-09-12 18:38:24 -0700872 (*symbol_table)->insert(std::make_pair(name, symbol));
Brian Carlstrom265091e2013-01-30 14:08:26 -0800873 if (!result.second) {
874 // If a duplicate, make sure it has the same logical value. Seen on x86.
Andreas Gampedaab38c2014-09-12 18:38:24 -0700875 if ((symbol->st_value != result.first->second->st_value) ||
876 (symbol->st_size != result.first->second->st_size) ||
877 (symbol->st_info != result.first->second->st_info) ||
878 (symbol->st_other != result.first->second->st_other) ||
879 (symbol->st_shndx != result.first->second->st_shndx)) {
880 return nullptr; // Failure condition.
881 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800882 }
883 }
884 }
Alex Light3470ab42014-06-18 10:35:45 -0700885 CHECK(*symbol_table != nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -0700886 typename SymbolTable::const_iterator it = (*symbol_table)->find(symbol_name);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800887 if (it == (*symbol_table)->end()) {
Alex Light3470ab42014-06-18 10:35:45 -0700888 return nullptr;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800889 }
890 return it->second;
891 }
892
893 // Fall back to linear search
Tong Shen62d1ca32014-09-03 17:24:56 -0700894 Elf_Shdr* symbol_section = FindSectionByType(section_type);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700895 if (symbol_section == nullptr) {
896 return nullptr;
897 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700898 Elf_Shdr* string_section = GetSectionHeader(symbol_section->sh_link);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700899 if (string_section == nullptr) {
900 return nullptr;
901 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800902 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700903 Elf_Sym* symbol = GetSymbol(section_type, i);
Andreas Gampedaab38c2014-09-12 18:38:24 -0700904 if (symbol == nullptr) {
905 return nullptr; // Failure condition.
906 }
907 const char* name = GetString(*string_section, symbol->st_name);
Alex Light3470ab42014-06-18 10:35:45 -0700908 if (name == nullptr) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800909 continue;
910 }
911 if (symbol_name == name) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700912 return symbol;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800913 }
914 }
Alex Light3470ab42014-06-18 10:35:45 -0700915 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800916}
917
David Srbecky533c2072015-04-22 12:20:22 +0100918template <typename ElfTypes>
919typename ElfTypes::Addr ElfFileImpl<ElfTypes>::FindSymbolAddress(
920 Elf_Word section_type, const std::string& symbol_name, bool build_map) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700921 Elf_Sym* symbol = FindSymbolByName(section_type, symbol_name, build_map);
Alex Light3470ab42014-06-18 10:35:45 -0700922 if (symbol == nullptr) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800923 return 0;
924 }
925 return symbol->st_value;
926}
927
David Srbecky533c2072015-04-22 12:20:22 +0100928template <typename ElfTypes>
929const char* ElfFileImpl<ElfTypes>::GetString(Elf_Shdr& string_section,
930 Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800931 CHECK(!program_header_only_) << file_->GetPath();
932 // TODO: remove this static_cast from enum when using -std=gnu++0x
Tong Shen62d1ca32014-09-03 17:24:56 -0700933 if (static_cast<Elf_Word>(SHT_STRTAB) != string_section.sh_type) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700934 return nullptr; // Failure condition.
935 }
936 if (i >= string_section.sh_size) {
937 return nullptr;
938 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800939 if (i == 0) {
Alex Light3470ab42014-06-18 10:35:45 -0700940 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800941 }
Ian Rogers13735952014-10-08 12:43:28 -0700942 uint8_t* strings = Begin() + string_section.sh_offset;
943 uint8_t* string = strings + i;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700944 if (string >= End()) {
945 return nullptr;
946 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800947 return reinterpret_cast<const char*>(string);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800948}
949
David Srbecky533c2072015-04-22 12:20:22 +0100950template <typename ElfTypes>
951typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetDynamicNum() const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700952 return GetDynamicProgramHeader().p_filesz / sizeof(Elf_Dyn);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800953}
954
David Srbecky533c2072015-04-22 12:20:22 +0100955template <typename ElfTypes>
956typename ElfTypes::Dyn& ElfFileImpl<ElfTypes>::GetDynamic(Elf_Word i) const {
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800957 CHECK_LT(i, GetDynamicNum()) << file_->GetPath();
958 return *(GetDynamicSectionStart() + i);
959}
960
David Srbecky533c2072015-04-22 12:20:22 +0100961template <typename ElfTypes>
962typename ElfTypes::Dyn* ElfFileImpl<ElfTypes>::FindDynamicByType(Elf_Sword type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700963 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
964 Elf_Dyn* dyn = &GetDynamic(i);
Alex Light53cb16b2014-06-12 11:26:29 -0700965 if (dyn->d_tag == type) {
966 return dyn;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800967 }
968 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700969 return nullptr;
Alex Light53cb16b2014-06-12 11:26:29 -0700970}
971
David Srbecky533c2072015-04-22 12:20:22 +0100972template <typename ElfTypes>
973typename ElfTypes::Word ElfFileImpl<ElfTypes>::FindDynamicValueByType(Elf_Sword type) const {
Tong Shen62d1ca32014-09-03 17:24:56 -0700974 Elf_Dyn* dyn = FindDynamicByType(type);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700975 if (dyn == nullptr) {
Alex Light53cb16b2014-06-12 11:26:29 -0700976 return 0;
977 } else {
978 return dyn->d_un.d_val;
979 }
Brian Carlstrom265091e2013-01-30 14:08:26 -0800980}
981
David Srbecky533c2072015-04-22 12:20:22 +0100982template <typename ElfTypes>
983typename ElfTypes::Rel* ElfFileImpl<ElfTypes>::GetRelSectionStart(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;
Tong Shen62d1ca32014-09-03 17:24:56 -0700985 return reinterpret_cast<Elf_Rel*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -0800986}
987
David Srbecky533c2072015-04-22 12:20:22 +0100988template <typename ElfTypes>
989typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelNum(Elf_Shdr& section_header) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000990 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800991 CHECK_NE(0U, section_header.sh_entsize) << file_->GetPath();
992 return section_header.sh_size / section_header.sh_entsize;
993}
994
David Srbecky533c2072015-04-22 12:20:22 +0100995template <typename ElfTypes>
996typename ElfTypes::Rel& ElfFileImpl<ElfTypes>::GetRel(Elf_Shdr& section_header, Elf_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000997 CHECK(SHT_REL == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -0800998 CHECK_LT(i, GetRelNum(section_header)) << file_->GetPath();
999 return *(GetRelSectionStart(section_header) + i);
1000}
1001
David Srbecky533c2072015-04-22 12:20:22 +01001002template <typename ElfTypes>
1003typename ElfTypes::Rela* ElfFileImpl<ElfTypes>::GetRelaSectionStart(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;
Tong Shen62d1ca32014-09-03 17:24:56 -07001005 return reinterpret_cast<Elf_Rela*>(Begin() + section_header.sh_offset);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001006}
1007
David Srbecky533c2072015-04-22 12:20:22 +01001008template <typename ElfTypes>
1009typename ElfTypes::Word ElfFileImpl<ElfTypes>::GetRelaNum(Elf_Shdr& section_header) 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 return section_header.sh_size / section_header.sh_entsize;
1012}
1013
David Srbecky533c2072015-04-22 12:20:22 +01001014template <typename ElfTypes>
1015typename ElfTypes::Rela& ElfFileImpl<ElfTypes>::GetRela(Elf_Shdr& section_header, Elf_Word i) const {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001016 CHECK(SHT_RELA == section_header.sh_type) << file_->GetPath() << " " << section_header.sh_type;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001017 CHECK_LT(i, GetRelaNum(section_header)) << file_->GetPath();
1018 return *(GetRelaSectionStart(section_header) + i);
1019}
1020
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001021// Base on bionic phdr_table_get_load_size
David Srbecky533c2072015-04-22 12:20:22 +01001022template <typename ElfTypes>
Vladimir Marko3fc99032015-05-13 19:06:30 +01001023bool ElfFileImpl<ElfTypes>::GetLoadedSize(size_t* size, std::string* error_msg) const {
1024 Elf_Addr min_vaddr = static_cast<Elf_Addr>(-1);
1025 Elf_Addr max_vaddr = 0u;
Tong Shen62d1ca32014-09-03 17:24:56 -07001026 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1027 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001028 if (program_header->p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001029 continue;
1030 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001031 Elf_Addr begin_vaddr = program_header->p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001032 if (begin_vaddr < min_vaddr) {
1033 min_vaddr = begin_vaddr;
1034 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001035 Elf_Addr end_vaddr = program_header->p_vaddr + program_header->p_memsz;
Vladimir Marko3fc99032015-05-13 19:06:30 +01001036 if (UNLIKELY(begin_vaddr > end_vaddr)) {
1037 std::ostringstream oss;
1038 oss << "Program header #" << i << " has overflow in p_vaddr+p_memsz: 0x" << std::hex
1039 << program_header->p_vaddr << "+0x" << program_header->p_memsz << "=0x" << end_vaddr
1040 << " in ELF file \"" << file_->GetPath() << "\"";
1041 *error_msg = oss.str();
1042 *size = static_cast<size_t>(-1);
1043 return false;
1044 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001045 if (end_vaddr > max_vaddr) {
1046 max_vaddr = end_vaddr;
1047 }
1048 }
1049 min_vaddr = RoundDown(min_vaddr, kPageSize);
1050 max_vaddr = RoundUp(max_vaddr, kPageSize);
1051 CHECK_LT(min_vaddr, max_vaddr) << file_->GetPath();
Vladimir Marko3fc99032015-05-13 19:06:30 +01001052 Elf_Addr loaded_size = max_vaddr - min_vaddr;
1053 // Check that the loaded_size fits in size_t.
1054 if (UNLIKELY(loaded_size > std::numeric_limits<size_t>::max())) {
1055 std::ostringstream oss;
1056 oss << "Loaded size is 0x" << std::hex << loaded_size << " but maximum size_t is 0x"
1057 << std::numeric_limits<size_t>::max() << " for ELF file \"" << file_->GetPath() << "\"";
1058 *error_msg = oss.str();
1059 *size = static_cast<size_t>(-1);
1060 return false;
1061 }
1062 *size = loaded_size;
1063 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001064}
1065
David Srbecky533c2072015-04-22 12:20:22 +01001066template <typename ElfTypes>
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001067bool ElfFileImpl<ElfTypes>::Load(bool executable, bool low_4gb, std::string* error_msg) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001068 CHECK(program_header_only_) << file_->GetPath();
Andreas Gampe91268c12014-04-03 17:50:24 -07001069
1070 if (executable) {
Andreas Gampe6f611412015-01-21 22:25:24 -08001071 InstructionSet elf_ISA = GetInstructionSetFromELF(GetHeader().e_machine, GetHeader().e_flags);
Andreas Gampe91268c12014-04-03 17:50:24 -07001072 if (elf_ISA != kRuntimeISA) {
1073 std::ostringstream oss;
1074 oss << "Expected ISA " << kRuntimeISA << " but found " << elf_ISA;
1075 *error_msg = oss.str();
1076 return false;
1077 }
1078 }
1079
Jim_Guoa62a5882014-04-28 11:11:57 +08001080 bool reserved = false;
Tong Shen62d1ca32014-09-03 17:24:56 -07001081 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1082 Elf_Phdr* program_header = GetProgramHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001083 if (program_header == nullptr) {
1084 *error_msg = StringPrintf("No program header for entry %d in ELF file %s.",
1085 i, file_->GetPath().c_str());
1086 return false;
1087 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001088
1089 // Record .dynamic header information for later use
Andreas Gampedaab38c2014-09-12 18:38:24 -07001090 if (program_header->p_type == PT_DYNAMIC) {
1091 dynamic_program_header_ = program_header;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001092 continue;
1093 }
1094
1095 // Not something to load, move on.
Andreas Gampedaab38c2014-09-12 18:38:24 -07001096 if (program_header->p_type != PT_LOAD) {
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001097 continue;
1098 }
1099
1100 // Found something to load.
1101
Jim_Guoa62a5882014-04-28 11:11:57 +08001102 // Before load the actual segments, reserve a contiguous chunk
1103 // of required size and address for all segments, but with no
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001104 // permissions. We'll then carve that up with the proper
1105 // permissions as we load the actual segments. If p_vaddr is
1106 // non-zero, the segments require the specific address specified,
1107 // which either was specified in the file because we already set
1108 // base_address_ after the first zero segment).
Ian Rogerscdfcf372014-01-23 20:38:36 -08001109 int64_t temp_file_length = file_->GetLength();
1110 if (temp_file_length < 0) {
1111 errno = -temp_file_length;
1112 *error_msg = StringPrintf("Failed to get length of file: '%s' fd=%d: %s",
1113 file_->GetPath().c_str(), file_->Fd(), strerror(errno));
1114 return false;
1115 }
1116 size_t file_length = static_cast<size_t>(temp_file_length);
Jim_Guoa62a5882014-04-28 11:11:57 +08001117 if (!reserved) {
Igor Murashkin46774762014-10-22 11:37:02 -07001118 uint8_t* reserve_base = reinterpret_cast<uint8_t*>(program_header->p_vaddr);
1119 uint8_t* reserve_base_override = reserve_base;
1120 // Override the base (e.g. when compiling with --compile-pic)
1121 if (requested_base_ != nullptr) {
1122 reserve_base_override = requested_base_;
1123 }
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001124 std::string reservation_name("ElfFile reservation for ");
1125 reservation_name += file_->GetPath();
Vladimir Marko3fc99032015-05-13 19:06:30 +01001126 size_t loaded_size;
1127 if (!GetLoadedSize(&loaded_size, error_msg)) {
1128 DCHECK(!error_msg->empty());
1129 return false;
1130 }
Ian Rogers700a4022014-05-19 16:49:03 -07001131 std::unique_ptr<MemMap> reserve(MemMap::MapAnonymous(reservation_name.c_str(),
Igor Murashkin46774762014-10-22 11:37:02 -07001132 reserve_base_override,
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001133 loaded_size,
1134 PROT_NONE,
1135 low_4gb,
1136 false,
Jim_Guoa62a5882014-04-28 11:11:57 +08001137 error_msg));
Brian Carlstromc1409452014-02-26 14:06:23 -08001138 if (reserve.get() == nullptr) {
1139 *error_msg = StringPrintf("Failed to allocate %s: %s",
1140 reservation_name.c_str(), error_msg->c_str());
1141 return false;
1142 }
Jim_Guoa62a5882014-04-28 11:11:57 +08001143 reserved = true;
Igor Murashkin46774762014-10-22 11:37:02 -07001144
1145 // Base address is the difference of actual mapped location and the p_vaddr
1146 base_address_ = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(reserve->Begin())
1147 - reinterpret_cast<uintptr_t>(reserve_base));
1148 // By adding the p_vaddr of a section/symbol to base_address_ we will always get the
1149 // dynamic memory address of where that object is actually mapped
1150 //
1151 // TODO: base_address_ needs to be calculated in ::Open, otherwise
1152 // FindDynamicSymbolAddress returns the wrong values until Load is called.
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001153 segments_.push_back(reserve.release());
1154 }
1155 // empty segment, nothing to map
Andreas Gampedaab38c2014-09-12 18:38:24 -07001156 if (program_header->p_memsz == 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001157 continue;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001158 }
Ian Rogers13735952014-10-08 12:43:28 -07001159 uint8_t* p_vaddr = base_address_ + program_header->p_vaddr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001160 int prot = 0;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001161 if (executable && ((program_header->p_flags & PF_X) != 0)) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001162 prot |= PROT_EXEC;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001163 }
Andreas Gampedaab38c2014-09-12 18:38:24 -07001164 if ((program_header->p_flags & PF_W) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001165 prot |= PROT_WRITE;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001166 }
Andreas Gampedaab38c2014-09-12 18:38:24 -07001167 if ((program_header->p_flags & PF_R) != 0) {
Brian Carlstrom6a47b9d2013-05-17 10:58:25 -07001168 prot |= PROT_READ;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001169 }
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -07001170 int flags = 0;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001171 if (writable_) {
1172 prot |= PROT_WRITE;
1173 flags |= MAP_SHARED;
1174 } else {
1175 flags |= MAP_PRIVATE;
1176 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001177 if (program_header->p_filesz > program_header->p_memsz) {
1178 *error_msg = StringPrintf("Invalid p_filesz > p_memsz (%" PRIu64 " > %" PRIu64 "): %s",
1179 static_cast<uint64_t>(program_header->p_filesz),
1180 static_cast<uint64_t>(program_header->p_memsz),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001181 file_->GetPath().c_str());
Brian Carlstrom3a223612013-10-10 17:18:24 -07001182 return false;
1183 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001184 if (program_header->p_filesz < program_header->p_memsz &&
1185 !IsAligned<kPageSize>(program_header->p_filesz)) {
1186 *error_msg = StringPrintf("Unsupported unaligned p_filesz < p_memsz (%" PRIu64
1187 " < %" PRIu64 "): %s",
1188 static_cast<uint64_t>(program_header->p_filesz),
1189 static_cast<uint64_t>(program_header->p_memsz),
1190 file_->GetPath().c_str());
Brian Carlstromc1409452014-02-26 14:06:23 -08001191 return false;
1192 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001193 if (file_length < (program_header->p_offset + program_header->p_filesz)) {
1194 *error_msg = StringPrintf("File size of %zd bytes not large enough to contain ELF segment "
1195 "%d of %" PRIu64 " bytes: '%s'", file_length, i,
1196 static_cast<uint64_t>(program_header->p_offset + program_header->p_filesz),
1197 file_->GetPath().c_str());
Brian Carlstromc1409452014-02-26 14:06:23 -08001198 return false;
1199 }
Vladimir Marko5c42c292015-02-25 12:02:49 +00001200 if (program_header->p_filesz != 0u) {
1201 std::unique_ptr<MemMap> segment(
1202 MemMap::MapFileAtAddress(p_vaddr,
1203 program_header->p_filesz,
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001204 prot,
1205 flags,
1206 file_->Fd(),
Vladimir Marko5c42c292015-02-25 12:02:49 +00001207 program_header->p_offset,
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001208 /*low4_gb*/false,
1209 /*reuse*/true, // implies MAP_FIXED
Vladimir Marko5c42c292015-02-25 12:02:49 +00001210 file_->GetPath().c_str(),
1211 error_msg));
1212 if (segment.get() == nullptr) {
1213 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s: %s",
1214 i, file_->GetPath().c_str(), error_msg->c_str());
1215 return false;
1216 }
1217 if (segment->Begin() != p_vaddr) {
1218 *error_msg = StringPrintf("Failed to map ELF file segment %d from %s at expected address %p, "
1219 "instead mapped to %p",
1220 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
1221 return false;
1222 }
1223 segments_.push_back(segment.release());
1224 }
1225 if (program_header->p_filesz < program_header->p_memsz) {
1226 std::string name = StringPrintf("Zero-initialized segment %" PRIu64 " of ELF file %s",
1227 static_cast<uint64_t>(i), file_->GetPath().c_str());
1228 std::unique_ptr<MemMap> segment(
1229 MemMap::MapAnonymous(name.c_str(),
1230 p_vaddr + program_header->p_filesz,
1231 program_header->p_memsz - program_header->p_filesz,
1232 prot, false, true /* reuse */, error_msg));
1233 if (segment == nullptr) {
1234 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s: %s",
1235 i, file_->GetPath().c_str(), error_msg->c_str());
1236 return false;
1237 }
1238 if (segment->Begin() != p_vaddr) {
1239 *error_msg = StringPrintf("Failed to map zero-initialized ELF file segment %d from %s "
1240 "at expected address %p, instead mapped to %p",
1241 i, file_->GetPath().c_str(), p_vaddr, segment->Begin());
1242 return false;
1243 }
1244 segments_.push_back(segment.release());
1245 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001246 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001247
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001248 // Now that we are done loading, .dynamic should be in memory to find .dynstr, .dynsym, .hash
Ian Rogers13735952014-10-08 12:43:28 -07001249 uint8_t* dsptr = base_address_ + GetDynamicProgramHeader().p_vaddr;
Andreas Gampedaab38c2014-09-12 18:38:24 -07001250 if ((dsptr < Begin() || dsptr >= End()) && !ValidPointer(dsptr)) {
1251 *error_msg = StringPrintf("dynamic section address invalid in ELF file %s",
1252 file_->GetPath().c_str());
1253 return false;
1254 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001255 dynamic_section_start_ = reinterpret_cast<Elf_Dyn*>(dsptr);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001256
Tong Shen62d1ca32014-09-03 17:24:56 -07001257 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1258 Elf_Dyn& elf_dyn = GetDynamic(i);
Ian Rogers13735952014-10-08 12:43:28 -07001259 uint8_t* d_ptr = base_address_ + elf_dyn.d_un.d_ptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001260 switch (elf_dyn.d_tag) {
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001261 case DT_HASH: {
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 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001267 hash_section_start_ = reinterpret_cast<Elf_Word*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001268 break;
1269 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001270 case DT_STRTAB: {
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 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001276 dynstr_section_start_ = reinterpret_cast<char*>(d_ptr);
1277 break;
1278 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001279 case DT_SYMTAB: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001280 if (!ValidPointer(d_ptr)) {
1281 *error_msg = StringPrintf("DT_HASH value %p does not refer to a loaded ELF segment of %s",
1282 d_ptr, file_->GetPath().c_str());
1283 return false;
1284 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001285 dynsym_section_start_ = reinterpret_cast<Elf_Sym*>(d_ptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001286 break;
1287 }
Nicolas Geoffray50cfe742014-02-19 13:27:42 +00001288 case DT_NULL: {
Brian Carlstromc1409452014-02-26 14:06:23 -08001289 if (GetDynamicNum() != i+1) {
1290 *error_msg = StringPrintf("DT_NULL found after %d .dynamic entries, "
1291 "expected %d as implied by size of PT_DYNAMIC segment in %s",
1292 i + 1, GetDynamicNum(), file_->GetPath().c_str());
1293 return false;
1294 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001295 break;
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001296 }
1297 }
1298 }
1299
Andreas Gampedaab38c2014-09-12 18:38:24 -07001300 // Check for the existence of some sections.
1301 if (!CheckSectionsExist(error_msg)) {
1302 return false;
1303 }
1304
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001305 return true;
1306}
1307
David Srbecky533c2072015-04-22 12:20:22 +01001308template <typename ElfTypes>
1309bool ElfFileImpl<ElfTypes>::ValidPointer(const uint8_t* start) const {
Brian Carlstromc1409452014-02-26 14:06:23 -08001310 for (size_t i = 0; i < segments_.size(); ++i) {
1311 const MemMap* segment = segments_[i];
1312 if (segment->Begin() <= start && start < segment->End()) {
1313 return true;
1314 }
1315 }
1316 return false;
1317}
1318
Alex Light3470ab42014-06-18 10:35:45 -07001319
David Srbecky533c2072015-04-22 12:20:22 +01001320template <typename ElfTypes>
1321typename ElfTypes::Shdr* ElfFileImpl<ElfTypes>::FindSectionByName(
1322 const std::string& name) const {
Alex Light3470ab42014-06-18 10:35:45 -07001323 CHECK(!program_header_only_);
Tong Shen62d1ca32014-09-03 17:24:56 -07001324 Elf_Shdr* shstrtab_sec = GetSectionNameStringSection();
Andreas Gampedaab38c2014-09-12 18:38:24 -07001325 if (shstrtab_sec == nullptr) {
1326 return nullptr;
1327 }
Alex Light3470ab42014-06-18 10:35:45 -07001328 for (uint32_t i = 0; i < GetSectionHeaderNum(); i++) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001329 Elf_Shdr* shdr = GetSectionHeader(i);
Andreas Gampedaab38c2014-09-12 18:38:24 -07001330 if (shdr == nullptr) {
1331 return nullptr;
1332 }
1333 const char* sec_name = GetString(*shstrtab_sec, shdr->sh_name);
Alex Light3470ab42014-06-18 10:35:45 -07001334 if (sec_name == nullptr) {
1335 continue;
1336 }
1337 if (name == sec_name) {
Andreas Gampedaab38c2014-09-12 18:38:24 -07001338 return shdr;
Alex Light3470ab42014-06-18 10:35:45 -07001339 }
1340 }
1341 return nullptr;
Mark Mendellae9fd932014-02-10 16:14:35 -08001342}
1343
David Srbecky533c2072015-04-22 12:20:22 +01001344template <typename ElfTypes>
David Srbeckyf8980872015-05-22 17:04:47 +01001345bool ElfFileImpl<ElfTypes>::FixupDebugSections(Elf_Addr base_address_delta) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001346 if (base_address_delta == 0) {
1347 return true;
1348 }
David Srbeckyf8980872015-05-22 17:04:47 +01001349 return ApplyOatPatchesTo(".debug_frame", base_address_delta) &&
1350 ApplyOatPatchesTo(".debug_info", base_address_delta) &&
1351 ApplyOatPatchesTo(".debug_line", base_address_delta);
David Srbecky2f6cdb02015-04-11 00:17:53 +01001352}
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001353
David Srbecky533c2072015-04-22 12:20:22 +01001354template <typename ElfTypes>
1355bool ElfFileImpl<ElfTypes>::ApplyOatPatchesTo(
David Srbeckyf8980872015-05-22 17:04:47 +01001356 const char* target_section_name, Elf_Addr delta) {
1357 auto target_section = FindSectionByName(target_section_name);
1358 if (target_section == nullptr) {
1359 return true;
1360 }
1361 std::string patches_name = target_section_name + std::string(".oat_patches");
1362 auto patches_section = FindSectionByName(patches_name.c_str());
David Srbecky2f6cdb02015-04-11 00:17:53 +01001363 if (patches_section == nullptr) {
David Srbeckyf8980872015-05-22 17:04:47 +01001364 LOG(ERROR) << patches_name << " section not found.";
Alex Light3470ab42014-06-18 10:35:45 -07001365 return false;
1366 }
David Srbecky2f6cdb02015-04-11 00:17:53 +01001367 if (patches_section->sh_type != SHT_OAT_PATCH) {
David Srbeckyf8980872015-05-22 17:04:47 +01001368 LOG(ERROR) << "Unexpected type of " << patches_name;
Alex Light3470ab42014-06-18 10:35:45 -07001369 return false;
1370 }
David Srbeckyf8980872015-05-22 17:04:47 +01001371 ApplyOatPatches(
David Srbecky2f6cdb02015-04-11 00:17:53 +01001372 Begin() + patches_section->sh_offset,
1373 Begin() + patches_section->sh_offset + patches_section->sh_size,
David Srbeckyf8980872015-05-22 17:04:47 +01001374 delta,
David Srbecky2f6cdb02015-04-11 00:17:53 +01001375 Begin() + target_section->sh_offset,
David Srbeckyf8980872015-05-22 17:04:47 +01001376 Begin() + target_section->sh_offset + target_section->sh_size);
David Srbecky2f6cdb02015-04-11 00:17:53 +01001377 return true;
1378}
1379
David Srbeckyf8980872015-05-22 17:04:47 +01001380// Apply LEB128 encoded patches to given section.
David Srbecky533c2072015-04-22 12:20:22 +01001381template <typename ElfTypes>
David Srbeckyf8980872015-05-22 17:04:47 +01001382void ElfFileImpl<ElfTypes>::ApplyOatPatches(
1383 const uint8_t* patches, const uint8_t* patches_end, Elf_Addr delta,
David Srbecky533c2072015-04-22 12:20:22 +01001384 uint8_t* to_patch, const uint8_t* to_patch_end) {
David Srbeckyf8980872015-05-22 17:04:47 +01001385 typedef __attribute__((__aligned__(1))) Elf_Addr UnalignedAddress;
1386 while (patches < patches_end) {
1387 to_patch += DecodeUnsignedLeb128(&patches);
1388 DCHECK_LE(patches, patches_end) << "Unexpected end of patch list.";
1389 DCHECK_LT(to_patch, to_patch_end) << "Patch past the end of section.";
1390 *reinterpret_cast<UnalignedAddress*>(to_patch) += delta;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001391 }
Alex Light3470ab42014-06-18 10:35:45 -07001392}
Mark Mendellae9fd932014-02-10 16:14:35 -08001393
David Srbecky533c2072015-04-22 12:20:22 +01001394template <typename ElfTypes>
David Srbecky533c2072015-04-22 12:20:22 +01001395bool ElfFileImpl<ElfTypes>::Strip(std::string* error_msg) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001396 // ELF files produced by MCLinker look roughly like this
1397 //
1398 // +------------+
1399 // | Elf_Ehdr | contains number of Elf_Shdr and offset to first
1400 // +------------+
1401 // | Elf_Phdr | program headers
1402 // | Elf_Phdr |
1403 // | ... |
1404 // | Elf_Phdr |
1405 // +------------+
1406 // | section | mixture of needed and unneeded sections
1407 // +------------+
1408 // | section |
1409 // +------------+
1410 // | ... |
1411 // +------------+
1412 // | section |
1413 // +------------+
1414 // | Elf_Shdr | section headers
1415 // | Elf_Shdr |
1416 // | ... | contains offset to section start
1417 // | Elf_Shdr |
1418 // +------------+
1419 //
1420 // To strip:
1421 // - leave the Elf_Ehdr and Elf_Phdr values in place.
1422 // - walk the sections making a new set of Elf_Shdr section headers for what we want to keep
1423 // - move the sections are keeping up to fill in gaps of sections we want to strip
1424 // - write new Elf_Shdr section headers to end of file, updating Elf_Ehdr
1425 // - truncate rest of file
1426 //
1427
1428 std::vector<Elf_Shdr> section_headers;
1429 std::vector<Elf_Word> section_headers_original_indexes;
1430 section_headers.reserve(GetSectionHeaderNum());
1431
1432
1433 Elf_Shdr* string_section = GetSectionNameStringSection();
1434 CHECK(string_section != nullptr);
1435 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1436 Elf_Shdr* sh = GetSectionHeader(i);
1437 CHECK(sh != nullptr);
1438 const char* name = GetString(*string_section, sh->sh_name);
1439 if (name == nullptr) {
1440 CHECK_EQ(0U, i);
1441 section_headers.push_back(*sh);
1442 section_headers_original_indexes.push_back(0);
1443 continue;
1444 }
1445 if (StartsWith(name, ".debug")
1446 || (strcmp(name, ".strtab") == 0)
1447 || (strcmp(name, ".symtab") == 0)) {
1448 continue;
1449 }
1450 section_headers.push_back(*sh);
1451 section_headers_original_indexes.push_back(i);
1452 }
1453 CHECK_NE(0U, section_headers.size());
1454 CHECK_EQ(section_headers.size(), section_headers_original_indexes.size());
1455
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001456 // section 0 is the null section, sections start at offset of first section
Tong Shen62d1ca32014-09-03 17:24:56 -07001457 CHECK(GetSectionHeader(1) != nullptr);
1458 Elf_Off offset = GetSectionHeader(1)->sh_offset;
1459 for (size_t i = 1; i < section_headers.size(); i++) {
1460 Elf_Shdr& new_sh = section_headers[i];
1461 Elf_Shdr* old_sh = GetSectionHeader(section_headers_original_indexes[i]);
1462 CHECK(old_sh != nullptr);
1463 CHECK_EQ(new_sh.sh_name, old_sh->sh_name);
1464 if (old_sh->sh_addralign > 1) {
1465 offset = RoundUp(offset, old_sh->sh_addralign);
1466 }
1467 if (old_sh->sh_offset == offset) {
1468 // already in place
1469 offset += old_sh->sh_size;
1470 continue;
1471 }
1472 // shift section earlier
1473 memmove(Begin() + offset,
1474 Begin() + old_sh->sh_offset,
1475 old_sh->sh_size);
1476 new_sh.sh_offset = offset;
1477 offset += old_sh->sh_size;
1478 }
1479
1480 Elf_Off shoff = offset;
1481 size_t section_headers_size_in_bytes = section_headers.size() * sizeof(Elf_Shdr);
1482 memcpy(Begin() + offset, &section_headers[0], section_headers_size_in_bytes);
1483 offset += section_headers_size_in_bytes;
1484
1485 GetHeader().e_shnum = section_headers.size();
1486 GetHeader().e_shoff = shoff;
1487 int result = ftruncate(file_->Fd(), offset);
1488 if (result != 0) {
1489 *error_msg = StringPrintf("Failed to truncate while stripping ELF file: '%s': %s",
1490 file_->GetPath().c_str(), strerror(errno));
1491 return false;
1492 }
1493 return true;
1494}
1495
1496static const bool DEBUG_FIXUP = false;
1497
David Srbecky533c2072015-04-22 12:20:22 +01001498template <typename ElfTypes>
1499bool ElfFileImpl<ElfTypes>::Fixup(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001500 if (!FixupDynamic(base_address)) {
1501 LOG(WARNING) << "Failed to fixup .dynamic in " << file_->GetPath();
1502 return false;
1503 }
1504 if (!FixupSectionHeaders(base_address)) {
1505 LOG(WARNING) << "Failed to fixup section headers in " << file_->GetPath();
1506 return false;
1507 }
1508 if (!FixupProgramHeaders(base_address)) {
1509 LOG(WARNING) << "Failed to fixup program headers in " << file_->GetPath();
1510 return false;
1511 }
1512 if (!FixupSymbols(base_address, true)) {
1513 LOG(WARNING) << "Failed to fixup .dynsym in " << file_->GetPath();
1514 return false;
1515 }
1516 if (!FixupSymbols(base_address, false)) {
1517 LOG(WARNING) << "Failed to fixup .symtab in " << file_->GetPath();
1518 return false;
1519 }
1520 if (!FixupRelocations(base_address)) {
1521 LOG(WARNING) << "Failed to fixup .rel.dyn in " << file_->GetPath();
1522 return false;
1523 }
Andreas Gampe3c54b002015-04-07 16:09:30 -07001524 static_assert(sizeof(Elf_Off) >= sizeof(base_address), "Potentially losing precision.");
1525 if (!FixupDebugSections(static_cast<Elf_Off>(base_address))) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001526 LOG(WARNING) << "Failed to fixup debug sections in " << file_->GetPath();
1527 return false;
1528 }
1529 return true;
1530}
1531
David Srbecky533c2072015-04-22 12:20:22 +01001532template <typename ElfTypes>
1533bool ElfFileImpl<ElfTypes>::FixupDynamic(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001534 for (Elf_Word i = 0; i < GetDynamicNum(); i++) {
1535 Elf_Dyn& elf_dyn = GetDynamic(i);
1536 Elf_Word d_tag = elf_dyn.d_tag;
1537 if (IsDynamicSectionPointer(d_tag, GetHeader().e_machine)) {
1538 Elf_Addr d_ptr = elf_dyn.d_un.d_ptr;
1539 if (DEBUG_FIXUP) {
1540 LOG(INFO) << StringPrintf("In %s moving Elf_Dyn[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1541 GetFile().GetPath().c_str(), i,
1542 static_cast<uint64_t>(d_ptr),
1543 static_cast<uint64_t>(d_ptr + base_address));
1544 }
1545 d_ptr += base_address;
1546 elf_dyn.d_un.d_ptr = d_ptr;
1547 }
1548 }
1549 return true;
1550}
1551
David Srbecky533c2072015-04-22 12:20:22 +01001552template <typename ElfTypes>
1553bool ElfFileImpl<ElfTypes>::FixupSectionHeaders(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001554 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1555 Elf_Shdr* sh = GetSectionHeader(i);
1556 CHECK(sh != nullptr);
1557 // 0 implies that the section will not exist in the memory of the process
1558 if (sh->sh_addr == 0) {
1559 continue;
1560 }
1561 if (DEBUG_FIXUP) {
1562 LOG(INFO) << StringPrintf("In %s moving Elf_Shdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1563 GetFile().GetPath().c_str(), i,
1564 static_cast<uint64_t>(sh->sh_addr),
1565 static_cast<uint64_t>(sh->sh_addr + base_address));
1566 }
1567 sh->sh_addr += base_address;
1568 }
1569 return true;
1570}
1571
David Srbecky533c2072015-04-22 12:20:22 +01001572template <typename ElfTypes>
1573bool ElfFileImpl<ElfTypes>::FixupProgramHeaders(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001574 // TODO: ELFObjectFile doesn't have give to Elf_Phdr, so we do that ourselves for now.
1575 for (Elf_Word i = 0; i < GetProgramHeaderNum(); i++) {
1576 Elf_Phdr* ph = GetProgramHeader(i);
1577 CHECK(ph != nullptr);
1578 CHECK_EQ(ph->p_vaddr, ph->p_paddr) << GetFile().GetPath() << " i=" << i;
1579 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1580 << GetFile().GetPath() << " i=" << i;
1581 if (DEBUG_FIXUP) {
1582 LOG(INFO) << StringPrintf("In %s moving Elf_Phdr[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1583 GetFile().GetPath().c_str(), i,
1584 static_cast<uint64_t>(ph->p_vaddr),
1585 static_cast<uint64_t>(ph->p_vaddr + base_address));
1586 }
1587 ph->p_vaddr += base_address;
1588 ph->p_paddr += base_address;
1589 CHECK((ph->p_align == 0) || (0 == ((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1))))
1590 << GetFile().GetPath() << " i=" << i;
1591 }
1592 return true;
1593}
1594
David Srbecky533c2072015-04-22 12:20:22 +01001595template <typename ElfTypes>
1596bool ElfFileImpl<ElfTypes>::FixupSymbols(Elf_Addr base_address, bool dynamic) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001597 Elf_Word section_type = dynamic ? SHT_DYNSYM : SHT_SYMTAB;
1598 // TODO: Unfortunate ELFObjectFile has protected symbol access, so use ElfFile
1599 Elf_Shdr* symbol_section = FindSectionByType(section_type);
1600 if (symbol_section == nullptr) {
1601 // file is missing optional .symtab
1602 CHECK(!dynamic) << GetFile().GetPath();
1603 return true;
1604 }
1605 for (uint32_t i = 0; i < GetSymbolNum(*symbol_section); i++) {
1606 Elf_Sym* symbol = GetSymbol(section_type, i);
1607 CHECK(symbol != nullptr);
1608 if (symbol->st_value != 0) {
1609 if (DEBUG_FIXUP) {
1610 LOG(INFO) << StringPrintf("In %s moving Elf_Sym[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
1611 GetFile().GetPath().c_str(), i,
1612 static_cast<uint64_t>(symbol->st_value),
1613 static_cast<uint64_t>(symbol->st_value + base_address));
1614 }
1615 symbol->st_value += base_address;
1616 }
1617 }
1618 return true;
1619}
1620
David Srbecky533c2072015-04-22 12:20:22 +01001621template <typename ElfTypes>
1622bool ElfFileImpl<ElfTypes>::FixupRelocations(Elf_Addr base_address) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001623 for (Elf_Word i = 0; i < GetSectionHeaderNum(); i++) {
1624 Elf_Shdr* sh = GetSectionHeader(i);
1625 CHECK(sh != nullptr);
1626 if (sh->sh_type == SHT_REL) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001627 for (uint32_t j = 0; j < GetRelNum(*sh); j++) {
1628 Elf_Rel& rel = GetRel(*sh, j);
Tong Shen62d1ca32014-09-03 17:24:56 -07001629 if (DEBUG_FIXUP) {
1630 LOG(INFO) << StringPrintf("In %s moving Elf_Rel[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001631 GetFile().GetPath().c_str(), j,
Tong Shen62d1ca32014-09-03 17:24:56 -07001632 static_cast<uint64_t>(rel.r_offset),
1633 static_cast<uint64_t>(rel.r_offset + base_address));
1634 }
1635 rel.r_offset += base_address;
1636 }
1637 } else if (sh->sh_type == SHT_RELA) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001638 for (uint32_t j = 0; j < GetRelaNum(*sh); j++) {
1639 Elf_Rela& rela = GetRela(*sh, j);
Tong Shen62d1ca32014-09-03 17:24:56 -07001640 if (DEBUG_FIXUP) {
1641 LOG(INFO) << StringPrintf("In %s moving Elf_Rela[%d] from 0x%" PRIx64 " to 0x%" PRIx64,
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001642 GetFile().GetPath().c_str(), j,
Tong Shen62d1ca32014-09-03 17:24:56 -07001643 static_cast<uint64_t>(rela.r_offset),
1644 static_cast<uint64_t>(rela.r_offset + base_address));
1645 }
1646 rela.r_offset += base_address;
1647 }
1648 }
1649 }
1650 return true;
1651}
1652
1653// Explicit instantiations
David Srbecky533c2072015-04-22 12:20:22 +01001654template class ElfFileImpl<ElfTypes32>;
1655template class ElfFileImpl<ElfTypes64>;
Tong Shen62d1ca32014-09-03 17:24:56 -07001656
Ian Rogersd4c4d952014-10-16 20:31:53 -07001657ElfFile::ElfFile(ElfFileImpl32* elf32) : elf32_(elf32), elf64_(nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001658}
1659
Ian Rogersd4c4d952014-10-16 20:31:53 -07001660ElfFile::ElfFile(ElfFileImpl64* elf64) : elf32_(nullptr), elf64_(elf64) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001661}
1662
1663ElfFile::~ElfFile() {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001664 // Should never have 32 and 64-bit impls.
1665 CHECK_NE(elf32_.get() == nullptr, elf64_.get() == nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -07001666}
1667
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001668ElfFile* ElfFile::Open(File* file,
1669 bool writable,
1670 bool program_header_only,
1671 bool low_4gb,
1672 std::string* error_msg,
Igor Murashkin46774762014-10-22 11:37:02 -07001673 uint8_t* requested_base) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001674 if (file->GetLength() < EI_NIDENT) {
1675 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1676 file->GetPath().c_str());
1677 return nullptr;
1678 }
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001679 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT,
1680 PROT_READ,
1681 MAP_PRIVATE,
1682 file->Fd(),
1683 0,
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001684 low_4gb,
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001685 file->GetPath().c_str(),
1686 error_msg));
Tong Shen62d1ca32014-09-03 17:24:56 -07001687 if (map == nullptr && map->Size() != EI_NIDENT) {
1688 return nullptr;
1689 }
Ian Rogers13735952014-10-08 12:43:28 -07001690 uint8_t* header = map->Begin();
Tong Shen62d1ca32014-09-03 17:24:56 -07001691 if (header[EI_CLASS] == ELFCLASS64) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001692 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file,
1693 writable,
1694 program_header_only,
1695 low_4gb,
1696 error_msg,
1697 requested_base);
Tong Shen62d1ca32014-09-03 17:24:56 -07001698 if (elf_file_impl == nullptr)
1699 return nullptr;
1700 return new ElfFile(elf_file_impl);
1701 } else if (header[EI_CLASS] == ELFCLASS32) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001702 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file,
1703 writable,
1704 program_header_only,
1705 low_4gb,
1706 error_msg,
1707 requested_base);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001708 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001709 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001710 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001711 return new ElfFile(elf_file_impl);
1712 } else {
1713 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1714 ELFCLASS32, ELFCLASS64,
1715 file->GetPath().c_str(),
1716 header[EI_CLASS]);
1717 return nullptr;
1718 }
1719}
1720
1721ElfFile* ElfFile::Open(File* file, int mmap_prot, int mmap_flags, std::string* error_msg) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001722 // low_4gb support not required for this path.
1723 constexpr bool low_4gb = false;
Tong Shen62d1ca32014-09-03 17:24:56 -07001724 if (file->GetLength() < EI_NIDENT) {
1725 *error_msg = StringPrintf("File %s is too short to be a valid ELF file",
1726 file->GetPath().c_str());
1727 return nullptr;
1728 }
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001729 std::unique_ptr<MemMap> map(MemMap::MapFile(EI_NIDENT,
1730 PROT_READ,
1731 MAP_PRIVATE,
1732 file->Fd(),
1733 0,
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001734 low_4gb,
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001735 file->GetPath().c_str(),
1736 error_msg));
Tong Shen62d1ca32014-09-03 17:24:56 -07001737 if (map == nullptr && map->Size() != EI_NIDENT) {
1738 return nullptr;
1739 }
Ian Rogers13735952014-10-08 12:43:28 -07001740 uint8_t* header = map->Begin();
Tong Shen62d1ca32014-09-03 17:24:56 -07001741 if (header[EI_CLASS] == ELFCLASS64) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001742 ElfFileImpl64* elf_file_impl = ElfFileImpl64::Open(file,
1743 mmap_prot,
1744 mmap_flags,
1745 low_4gb,
1746 error_msg);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001747 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001748 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001749 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001750 return new ElfFile(elf_file_impl);
1751 } else if (header[EI_CLASS] == ELFCLASS32) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001752 ElfFileImpl32* elf_file_impl = ElfFileImpl32::Open(file,
1753 mmap_prot,
1754 mmap_flags,
1755 low_4gb,
1756 error_msg);
Ian Rogersd4c4d952014-10-16 20:31:53 -07001757 if (elf_file_impl == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001758 return nullptr;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001759 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001760 return new ElfFile(elf_file_impl);
1761 } else {
1762 *error_msg = StringPrintf("Failed to find expected EI_CLASS value %d or %d in %s, found %d",
1763 ELFCLASS32, ELFCLASS64,
1764 file->GetPath().c_str(),
1765 header[EI_CLASS]);
1766 return nullptr;
1767 }
1768}
1769
1770#define DELEGATE_TO_IMPL(func, ...) \
Ian Rogersd4c4d952014-10-16 20:31:53 -07001771 if (elf64_.get() != nullptr) { \
1772 return elf64_->func(__VA_ARGS__); \
Tong Shen62d1ca32014-09-03 17:24:56 -07001773 } else { \
Ian Rogersd4c4d952014-10-16 20:31:53 -07001774 DCHECK(elf32_.get() != nullptr); \
1775 return elf32_->func(__VA_ARGS__); \
Tong Shen62d1ca32014-09-03 17:24:56 -07001776 }
1777
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001778bool ElfFile::Load(bool executable, bool low_4gb, std::string* error_msg) {
1779 DELEGATE_TO_IMPL(Load, executable, low_4gb, error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001780}
1781
Ian Rogers13735952014-10-08 12:43:28 -07001782const uint8_t* ElfFile::FindDynamicSymbolAddress(const std::string& symbol_name) const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001783 DELEGATE_TO_IMPL(FindDynamicSymbolAddress, symbol_name);
1784}
1785
1786size_t ElfFile::Size() const {
1787 DELEGATE_TO_IMPL(Size);
1788}
1789
Ian Rogers13735952014-10-08 12:43:28 -07001790uint8_t* ElfFile::Begin() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001791 DELEGATE_TO_IMPL(Begin);
1792}
1793
Ian Rogers13735952014-10-08 12:43:28 -07001794uint8_t* ElfFile::End() const {
Tong Shen62d1ca32014-09-03 17:24:56 -07001795 DELEGATE_TO_IMPL(End);
1796}
1797
1798const File& ElfFile::GetFile() const {
1799 DELEGATE_TO_IMPL(GetFile);
1800}
1801
Alex Light0eb76d22015-08-11 18:03:47 -07001802bool ElfFile::GetSectionOffsetAndSize(const char* section_name, uint64_t* offset,
1803 uint64_t* size) const {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001804 if (elf32_.get() == nullptr) {
1805 CHECK(elf64_.get() != nullptr);
Tong Shen62d1ca32014-09-03 17:24:56 -07001806
Ian Rogersd4c4d952014-10-16 20:31:53 -07001807 Elf64_Shdr *shdr = elf64_->FindSectionByName(section_name);
1808 if (shdr == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001809 return false;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001810 }
1811 if (offset != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001812 *offset = shdr->sh_offset;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001813 }
1814 if (size != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001815 *size = shdr->sh_size;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001816 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001817 return true;
1818 } else {
Ian Rogersd4c4d952014-10-16 20:31:53 -07001819 Elf32_Shdr *shdr = elf32_->FindSectionByName(section_name);
1820 if (shdr == nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001821 return false;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001822 }
1823 if (offset != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001824 *offset = shdr->sh_offset;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001825 }
1826 if (size != nullptr) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001827 *size = shdr->sh_size;
Ian Rogersd4c4d952014-10-16 20:31:53 -07001828 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001829 return true;
1830 }
1831}
1832
Jeff Hao24ec0282016-03-17 21:32:45 -07001833bool ElfFile::HasSection(const std::string& name) const {
1834 if (elf64_.get() != nullptr) {
1835 return elf64_->FindSectionByName(name) != nullptr;
1836 } else {
1837 return elf32_->FindSectionByName(name) != nullptr;
1838 }
1839}
1840
Tong Shen62d1ca32014-09-03 17:24:56 -07001841uint64_t ElfFile::FindSymbolAddress(unsigned section_type,
1842 const std::string& symbol_name,
1843 bool build_map) {
1844 DELEGATE_TO_IMPL(FindSymbolAddress, section_type, symbol_name, build_map);
1845}
1846
Vladimir Marko3fc99032015-05-13 19:06:30 +01001847bool ElfFile::GetLoadedSize(size_t* size, std::string* error_msg) const {
1848 DELEGATE_TO_IMPL(GetLoadedSize, size, error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001849}
1850
1851bool ElfFile::Strip(File* file, std::string* error_msg) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001852 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file, true, false, /*low_4gb*/false, error_msg));
Tong Shen62d1ca32014-09-03 17:24:56 -07001853 if (elf_file.get() == nullptr) {
1854 return false;
1855 }
1856
Ian Rogersd4c4d952014-10-16 20:31:53 -07001857 if (elf_file->elf64_.get() != nullptr)
1858 return elf_file->elf64_->Strip(error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001859 else
Ian Rogersd4c4d952014-10-16 20:31:53 -07001860 return elf_file->elf32_->Strip(error_msg);
Tong Shen62d1ca32014-09-03 17:24:56 -07001861}
1862
Andreas Gampe3c54b002015-04-07 16:09:30 -07001863bool ElfFile::Fixup(uint64_t base_address) {
1864 if (elf64_.get() != nullptr) {
1865 return elf64_->Fixup(static_cast<Elf64_Addr>(base_address));
1866 } else {
1867 DCHECK(elf32_.get() != nullptr);
1868 CHECK(IsUint<32>(base_address)) << std::hex << base_address;
1869 return elf32_->Fixup(static_cast<Elf32_Addr>(base_address));
1870 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001871 DELEGATE_TO_IMPL(Fixup, base_address);
1872}
1873
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001874} // namespace art