blob: 02831c9dc71de8d544e4e1379e656cfebdf0b167 [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,
622 Elf_Word bss_size) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000623 std::string soname(elf_file_path);
624 size_t directory_separator_pos = soname.rfind('/');
625 if (directory_separator_pos != std::string::npos) {
626 soname = soname.substr(directory_separator_pos + 1);
627 }
628
Vladimir Marko944da602016-02-19 12:27:55 +0000629 // Calculate addresses of .text, .bss and .dynstr.
630 DCHECK_EQ(rodata_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
631 DCHECK_EQ(text_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
632 DCHECK_EQ(bss_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
633 DCHECK_EQ(dynstr_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
634 Elf_Word rodata_address = rodata_.GetAddress();
635 Elf_Word text_address = RoundUp(rodata_address + rodata_size, kPageSize);
636 Elf_Word bss_address = RoundUp(text_address + text_size, kPageSize);
Douglas Leung316a2182015-09-17 15:26:25 -0700637 Elf_Word abiflags_address = RoundUp(bss_address + bss_size, kPageSize);
638 Elf_Word abiflags_size = 0;
639 if (isa_ == kMips || isa_ == kMips64) {
640 abiflags_size = abiflags_.GetSize();
641 }
642 Elf_Word dynstr_address = RoundUp(abiflags_address + abiflags_size, kPageSize);
Vladimir Marko45724f92016-02-17 17:46:10 +0000643
Vladimir Marko944da602016-02-19 12:27:55 +0000644 // Cache .dynstr, .dynsym and .hash data.
645 dynstr_.Add(""); // dynstr should start with empty string.
646 Elf_Word rodata_index = rodata_.GetSectionIndex();
647 Elf_Word oatdata = dynstr_.Add("oatdata");
648 dynsym_.Add(oatdata, rodata_index, rodata_address, rodata_size, STB_GLOBAL, STT_OBJECT);
649 if (text_size != 0u) {
650 Elf_Word text_index = rodata_index + 1u;
651 Elf_Word oatexec = dynstr_.Add("oatexec");
652 dynsym_.Add(oatexec, text_index, text_address, text_size, STB_GLOBAL, STT_OBJECT);
653 Elf_Word oatlastword = dynstr_.Add("oatlastword");
654 Elf_Word oatlastword_address = text_address + text_size - 4;
655 dynsym_.Add(oatlastword, text_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
656 } else if (rodata_size != 0) {
657 // rodata_ can be size 0 for dwarf_test.
658 Elf_Word oatlastword = dynstr_.Add("oatlastword");
659 Elf_Word oatlastword_address = rodata_address + rodata_size - 4;
660 dynsym_.Add(oatlastword, rodata_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
661 }
662 if (bss_size != 0u) {
663 Elf_Word bss_index = rodata_index + 1u + (text_size != 0 ? 1u : 0u);
664 Elf_Word oatbss = dynstr_.Add("oatbss");
665 dynsym_.Add(oatbss, bss_index, bss_address, bss_size, STB_GLOBAL, STT_OBJECT);
666 Elf_Word oatbsslastword = dynstr_.Add("oatbsslastword");
667 Elf_Word bsslastword_address = bss_address + bss_size - 4;
668 dynsym_.Add(oatbsslastword, bss_index, bsslastword_address, 4, STB_GLOBAL, STT_OBJECT);
669 }
670 Elf_Word soname_offset = dynstr_.Add(soname);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000671
672 // We do not really need a hash-table since there is so few entries.
673 // However, the hash-table is the only way the linker can actually
674 // determine the number of symbols in .dynsym so it is required.
Vladimir Marko944da602016-02-19 12:27:55 +0000675 int count = dynsym_.GetCacheSize() / sizeof(Elf_Sym); // Includes NULL.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000676 std::vector<Elf_Word> hash;
677 hash.push_back(1); // Number of buckets.
678 hash.push_back(count); // Number of chains.
679 // Buckets. Having just one makes it linear search.
680 hash.push_back(1); // Point to first non-NULL symbol.
681 // Chains. This creates linked list of symbols.
682 hash.push_back(0); // Dummy entry for the NULL symbol.
683 for (int i = 1; i < count - 1; i++) {
684 hash.push_back(i + 1); // Each symbol points to the next one.
685 }
686 hash.push_back(0); // Last symbol terminates the chain.
Vladimir Marko944da602016-02-19 12:27:55 +0000687 hash_.Add(hash.data(), hash.size() * sizeof(hash[0]));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000688
Vladimir Marko944da602016-02-19 12:27:55 +0000689 // Calculate addresses of .dynsym, .hash and .dynamic.
690 DCHECK_EQ(dynstr_.header_.sh_flags, dynsym_.header_.sh_flags);
691 DCHECK_EQ(dynsym_.header_.sh_flags, hash_.header_.sh_flags);
692 Elf_Word dynsym_address =
693 RoundUp(dynstr_address + dynstr_.GetCacheSize(), dynsym_.header_.sh_addralign);
694 Elf_Word hash_address =
695 RoundUp(dynsym_address + dynsym_.GetCacheSize(), hash_.header_.sh_addralign);
696 DCHECK_EQ(dynamic_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
697 Elf_Word dynamic_address = RoundUp(hash_address + dynsym_.GetCacheSize(), kPageSize);
698
David Srbecky6d8c8f02015-10-26 10:57:09 +0000699 Elf_Dyn dyns[] = {
Vladimir Marko944da602016-02-19 12:27:55 +0000700 { DT_HASH, { hash_address } },
701 { DT_STRTAB, { dynstr_address } },
702 { DT_SYMTAB, { dynsym_address } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000703 { DT_SYMENT, { sizeof(Elf_Sym) } },
Vladimir Marko944da602016-02-19 12:27:55 +0000704 { DT_STRSZ, { dynstr_.GetCacheSize() } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000705 { DT_SONAME, { soname_offset } },
706 { DT_NULL, { 0 } },
707 };
Vladimir Marko944da602016-02-19 12:27:55 +0000708 dynamic_.Add(&dyns, sizeof(dyns));
709
710 loaded_size_ = RoundUp(dynamic_address + dynamic_.GetCacheSize(), kPageSize);
711 }
712
713 void WriteDynamicSection() {
714 dynstr_.WriteCachedSection();
715 dynsym_.WriteCachedSection();
716 hash_.WriteCachedSection();
717 dynamic_.WriteCachedSection();
718
719 CHECK_EQ(loaded_size_, RoundUp(dynamic_.GetAddress() + dynamic_.GetSize(), kPageSize));
720 }
721
722 Elf_Word GetLoadedSize() {
723 CHECK_NE(loaded_size_, 0u);
724 return loaded_size_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700725 }
726
Douglas Leung316a2182015-09-17 15:26:25 -0700727 void WriteMIPSabiflagsSection() {
728 abiflags_.Start();
729 abiflags_.Write();
730 abiflags_.End();
731 }
732
David Srbecky6d8c8f02015-10-26 10:57:09 +0000733 // Returns true if all writes and seeks on the output stream succeeded.
734 bool Good() {
Vladimir Marko131980f2015-12-03 18:29:23 +0000735 return stream_.Good();
736 }
737
738 // Returns the builder's internal stream.
739 OutputStream* GetStream() {
740 return &stream_;
David Srbecky527c9c72015-04-17 21:14:10 +0100741 }
742
David Srbecky579942f2016-01-28 20:01:28 +0000743 off_t AlignFileOffset(size_t alignment) {
744 return stream_.Seek(RoundUp(stream_.Seek(0, kSeekCurrent), alignment), kSeekSet);
745 }
746
747 Elf_Addr AlignVirtualAddress(size_t alignment) {
748 return virtual_address_ = RoundUp(virtual_address_, alignment);
749 }
750
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700751 private:
Douglas Leung316a2182015-09-17 15:26:25 -0700752 static Elf_Ehdr MakeElfHeader(InstructionSet isa, const InstructionSetFeatures* features) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100753 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700754 switch (isa) {
755 case kArm:
756 // Fall through.
757 case kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100758 elf_header.e_machine = EM_ARM;
759 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700760 break;
761 }
762 case kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100763 elf_header.e_machine = EM_AARCH64;
764 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700765 break;
766 }
767 case kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100768 elf_header.e_machine = EM_386;
769 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700770 break;
771 }
772 case kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100773 elf_header.e_machine = EM_X86_64;
774 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700775 break;
776 }
777 case kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100778 elf_header.e_machine = EM_MIPS;
779 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700780 EF_MIPS_PIC |
781 EF_MIPS_CPIC |
782 EF_MIPS_ABI_O32 |
Greg Kaiser81a18992016-06-16 15:55:15 -0700783 (features->AsMipsInstructionSetFeatures()->IsR6()
784 ? EF_MIPS_ARCH_32R6
785 : EF_MIPS_ARCH_32R2));
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700786 break;
787 }
Andreas Gampe57b34292015-01-14 15:45:59 -0800788 case kMips64: {
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_ARCH_64R6);
Andreas Gampe57b34292015-01-14 15:45:59 -0800794 break;
795 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100796 case kNone: {
797 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000798 break;
799 }
800 default: {
801 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700802 }
803 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700804
David Srbeckybc90fd02015-04-22 19:40:27 +0100805 elf_header.e_ident[EI_MAG0] = ELFMAG0;
806 elf_header.e_ident[EI_MAG1] = ELFMAG1;
807 elf_header.e_ident[EI_MAG2] = ELFMAG2;
808 elf_header.e_ident[EI_MAG3] = ELFMAG3;
809 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Tong Shen62d1ca32014-09-03 17:24:56 -0700810 ? ELFCLASS32 : ELFCLASS64;;
David Srbeckybc90fd02015-04-22 19:40:27 +0100811 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
812 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
813 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
814 elf_header.e_ident[EI_ABIVERSION] = 0;
815 elf_header.e_type = ET_DYN;
816 elf_header.e_version = 1;
817 elf_header.e_entry = 0;
818 elf_header.e_ehsize = sizeof(Elf_Ehdr);
819 elf_header.e_phentsize = sizeof(Elf_Phdr);
820 elf_header.e_shentsize = sizeof(Elf_Shdr);
821 elf_header.e_phoff = sizeof(Elf_Ehdr);
822 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700823 }
824
David Srbecky6d8c8f02015-10-26 10:57:09 +0000825 // Create program headers based on written sections.
826 std::vector<Elf_Phdr> MakeProgramHeaders() {
827 CHECK(!sections_.empty());
828 std::vector<Elf_Phdr> phdrs;
829 {
830 // The program headers must start with PT_PHDR which is used in
831 // loaded process to determine the number of program headers.
832 Elf_Phdr phdr = Elf_Phdr();
833 phdr.p_type = PT_PHDR;
834 phdr.p_flags = PF_R;
835 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
836 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
837 phdr.p_align = sizeof(Elf_Off);
838 phdrs.push_back(phdr);
839 // Tell the linker to mmap the start of file to memory.
840 Elf_Phdr load = Elf_Phdr();
841 load.p_type = PT_LOAD;
842 load.p_flags = PF_R;
843 load.p_offset = load.p_vaddr = load.p_paddr = 0;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000844 load.p_filesz = load.p_memsz = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000845 load.p_align = kPageSize;
846 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100847 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000848 // Create program headers for sections.
849 for (auto* section : sections_) {
850 const Elf_Shdr& shdr = section->header_;
851 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
852 // PT_LOAD tells the linker to mmap part of the file.
853 // The linker can only mmap page-aligned sections.
854 // Single PT_LOAD may contain several ELF sections.
855 Elf_Phdr& prev = phdrs.back();
856 Elf_Phdr load = Elf_Phdr();
857 load.p_type = PT_LOAD;
858 load.p_flags = section->phdr_flags_;
859 load.p_offset = shdr.sh_offset;
860 load.p_vaddr = load.p_paddr = shdr.sh_addr;
861 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
862 load.p_memsz = shdr.sh_size;
863 load.p_align = shdr.sh_addralign;
864 if (prev.p_type == load.p_type &&
865 prev.p_flags == load.p_flags &&
866 prev.p_filesz == prev.p_memsz && // Do not merge .bss
867 load.p_filesz == load.p_memsz) { // Do not merge .bss
868 // Merge this PT_LOAD with the previous one.
869 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
870 prev.p_filesz = size;
871 prev.p_memsz = size;
872 } else {
873 // If we are adding new load, it must be aligned.
874 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
875 phdrs.push_back(load);
876 }
877 }
878 }
879 for (auto* section : sections_) {
880 const Elf_Shdr& shdr = section->header_;
881 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
882 // Other PT_* types allow the program to locate interesting
883 // parts of memory at runtime. They must overlap with PT_LOAD.
884 if (section->phdr_type_ != 0) {
885 Elf_Phdr phdr = Elf_Phdr();
886 phdr.p_type = section->phdr_type_;
887 phdr.p_flags = section->phdr_flags_;
888 phdr.p_offset = shdr.sh_offset;
889 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
890 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
891 phdr.p_align = shdr.sh_addralign;
892 phdrs.push_back(phdr);
893 }
894 }
895 }
896 // Set the size of the initial PT_PHDR.
897 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
898 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100899
David Srbecky6d8c8f02015-10-26 10:57:09 +0000900 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700901 }
902
David Srbeckybc90fd02015-04-22 19:40:27 +0100903 InstructionSet isa_;
David Srbecky5d811202016-03-08 13:21:22 +0000904 const InstructionSetFeatures* features_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000905
Vladimir Marko131980f2015-12-03 18:29:23 +0000906 ErrorDelayingOutputStream stream_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000907
908 Section rodata_;
909 Section text_;
910 Section bss_;
Vladimir Marko944da602016-02-19 12:27:55 +0000911 CachedStringSection dynstr_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000912 SymbolSection dynsym_;
Vladimir Marko944da602016-02-19 12:27:55 +0000913 CachedSection hash_;
914 CachedSection dynamic_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000915 Section eh_frame_;
916 Section eh_frame_hdr_;
917 StringSection strtab_;
918 SymbolSection symtab_;
919 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +0000920 Section debug_info_;
921 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000922 StringSection shstrtab_;
Douglas Leung316a2182015-09-17 15:26:25 -0700923 AbiflagsSection abiflags_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000924 std::vector<std::unique_ptr<Section>> other_sections_;
925
926 // List of used section in the order in which they were written.
927 std::vector<Section*> sections_;
928
David Srbecky579942f2016-01-28 20:01:28 +0000929 bool started_;
Vladimir Marko944da602016-02-19 12:27:55 +0000930 bool write_program_headers_;
931
932 // The size of the memory taken by the ELF file when loaded.
933 size_t loaded_size_;
David Srbecky579942f2016-01-28 20:01:28 +0000934
David Srbecky6d8c8f02015-10-26 10:57:09 +0000935 // Used for allocation of virtual address space.
936 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700937
938 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700939};
940
941} // namespace art
942
943#endif // ART_COMPILER_ELF_BUILDER_H_