blob: 73240bed0361c872148dc74f673ac14ce54317e7 [file] [log] [blame]
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001/*
David Srbeckybc90fd02015-04-22 19:40:27 +01002 * Copyright (C) 2015 The Android Open Source Project
Andreas Gampe54fc26c2014-09-04 21:47:42 -07003 *
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#ifndef ART_COMPILER_ELF_BUILDER_H_
18#define ART_COMPILER_ELF_BUILDER_H_
19
David Srbeckybc90fd02015-04-22 19:40:27 +010020#include <vector>
21
Ian Rogersd582fa42014-11-05 23:46:43 -080022#include "arch/instruction_set.h"
David Srbecky5d811202016-03-08 13:21:22 +000023#include "arch/mips/instruction_set_features_mips.h"
David Brazdild9c90372016-09-14 16:53:55 +010024#include "base/array_ref.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010025#include "base/bit_utils.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000026#include "base/casts.h"
David Srbeckybc90fd02015-04-22 19:40:27 +010027#include "base/unix_file/fd_file.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070028#include "elf_utils.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000029#include "leb128.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000030#include "linker/error_delaying_output_stream.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070031
32namespace art {
33
David Srbeckybc90fd02015-04-22 19:40:27 +010034// Writes ELF file.
David Srbecky6d8c8f02015-10-26 10:57:09 +000035//
36// The basic layout of the elf file:
37// Elf_Ehdr - The ELF header.
38// Elf_Phdr[] - Program headers for the linker.
39// .rodata - DEX files and oat metadata.
40// .text - Compiled code.
41// .bss - Zero-initialized writeable section.
Douglas Leung316a2182015-09-17 15:26:25 -070042// .MIPS.abiflags - MIPS specific section.
David Srbecky6d8c8f02015-10-26 10:57:09 +000043// .dynstr - Names for .dynsym.
44// .dynsym - A few oat-specific dynamic symbols.
45// .hash - Hash-table for .dynsym.
46// .dynamic - Tags which let the linker locate .dynsym.
47// .strtab - Names for .symtab.
48// .symtab - Debug symbols.
49// .eh_frame - Unwind information (CFI).
50// .eh_frame_hdr - Index of .eh_frame.
51// .debug_frame - Unwind information (CFI).
52// .debug_frame.oat_patches - Addresses for relocation.
53// .debug_info - Debug information.
54// .debug_info.oat_patches - Addresses for relocation.
55// .debug_abbrev - Decoding information for .debug_info.
56// .debug_str - Strings for .debug_info.
57// .debug_line - Line number tables.
58// .debug_line.oat_patches - Addresses for relocation.
59// .text.oat_patches - Addresses for relocation.
60// .shstrtab - Names of ELF sections.
61// Elf_Shdr[] - Section headers.
62//
63// Some section are optional (the debug sections in particular).
64//
65// We try write the section data directly into the file without much
66// in-memory buffering. This means we generally write sections based on the
67// dependency order (e.g. .dynamic points to .dynsym which points to .text).
68//
69// In the cases where we need to buffer, we write the larger section first
70// and buffer the smaller one (e.g. .strtab is bigger than .symtab).
71//
72// The debug sections are written last for easier stripping.
73//
David Srbecky533c2072015-04-22 12:20:22 +010074template <typename ElfTypes>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070075class ElfBuilder FINAL {
76 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000077 static constexpr size_t kMaxProgramHeaders = 16;
David Srbecky533c2072015-04-22 12:20:22 +010078 using Elf_Addr = typename ElfTypes::Addr;
David Srbeckybc90fd02015-04-22 19:40:27 +010079 using Elf_Off = typename ElfTypes::Off;
David Srbecky533c2072015-04-22 12:20:22 +010080 using Elf_Word = typename ElfTypes::Word;
81 using Elf_Sword = typename ElfTypes::Sword;
82 using Elf_Ehdr = typename ElfTypes::Ehdr;
83 using Elf_Shdr = typename ElfTypes::Shdr;
84 using Elf_Sym = typename ElfTypes::Sym;
85 using Elf_Phdr = typename ElfTypes::Phdr;
86 using Elf_Dyn = typename ElfTypes::Dyn;
87
David Srbeckybc90fd02015-04-22 19:40:27 +010088 // Base class of all sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +000089 class Section : public OutputStream {
David Srbecky0c5bbc12015-04-28 17:54:52 +010090 public:
Vladimir Marko944da602016-02-19 12:27:55 +000091 Section(ElfBuilder<ElfTypes>* owner,
92 const std::string& name,
93 Elf_Word type,
94 Elf_Word flags,
95 const Section* link,
96 Elf_Word info,
97 Elf_Word align,
98 Elf_Word entsize)
99 : OutputStream(name),
100 owner_(owner),
101 header_(),
102 section_index_(0),
103 name_(name),
104 link_(link),
105 started_(false),
106 finished_(false),
107 phdr_flags_(PF_R),
108 phdr_type_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000109 DCHECK_GE(align, 1u);
David Srbecky491a7fe2015-05-28 00:59:08 +0100110 header_.sh_type = type;
111 header_.sh_flags = flags;
112 header_.sh_info = info;
113 header_.sh_addralign = align;
114 header_.sh_entsize = entsize;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100115 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100116
David Srbecky6d8c8f02015-10-26 10:57:09 +0000117 // Start writing of this section.
118 void Start() {
119 CHECK(!started_);
120 CHECK(!finished_);
121 started_ = true;
122 auto& sections = owner_->sections_;
123 // Check that the previous section is complete.
124 CHECK(sections.empty() || sections.back()->finished_);
125 // The first ELF section index is 1. Index 0 is reserved for NULL.
126 section_index_ = sections.size() + 1;
David Srbecky579942f2016-01-28 20:01:28 +0000127 // Page-align if we switch between allocated and non-allocated sections,
128 // or if we change the type of allocation (e.g. executable vs non-executable).
129 if (!sections.empty()) {
130 if (header_.sh_flags != sections.back()->header_.sh_flags) {
131 header_.sh_addralign = kPageSize;
132 }
133 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000134 // Align file position.
135 if (header_.sh_type != SHT_NOBITS) {
David Srbecky579942f2016-01-28 20:01:28 +0000136 header_.sh_offset = owner_->AlignFileOffset(header_.sh_addralign);
137 } else {
138 header_.sh_offset = 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000139 }
140 // Align virtual memory address.
141 if ((header_.sh_flags & SHF_ALLOC) != 0) {
David Srbecky579942f2016-01-28 20:01:28 +0000142 header_.sh_addr = owner_->AlignVirtualAddress(header_.sh_addralign);
143 } else {
144 header_.sh_addr = 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000145 }
David Srbecky579942f2016-01-28 20:01:28 +0000146 // Push this section on the list of written sections.
147 sections.push_back(this);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100148 }
149
David Srbecky6d8c8f02015-10-26 10:57:09 +0000150 // Finish writing of this section.
151 void End() {
152 CHECK(started_);
153 CHECK(!finished_);
154 finished_ = true;
155 if (header_.sh_type == SHT_NOBITS) {
156 CHECK_GT(header_.sh_size, 0u);
157 } else {
158 // Use the current file position to determine section size.
Vladimir Marko131980f2015-12-03 18:29:23 +0000159 off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000160 CHECK_GE(file_offset, (off_t)header_.sh_offset);
161 header_.sh_size = file_offset - header_.sh_offset;
162 }
163 if ((header_.sh_flags & SHF_ALLOC) != 0) {
164 owner_->virtual_address_ += header_.sh_size;
165 }
166 }
167
168 // Get the location of this section in virtual memory.
169 Elf_Addr GetAddress() const {
170 CHECK(started_);
171 return header_.sh_addr;
172 }
173
174 // Returns the size of the content of this section.
175 Elf_Word GetSize() const {
David Srbeckyb851b492015-11-11 20:19:38 +0000176 if (finished_) {
177 return header_.sh_size;
178 } else {
179 CHECK(started_);
180 CHECK_NE(header_.sh_type, (Elf_Word)SHT_NOBITS);
Vladimir Marko131980f2015-12-03 18:29:23 +0000181 return owner_->stream_.Seek(0, kSeekCurrent) - header_.sh_offset;
David Srbeckyb851b492015-11-11 20:19:38 +0000182 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000183 }
184
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000185 // Write this section as "NOBITS" section. (used for the .bss section)
186 // This means that the ELF file does not contain the initial data for this section
187 // and it will be zero-initialized when the ELF file is loaded in the running program.
188 void WriteNoBitsSection(Elf_Word size) {
189 DCHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000190 header_.sh_type = SHT_NOBITS;
David Srbecky579942f2016-01-28 20:01:28 +0000191 Start();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000192 header_.sh_size = size;
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000193 End();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000194 }
195
196 // This function always succeeds to simplify code.
197 // Use builder's Good() to check the actual status.
198 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
199 CHECK(started_);
200 CHECK(!finished_);
Vladimir Marko131980f2015-12-03 18:29:23 +0000201 return owner_->stream_.WriteFully(buffer, byte_count);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000202 }
203
204 // This function always succeeds to simplify code.
205 // Use builder's Good() to check the actual status.
206 off_t Seek(off_t offset, Whence whence) OVERRIDE {
207 // Forward the seek as-is and trust the caller to use it reasonably.
Vladimir Marko131980f2015-12-03 18:29:23 +0000208 return owner_->stream_.Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100209 }
210
Vladimir Marko10c13562015-11-25 14:33:36 +0000211 // This function flushes the output and returns whether it succeeded.
212 // If there was a previous failure, this does nothing and returns false, i.e. failed.
213 bool Flush() OVERRIDE {
Vladimir Marko131980f2015-12-03 18:29:23 +0000214 return owner_->stream_.Flush();
Vladimir Marko10c13562015-11-25 14:33:36 +0000215 }
216
David Srbecky0c5bbc12015-04-28 17:54:52 +0100217 Elf_Word GetSectionIndex() const {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000218 DCHECK(started_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100219 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100220 return section_index_;
221 }
222
David Srbecky0c5bbc12015-04-28 17:54:52 +0100223 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000224 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100225 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100226 Elf_Word section_index_;
227 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100228 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000229 bool started_;
230 bool finished_;
231 Elf_Word phdr_flags_;
232 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100233
David Srbecky6d8c8f02015-10-26 10:57:09 +0000234 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000235
236 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100237 };
238
Vladimir Marko944da602016-02-19 12:27:55 +0000239 class CachedSection : public Section {
240 public:
241 CachedSection(ElfBuilder<ElfTypes>* owner,
242 const std::string& name,
243 Elf_Word type,
244 Elf_Word flags,
245 const Section* link,
246 Elf_Word info,
247 Elf_Word align,
248 Elf_Word entsize)
249 : Section(owner, name, type, flags, link, info, align, entsize), cache_() { }
250
251 Elf_Word Add(const void* data, size_t length) {
252 Elf_Word offset = cache_.size();
253 const uint8_t* d = reinterpret_cast<const uint8_t*>(data);
254 cache_.insert(cache_.end(), d, d + length);
255 return offset;
256 }
257
258 Elf_Word GetCacheSize() {
259 return cache_.size();
260 }
261
262 void Write() {
263 this->WriteFully(cache_.data(), cache_.size());
264 cache_.clear();
265 cache_.shrink_to_fit();
266 }
267
268 void WriteCachedSection() {
269 this->Start();
270 Write();
271 this->End();
272 }
273
274 private:
275 std::vector<uint8_t> cache_;
276 };
277
278 // Writer of .dynstr section.
279 class CachedStringSection FINAL : public CachedSection {
280 public:
281 CachedStringSection(ElfBuilder<ElfTypes>* owner,
282 const std::string& name,
283 Elf_Word flags,
284 Elf_Word align)
285 : CachedSection(owner,
286 name,
287 SHT_STRTAB,
288 flags,
289 /* link */ nullptr,
290 /* info */ 0,
291 align,
292 /* entsize */ 0) { }
293
294 Elf_Word Add(const std::string& name) {
295 if (CachedSection::GetCacheSize() == 0u) {
296 DCHECK(name.empty());
297 }
298 return CachedSection::Add(name.c_str(), name.length() + 1);
299 }
300 };
301
302 // Writer of .strtab and .shstrtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000303 class StringSection FINAL : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100304 public:
Vladimir Marko944da602016-02-19 12:27:55 +0000305 StringSection(ElfBuilder<ElfTypes>* owner,
306 const std::string& name,
307 Elf_Word flags,
308 Elf_Word align)
309 : Section(owner,
310 name,
311 SHT_STRTAB,
312 flags,
313 /* link */ nullptr,
314 /* info */ 0,
315 align,
316 /* entsize */ 0),
David Srbecky6d8c8f02015-10-26 10:57:09 +0000317 current_offset_(0) {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100318 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100319
David Srbecky6d8c8f02015-10-26 10:57:09 +0000320 Elf_Word Write(const std::string& name) {
321 if (current_offset_ == 0) {
322 DCHECK(name.empty());
323 }
324 Elf_Word offset = current_offset_;
325 this->WriteFully(name.c_str(), name.length() + 1);
326 current_offset_ += name.length() + 1;
David Srbeckybc90fd02015-04-22 19:40:27 +0100327 return offset;
328 }
329
David Srbeckybc90fd02015-04-22 19:40:27 +0100330 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000331 Elf_Word current_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100332 };
333
David Srbeckybc90fd02015-04-22 19:40:27 +0100334 // Writer of .dynsym and .symtab sections.
Vladimir Marko944da602016-02-19 12:27:55 +0000335 class SymbolSection FINAL : public CachedSection {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100336 public:
Vladimir Marko944da602016-02-19 12:27:55 +0000337 SymbolSection(ElfBuilder<ElfTypes>* owner,
338 const std::string& name,
339 Elf_Word type,
340 Elf_Word flags,
341 Section* strtab)
342 : CachedSection(owner,
343 name,
344 type,
345 flags,
346 strtab,
347 /* info */ 0,
348 sizeof(Elf_Off),
349 sizeof(Elf_Sym)) {
350 // The symbol table always has to start with NULL symbol.
351 Elf_Sym null_symbol = Elf_Sym();
352 CachedSection::Add(&null_symbol, sizeof(null_symbol));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000353 }
354
355 // Buffer symbol for this section. It will be written later.
David Srbecky5cc349f2015-12-18 15:04:48 +0000356 // If the symbol's section is null, it will be considered absolute (SHN_ABS).
357 // (we use this in JIT to reference code which is stored outside the debug ELF file)
Vladimir Marko944da602016-02-19 12:27:55 +0000358 void Add(Elf_Word name,
359 const Section* section,
360 Elf_Addr addr,
Vladimir Marko944da602016-02-19 12:27:55 +0000361 Elf_Word size,
362 uint8_t binding,
David Srbecky197160d2016-03-07 17:33:57 +0000363 uint8_t type) {
364 Elf_Word section_index;
365 if (section != nullptr) {
366 DCHECK_LE(section->GetAddress(), addr);
367 DCHECK_LE(addr, section->GetAddress() + section->GetSize());
368 section_index = section->GetSectionIndex();
369 } else {
370 section_index = static_cast<Elf_Word>(SHN_ABS);
371 }
372 Add(name, section_index, addr, size, binding, type);
Vladimir Marko944da602016-02-19 12:27:55 +0000373 }
374
375 void Add(Elf_Word name,
376 Elf_Word section_index,
377 Elf_Addr addr,
378 Elf_Word size,
379 uint8_t binding,
David Srbecky197160d2016-03-07 17:33:57 +0000380 uint8_t type) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000381 Elf_Sym sym = Elf_Sym();
382 sym.st_name = name;
Vladimir Marko944da602016-02-19 12:27:55 +0000383 sym.st_value = addr;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000384 sym.st_size = size;
David Srbecky197160d2016-03-07 17:33:57 +0000385 sym.st_other = 0;
Vladimir Marko944da602016-02-19 12:27:55 +0000386 sym.st_shndx = section_index;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000387 sym.st_info = (binding << 4) + (type & 0xf);
Vladimir Marko944da602016-02-19 12:27:55 +0000388 CachedSection::Add(&sym, sizeof(sym));
David Srbecky0c5bbc12015-04-28 17:54:52 +0100389 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100390 };
391
Douglas Leung316a2182015-09-17 15:26:25 -0700392 class AbiflagsSection FINAL : public Section {
393 public:
394 // Section with Mips abiflag info.
395 static constexpr uint8_t MIPS_AFL_REG_NONE = 0; // no registers
396 static constexpr uint8_t MIPS_AFL_REG_32 = 1; // 32-bit registers
397 static constexpr uint8_t MIPS_AFL_REG_64 = 2; // 64-bit registers
398 static constexpr uint32_t MIPS_AFL_FLAGS1_ODDSPREG = 1; // Uses odd single-prec fp regs
399 static constexpr uint8_t MIPS_ABI_FP_DOUBLE = 1; // -mdouble-float
400 static constexpr uint8_t MIPS_ABI_FP_XX = 5; // -mfpxx
401 static constexpr uint8_t MIPS_ABI_FP_64A = 7; // -mips32r* -mfp64 -mno-odd-spreg
402
403 AbiflagsSection(ElfBuilder<ElfTypes>* owner,
404 const std::string& name,
405 Elf_Word type,
406 Elf_Word flags,
407 const Section* link,
408 Elf_Word info,
409 Elf_Word align,
410 Elf_Word entsize,
411 InstructionSet isa,
412 const InstructionSetFeatures* features)
413 : Section(owner, name, type, flags, link, info, align, entsize) {
414 if (isa == kMips || isa == kMips64) {
415 bool fpu32 = false; // assume mips64 values
416 uint8_t isa_rev = 6; // assume mips64 values
417 if (isa == kMips) {
418 // adjust for mips32 values
419 fpu32 = features->AsMipsInstructionSetFeatures()->Is32BitFloatingPoint();
420 isa_rev = features->AsMipsInstructionSetFeatures()->IsR6()
421 ? 6
422 : features->AsMipsInstructionSetFeatures()->IsMipsIsaRevGreaterThanEqual2()
423 ? (fpu32 ? 2 : 5)
424 : 1;
425 }
426 abiflags_.version = 0; // version of flags structure
427 abiflags_.isa_level = (isa == kMips) ? 32 : 64;
428 abiflags_.isa_rev = isa_rev;
429 abiflags_.gpr_size = (isa == kMips) ? MIPS_AFL_REG_32 : MIPS_AFL_REG_64;
430 abiflags_.cpr1_size = fpu32 ? MIPS_AFL_REG_32 : MIPS_AFL_REG_64;
431 abiflags_.cpr2_size = MIPS_AFL_REG_NONE;
432 // Set the fp_abi to MIPS_ABI_FP_64A for mips32 with 64-bit FPUs (ie: mips32 R5 and R6).
433 // Otherwise set to MIPS_ABI_FP_DOUBLE.
434 abiflags_.fp_abi = (isa == kMips && !fpu32) ? MIPS_ABI_FP_64A : MIPS_ABI_FP_DOUBLE;
435 abiflags_.isa_ext = 0;
436 abiflags_.ases = 0;
437 // To keep the code simple, we are not using odd FP reg for single floats for both
438 // mips32 and mips64 ART. Therefore we are not setting the MIPS_AFL_FLAGS1_ODDSPREG bit.
439 abiflags_.flags1 = 0;
440 abiflags_.flags2 = 0;
441 }
442 }
443
444 Elf_Word GetSize() const {
445 return sizeof(abiflags_);
446 }
447
448 void Write() {
449 this->WriteFully(&abiflags_, sizeof(abiflags_));
450 }
451
452 private:
453 struct {
454 uint16_t version; // version of this structure
455 uint8_t isa_level, isa_rev, gpr_size, cpr1_size, cpr2_size;
456 uint8_t fp_abi;
457 uint32_t isa_ext, ases, flags1, flags2;
458 } abiflags_;
459 };
460
David Srbecky5d811202016-03-08 13:21:22 +0000461 ElfBuilder(InstructionSet isa, const InstructionSetFeatures* features, OutputStream* output)
Vladimir Marko131980f2015-12-03 18:29:23 +0000462 : isa_(isa),
David Srbecky5d811202016-03-08 13:21:22 +0000463 features_(features),
Vladimir Marko131980f2015-12-03 18:29:23 +0000464 stream_(output),
465 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
466 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
467 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
468 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
469 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
470 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
471 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
472 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
473 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
David Srbecky579942f2016-01-28 20:01:28 +0000474 strtab_(this, ".strtab", 0, 1),
Vladimir Marko131980f2015-12-03 18:29:23 +0000475 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
476 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
477 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
478 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
479 shstrtab_(this, ".shstrtab", 0, 1),
Douglas Leung316a2182015-09-17 15:26:25 -0700480 abiflags_(this, ".MIPS.abiflags", SHT_MIPS_ABIFLAGS, SHF_ALLOC, nullptr, 0, kPageSize, 0,
481 isa, features),
David Srbecky579942f2016-01-28 20:01:28 +0000482 started_(false),
Vladimir Marko944da602016-02-19 12:27:55 +0000483 write_program_headers_(false),
484 loaded_size_(0u),
Vladimir Marko131980f2015-12-03 18:29:23 +0000485 virtual_address_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000486 text_.phdr_flags_ = PF_R | PF_X;
487 bss_.phdr_flags_ = PF_R | PF_W;
488 dynamic_.phdr_flags_ = PF_R | PF_W;
489 dynamic_.phdr_type_ = PT_DYNAMIC;
490 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Douglas Leung316a2182015-09-17 15:26:25 -0700491 abiflags_.phdr_type_ = PT_MIPS_ABIFLAGS;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700492 }
493 ~ElfBuilder() {}
494
David Srbecky6d8c8f02015-10-26 10:57:09 +0000495 InstructionSet GetIsa() { return isa_; }
496 Section* GetRoData() { return &rodata_; }
497 Section* GetText() { return &text_; }
498 Section* GetBss() { return &bss_; }
499 StringSection* GetStrTab() { return &strtab_; }
500 SymbolSection* GetSymTab() { return &symtab_; }
501 Section* GetEhFrame() { return &eh_frame_; }
502 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
503 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000504 Section* GetDebugInfo() { return &debug_info_; }
505 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700506
David Srbecky6d8c8f02015-10-26 10:57:09 +0000507 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
508 // (exposed publicly for tests)
Vladimir Marko10c13562015-11-25 14:33:36 +0000509 static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000510 std::vector<uint8_t>* buffer) {
511 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
512 uintptr_t address = 0; // relative to start of section.
513 for (uintptr_t location : locations) {
514 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
515 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
516 address = location;
517 }
518 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700519
Vladimir Marko10c13562015-11-25 14:33:36 +0000520 void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000521 std::vector<uint8_t> buffer;
Vladimir Marko10c13562015-11-25 14:33:36 +0000522 EncodeOatPatches(patch_locations, &buffer);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000523 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
524 s->Start();
525 s->WriteFully(buffer.data(), buffer.size());
526 s->End();
527 other_sections_.push_back(std::move(s));
528 }
David Srbecky527c9c72015-04-17 21:14:10 +0100529
David Srbecky6d8c8f02015-10-26 10:57:09 +0000530 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
531 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
532 s->Start();
533 s->WriteFully(buffer->data(), buffer->size());
534 s->End();
535 other_sections_.push_back(std::move(s));
536 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700537
David Srbecky579942f2016-01-28 20:01:28 +0000538 // Reserve space for ELF header and program headers.
539 // We do not know the number of headers until later, so
540 // it is easiest to just reserve a fixed amount of space.
541 // Program headers are required for loading by the linker.
542 // It is possible to omit them for ELF files used for debugging.
543 void Start(bool write_program_headers = true) {
544 int size = sizeof(Elf_Ehdr);
545 if (write_program_headers) {
546 size += sizeof(Elf_Phdr) * kMaxProgramHeaders;
547 }
Vladimir Marko131980f2015-12-03 18:29:23 +0000548 stream_.Seek(size, kSeekSet);
David Srbecky579942f2016-01-28 20:01:28 +0000549 started_ = true;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000550 virtual_address_ += size;
David Srbecky579942f2016-01-28 20:01:28 +0000551 write_program_headers_ = write_program_headers;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000552 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700553
David Srbecky6d8c8f02015-10-26 10:57:09 +0000554 void End() {
David Srbecky579942f2016-01-28 20:01:28 +0000555 DCHECK(started_);
556
Vladimir Marko944da602016-02-19 12:27:55 +0000557 // Note: loaded_size_ == 0 for tests that don't write .rodata, .text, .bss,
558 // .dynstr, dynsym, .hash and .dynamic. These tests should not read loaded_size_.
559 // TODO: Either refactor the .eh_frame creation so that it counts towards loaded_size_,
560 // or remove all support for .eh_frame. (The currently unused .eh_frame counts towards
561 // the virtual_address_ but we don't consider it for loaded_size_.)
562 CHECK(loaded_size_ == 0 || loaded_size_ == RoundUp(virtual_address_, kPageSize))
563 << loaded_size_ << " " << virtual_address_;
564
David Srbecky6d8c8f02015-10-26 10:57:09 +0000565 // Write section names and finish the section headers.
566 shstrtab_.Start();
567 shstrtab_.Write("");
568 for (auto* section : sections_) {
569 section->header_.sh_name = shstrtab_.Write(section->name_);
570 if (section->link_ != nullptr) {
571 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100572 }
David Srbecky527c9c72015-04-17 21:14:10 +0100573 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000574 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100575
David Srbecky6d8c8f02015-10-26 10:57:09 +0000576 // Write section headers at the end of the ELF file.
577 std::vector<Elf_Shdr> shdrs;
578 shdrs.reserve(1u + sections_.size());
579 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
580 for (auto* section : sections_) {
581 shdrs.push_back(section->header_);
582 }
583 Elf_Off section_headers_offset;
David Srbecky579942f2016-01-28 20:01:28 +0000584 section_headers_offset = AlignFileOffset(sizeof(Elf_Off));
Vladimir Marko131980f2015-12-03 18:29:23 +0000585 stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
586
587 // Flush everything else before writing the program headers. This should prevent
588 // the OS from reordering writes, so that we don't end up with valid headers
589 // and partially written data if we suddenly lose power, for example.
590 stream_.Flush();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000591
David Srbecky579942f2016-01-28 20:01:28 +0000592 // The main ELF header.
Douglas Leung316a2182015-09-17 15:26:25 -0700593 Elf_Ehdr elf_header = MakeElfHeader(isa_, features_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100594 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000595 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100596 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
David Srbecky579942f2016-01-28 20:01:28 +0000597
598 // Program headers (i.e. mmap instructions).
599 std::vector<Elf_Phdr> phdrs;
600 if (write_program_headers_) {
601 phdrs = MakeProgramHeaders();
602 CHECK_LE(phdrs.size(), kMaxProgramHeaders);
603 elf_header.e_phoff = sizeof(Elf_Ehdr);
604 elf_header.e_phnum = phdrs.size();
605 }
606
Vladimir Marko131980f2015-12-03 18:29:23 +0000607 stream_.Seek(0, kSeekSet);
608 stream_.WriteFully(&elf_header, sizeof(elf_header));
609 stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
610 stream_.Flush();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700611 }
612
David Srbecky6d8c8f02015-10-26 10:57:09 +0000613 // The running program does not have access to section headers
614 // and the loader is not supposed to use them either.
615 // The dynamic sections therefore replicates some of the layout
616 // information like the address and size of .rodata and .text.
617 // It also contains other metadata like the SONAME.
618 // The .dynamic section is found using the PT_DYNAMIC program header.
Vladimir Marko944da602016-02-19 12:27:55 +0000619 void PrepareDynamicSection(const std::string& elf_file_path,
620 Elf_Word rodata_size,
621 Elf_Word text_size,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000622 Elf_Word bss_size,
623 Elf_Word bss_roots_offset) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000624 std::string soname(elf_file_path);
625 size_t directory_separator_pos = soname.rfind('/');
626 if (directory_separator_pos != std::string::npos) {
627 soname = soname.substr(directory_separator_pos + 1);
628 }
629
Vladimir Marko944da602016-02-19 12:27:55 +0000630 // Calculate addresses of .text, .bss and .dynstr.
631 DCHECK_EQ(rodata_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
632 DCHECK_EQ(text_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
633 DCHECK_EQ(bss_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
634 DCHECK_EQ(dynstr_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
635 Elf_Word rodata_address = rodata_.GetAddress();
636 Elf_Word text_address = RoundUp(rodata_address + rodata_size, kPageSize);
637 Elf_Word bss_address = RoundUp(text_address + text_size, kPageSize);
Douglas Leung316a2182015-09-17 15:26:25 -0700638 Elf_Word abiflags_address = RoundUp(bss_address + bss_size, kPageSize);
639 Elf_Word abiflags_size = 0;
640 if (isa_ == kMips || isa_ == kMips64) {
641 abiflags_size = abiflags_.GetSize();
642 }
643 Elf_Word dynstr_address = RoundUp(abiflags_address + abiflags_size, kPageSize);
Vladimir Marko45724f92016-02-17 17:46:10 +0000644
Vladimir Marko944da602016-02-19 12:27:55 +0000645 // Cache .dynstr, .dynsym and .hash data.
646 dynstr_.Add(""); // dynstr should start with empty string.
647 Elf_Word rodata_index = rodata_.GetSectionIndex();
648 Elf_Word oatdata = dynstr_.Add("oatdata");
649 dynsym_.Add(oatdata, rodata_index, rodata_address, rodata_size, STB_GLOBAL, STT_OBJECT);
650 if (text_size != 0u) {
651 Elf_Word text_index = rodata_index + 1u;
652 Elf_Word oatexec = dynstr_.Add("oatexec");
653 dynsym_.Add(oatexec, text_index, text_address, text_size, STB_GLOBAL, STT_OBJECT);
654 Elf_Word oatlastword = dynstr_.Add("oatlastword");
655 Elf_Word oatlastword_address = text_address + text_size - 4;
656 dynsym_.Add(oatlastword, text_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
657 } else if (rodata_size != 0) {
658 // rodata_ can be size 0 for dwarf_test.
659 Elf_Word oatlastword = dynstr_.Add("oatlastword");
660 Elf_Word oatlastword_address = rodata_address + rodata_size - 4;
661 dynsym_.Add(oatlastword, rodata_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
662 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000663 DCHECK_LE(bss_roots_offset, bss_size);
Vladimir Marko944da602016-02-19 12:27:55 +0000664 if (bss_size != 0u) {
665 Elf_Word bss_index = rodata_index + 1u + (text_size != 0 ? 1u : 0u);
666 Elf_Word oatbss = dynstr_.Add("oatbss");
Vladimir Markoaad75c62016-10-03 08:46:48 +0000667 dynsym_.Add(oatbss, bss_index, bss_address, bss_roots_offset, STB_GLOBAL, STT_OBJECT);
668 // Add a symbol marking the start of the GC roots part of the .bss, if not empty.
669 if (bss_roots_offset != bss_size) {
670 DCHECK_LT(bss_roots_offset, bss_size);
671 Elf_Word bss_roots_address = bss_address + bss_roots_offset;
672 Elf_Word bss_roots_size = bss_size - bss_roots_offset;
673 Elf_Word oatbssroots = dynstr_.Add("oatbssroots");
674 dynsym_.Add(
675 oatbssroots, bss_index, bss_roots_address, bss_roots_size, STB_GLOBAL, STT_OBJECT);
676 }
Vladimir Marko944da602016-02-19 12:27:55 +0000677 Elf_Word oatbsslastword = dynstr_.Add("oatbsslastword");
678 Elf_Word bsslastword_address = bss_address + bss_size - 4;
679 dynsym_.Add(oatbsslastword, bss_index, bsslastword_address, 4, STB_GLOBAL, STT_OBJECT);
680 }
681 Elf_Word soname_offset = dynstr_.Add(soname);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000682
683 // We do not really need a hash-table since there is so few entries.
684 // However, the hash-table is the only way the linker can actually
685 // determine the number of symbols in .dynsym so it is required.
Vladimir Marko944da602016-02-19 12:27:55 +0000686 int count = dynsym_.GetCacheSize() / sizeof(Elf_Sym); // Includes NULL.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000687 std::vector<Elf_Word> hash;
688 hash.push_back(1); // Number of buckets.
689 hash.push_back(count); // Number of chains.
690 // Buckets. Having just one makes it linear search.
691 hash.push_back(1); // Point to first non-NULL symbol.
692 // Chains. This creates linked list of symbols.
693 hash.push_back(0); // Dummy entry for the NULL symbol.
694 for (int i = 1; i < count - 1; i++) {
695 hash.push_back(i + 1); // Each symbol points to the next one.
696 }
697 hash.push_back(0); // Last symbol terminates the chain.
Vladimir Marko944da602016-02-19 12:27:55 +0000698 hash_.Add(hash.data(), hash.size() * sizeof(hash[0]));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000699
Vladimir Marko944da602016-02-19 12:27:55 +0000700 // Calculate addresses of .dynsym, .hash and .dynamic.
701 DCHECK_EQ(dynstr_.header_.sh_flags, dynsym_.header_.sh_flags);
702 DCHECK_EQ(dynsym_.header_.sh_flags, hash_.header_.sh_flags);
703 Elf_Word dynsym_address =
704 RoundUp(dynstr_address + dynstr_.GetCacheSize(), dynsym_.header_.sh_addralign);
705 Elf_Word hash_address =
706 RoundUp(dynsym_address + dynsym_.GetCacheSize(), hash_.header_.sh_addralign);
707 DCHECK_EQ(dynamic_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
708 Elf_Word dynamic_address = RoundUp(hash_address + dynsym_.GetCacheSize(), kPageSize);
709
David Srbecky6d8c8f02015-10-26 10:57:09 +0000710 Elf_Dyn dyns[] = {
Vladimir Marko944da602016-02-19 12:27:55 +0000711 { DT_HASH, { hash_address } },
712 { DT_STRTAB, { dynstr_address } },
713 { DT_SYMTAB, { dynsym_address } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000714 { DT_SYMENT, { sizeof(Elf_Sym) } },
Vladimir Marko944da602016-02-19 12:27:55 +0000715 { DT_STRSZ, { dynstr_.GetCacheSize() } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000716 { DT_SONAME, { soname_offset } },
717 { DT_NULL, { 0 } },
718 };
Vladimir Marko944da602016-02-19 12:27:55 +0000719 dynamic_.Add(&dyns, sizeof(dyns));
720
721 loaded_size_ = RoundUp(dynamic_address + dynamic_.GetCacheSize(), kPageSize);
722 }
723
724 void WriteDynamicSection() {
725 dynstr_.WriteCachedSection();
726 dynsym_.WriteCachedSection();
727 hash_.WriteCachedSection();
728 dynamic_.WriteCachedSection();
729
730 CHECK_EQ(loaded_size_, RoundUp(dynamic_.GetAddress() + dynamic_.GetSize(), kPageSize));
731 }
732
733 Elf_Word GetLoadedSize() {
734 CHECK_NE(loaded_size_, 0u);
735 return loaded_size_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700736 }
737
Douglas Leung316a2182015-09-17 15:26:25 -0700738 void WriteMIPSabiflagsSection() {
739 abiflags_.Start();
740 abiflags_.Write();
741 abiflags_.End();
742 }
743
David Srbecky6d8c8f02015-10-26 10:57:09 +0000744 // Returns true if all writes and seeks on the output stream succeeded.
745 bool Good() {
Vladimir Marko131980f2015-12-03 18:29:23 +0000746 return stream_.Good();
747 }
748
749 // Returns the builder's internal stream.
750 OutputStream* GetStream() {
751 return &stream_;
David Srbecky527c9c72015-04-17 21:14:10 +0100752 }
753
David Srbecky579942f2016-01-28 20:01:28 +0000754 off_t AlignFileOffset(size_t alignment) {
755 return stream_.Seek(RoundUp(stream_.Seek(0, kSeekCurrent), alignment), kSeekSet);
756 }
757
758 Elf_Addr AlignVirtualAddress(size_t alignment) {
759 return virtual_address_ = RoundUp(virtual_address_, alignment);
760 }
761
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700762 private:
Douglas Leung316a2182015-09-17 15:26:25 -0700763 static Elf_Ehdr MakeElfHeader(InstructionSet isa, const InstructionSetFeatures* features) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100764 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700765 switch (isa) {
766 case kArm:
767 // Fall through.
768 case kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100769 elf_header.e_machine = EM_ARM;
770 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700771 break;
772 }
773 case kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100774 elf_header.e_machine = EM_AARCH64;
775 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700776 break;
777 }
778 case kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100779 elf_header.e_machine = EM_386;
780 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700781 break;
782 }
783 case kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100784 elf_header.e_machine = EM_X86_64;
785 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700786 break;
787 }
788 case kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100789 elf_header.e_machine = EM_MIPS;
790 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700791 EF_MIPS_PIC |
792 EF_MIPS_CPIC |
793 EF_MIPS_ABI_O32 |
Greg Kaiser81a18992016-06-16 15:55:15 -0700794 (features->AsMipsInstructionSetFeatures()->IsR6()
795 ? EF_MIPS_ARCH_32R6
796 : EF_MIPS_ARCH_32R2));
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700797 break;
798 }
Andreas Gampe57b34292015-01-14 15:45:59 -0800799 case kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100800 elf_header.e_machine = EM_MIPS;
801 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700802 EF_MIPS_PIC |
803 EF_MIPS_CPIC |
804 EF_MIPS_ARCH_64R6);
Andreas Gampe57b34292015-01-14 15:45:59 -0800805 break;
806 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100807 case kNone: {
808 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000809 break;
810 }
811 default: {
812 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700813 }
814 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700815
David Srbeckybc90fd02015-04-22 19:40:27 +0100816 elf_header.e_ident[EI_MAG0] = ELFMAG0;
817 elf_header.e_ident[EI_MAG1] = ELFMAG1;
818 elf_header.e_ident[EI_MAG2] = ELFMAG2;
819 elf_header.e_ident[EI_MAG3] = ELFMAG3;
820 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Tong Shen62d1ca32014-09-03 17:24:56 -0700821 ? ELFCLASS32 : ELFCLASS64;;
David Srbeckybc90fd02015-04-22 19:40:27 +0100822 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
823 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
824 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
825 elf_header.e_ident[EI_ABIVERSION] = 0;
826 elf_header.e_type = ET_DYN;
827 elf_header.e_version = 1;
828 elf_header.e_entry = 0;
829 elf_header.e_ehsize = sizeof(Elf_Ehdr);
830 elf_header.e_phentsize = sizeof(Elf_Phdr);
831 elf_header.e_shentsize = sizeof(Elf_Shdr);
832 elf_header.e_phoff = sizeof(Elf_Ehdr);
833 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700834 }
835
David Srbecky6d8c8f02015-10-26 10:57:09 +0000836 // Create program headers based on written sections.
837 std::vector<Elf_Phdr> MakeProgramHeaders() {
838 CHECK(!sections_.empty());
839 std::vector<Elf_Phdr> phdrs;
840 {
841 // The program headers must start with PT_PHDR which is used in
842 // loaded process to determine the number of program headers.
843 Elf_Phdr phdr = Elf_Phdr();
844 phdr.p_type = PT_PHDR;
845 phdr.p_flags = PF_R;
846 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
847 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
848 phdr.p_align = sizeof(Elf_Off);
849 phdrs.push_back(phdr);
850 // Tell the linker to mmap the start of file to memory.
851 Elf_Phdr load = Elf_Phdr();
852 load.p_type = PT_LOAD;
853 load.p_flags = PF_R;
854 load.p_offset = load.p_vaddr = load.p_paddr = 0;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000855 load.p_filesz = load.p_memsz = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000856 load.p_align = kPageSize;
857 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100858 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000859 // Create program headers for sections.
860 for (auto* section : sections_) {
861 const Elf_Shdr& shdr = section->header_;
862 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
863 // PT_LOAD tells the linker to mmap part of the file.
864 // The linker can only mmap page-aligned sections.
865 // Single PT_LOAD may contain several ELF sections.
866 Elf_Phdr& prev = phdrs.back();
867 Elf_Phdr load = Elf_Phdr();
868 load.p_type = PT_LOAD;
869 load.p_flags = section->phdr_flags_;
870 load.p_offset = shdr.sh_offset;
871 load.p_vaddr = load.p_paddr = shdr.sh_addr;
872 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
873 load.p_memsz = shdr.sh_size;
874 load.p_align = shdr.sh_addralign;
875 if (prev.p_type == load.p_type &&
876 prev.p_flags == load.p_flags &&
877 prev.p_filesz == prev.p_memsz && // Do not merge .bss
878 load.p_filesz == load.p_memsz) { // Do not merge .bss
879 // Merge this PT_LOAD with the previous one.
880 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
881 prev.p_filesz = size;
882 prev.p_memsz = size;
883 } else {
884 // If we are adding new load, it must be aligned.
885 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
886 phdrs.push_back(load);
887 }
888 }
889 }
890 for (auto* section : sections_) {
891 const Elf_Shdr& shdr = section->header_;
892 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
893 // Other PT_* types allow the program to locate interesting
894 // parts of memory at runtime. They must overlap with PT_LOAD.
895 if (section->phdr_type_ != 0) {
896 Elf_Phdr phdr = Elf_Phdr();
897 phdr.p_type = section->phdr_type_;
898 phdr.p_flags = section->phdr_flags_;
899 phdr.p_offset = shdr.sh_offset;
900 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
901 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
902 phdr.p_align = shdr.sh_addralign;
903 phdrs.push_back(phdr);
904 }
905 }
906 }
907 // Set the size of the initial PT_PHDR.
908 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
909 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100910
David Srbecky6d8c8f02015-10-26 10:57:09 +0000911 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700912 }
913
David Srbeckybc90fd02015-04-22 19:40:27 +0100914 InstructionSet isa_;
David Srbecky5d811202016-03-08 13:21:22 +0000915 const InstructionSetFeatures* features_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000916
Vladimir Marko131980f2015-12-03 18:29:23 +0000917 ErrorDelayingOutputStream stream_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000918
919 Section rodata_;
920 Section text_;
921 Section bss_;
Vladimir Marko944da602016-02-19 12:27:55 +0000922 CachedStringSection dynstr_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000923 SymbolSection dynsym_;
Vladimir Marko944da602016-02-19 12:27:55 +0000924 CachedSection hash_;
925 CachedSection dynamic_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000926 Section eh_frame_;
927 Section eh_frame_hdr_;
928 StringSection strtab_;
929 SymbolSection symtab_;
930 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +0000931 Section debug_info_;
932 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000933 StringSection shstrtab_;
Douglas Leung316a2182015-09-17 15:26:25 -0700934 AbiflagsSection abiflags_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000935 std::vector<std::unique_ptr<Section>> other_sections_;
936
937 // List of used section in the order in which they were written.
938 std::vector<Section*> sections_;
939
David Srbecky579942f2016-01-28 20:01:28 +0000940 bool started_;
Vladimir Marko944da602016-02-19 12:27:55 +0000941 bool write_program_headers_;
942
943 // The size of the memory taken by the ELF file when loaded.
944 size_t loaded_size_;
David Srbecky579942f2016-01-28 20:01:28 +0000945
David Srbecky6d8c8f02015-10-26 10:57:09 +0000946 // Used for allocation of virtual address space.
947 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700948
949 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700950};
951
952} // namespace art
953
954#endif // ART_COMPILER_ELF_BUILDER_H_