blob: b30b55e9b4ca563a5d692a61da879db8da69abfb [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
Vladimir Marko74527972016-11-29 15:57:32 +000017#ifndef ART_COMPILER_LINKER_ELF_BUILDER_H_
18#define ART_COMPILER_LINKER_ELF_BUILDER_H_
Andreas Gampe54fc26c2014-09-04 21:47:42 -070019
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 {
Vladimir Marko74527972016-11-29 15:57:32 +000033namespace linker {
Andreas Gampe54fc26c2014-09-04 21:47:42 -070034
David Srbeckybc90fd02015-04-22 19:40:27 +010035// Writes ELF file.
David Srbecky6d8c8f02015-10-26 10:57:09 +000036//
37// The basic layout of the elf file:
38// Elf_Ehdr - The ELF header.
39// Elf_Phdr[] - Program headers for the linker.
Alexey Alexandrovab40c112016-09-19 09:33:49 -070040// .note.gnu.build-id - Optional build ID section (SHA-1 digest).
David Srbecky6d8c8f02015-10-26 10:57:09 +000041// .rodata - DEX files and oat metadata.
42// .text - Compiled code.
43// .bss - Zero-initialized writeable section.
Douglas Leung316a2182015-09-17 15:26:25 -070044// .MIPS.abiflags - MIPS specific section.
David Srbecky6d8c8f02015-10-26 10:57:09 +000045// .dynstr - Names for .dynsym.
46// .dynsym - A few oat-specific dynamic symbols.
47// .hash - Hash-table for .dynsym.
48// .dynamic - Tags which let the linker locate .dynsym.
49// .strtab - Names for .symtab.
50// .symtab - Debug symbols.
51// .eh_frame - Unwind information (CFI).
52// .eh_frame_hdr - Index of .eh_frame.
53// .debug_frame - Unwind information (CFI).
54// .debug_frame.oat_patches - Addresses for relocation.
55// .debug_info - Debug information.
56// .debug_info.oat_patches - Addresses for relocation.
57// .debug_abbrev - Decoding information for .debug_info.
58// .debug_str - Strings for .debug_info.
59// .debug_line - Line number tables.
60// .debug_line.oat_patches - Addresses for relocation.
61// .text.oat_patches - Addresses for relocation.
62// .shstrtab - Names of ELF sections.
63// Elf_Shdr[] - Section headers.
64//
65// Some section are optional (the debug sections in particular).
66//
67// We try write the section data directly into the file without much
68// in-memory buffering. This means we generally write sections based on the
69// dependency order (e.g. .dynamic points to .dynsym which points to .text).
70//
71// In the cases where we need to buffer, we write the larger section first
72// and buffer the smaller one (e.g. .strtab is bigger than .symtab).
73//
74// The debug sections are written last for easier stripping.
75//
David Srbecky533c2072015-04-22 12:20:22 +010076template <typename ElfTypes>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070077class ElfBuilder FINAL {
78 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000079 static constexpr size_t kMaxProgramHeaders = 16;
Alexey Alexandrovab40c112016-09-19 09:33:49 -070080 // SHA-1 digest. Not using SHA_DIGEST_LENGTH from openssl/sha.h to avoid
81 // spreading this header dependency for just this single constant.
82 static constexpr size_t kBuildIdLen = 20;
83
David Srbecky533c2072015-04-22 12:20:22 +010084 using Elf_Addr = typename ElfTypes::Addr;
David Srbeckybc90fd02015-04-22 19:40:27 +010085 using Elf_Off = typename ElfTypes::Off;
David Srbecky533c2072015-04-22 12:20:22 +010086 using Elf_Word = typename ElfTypes::Word;
87 using Elf_Sword = typename ElfTypes::Sword;
88 using Elf_Ehdr = typename ElfTypes::Ehdr;
89 using Elf_Shdr = typename ElfTypes::Shdr;
90 using Elf_Sym = typename ElfTypes::Sym;
91 using Elf_Phdr = typename ElfTypes::Phdr;
92 using Elf_Dyn = typename ElfTypes::Dyn;
93
David Srbeckybc90fd02015-04-22 19:40:27 +010094 // Base class of all sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +000095 class Section : public OutputStream {
David Srbecky0c5bbc12015-04-28 17:54:52 +010096 public:
Vladimir Marko944da602016-02-19 12:27:55 +000097 Section(ElfBuilder<ElfTypes>* owner,
98 const std::string& name,
99 Elf_Word type,
100 Elf_Word flags,
101 const Section* link,
102 Elf_Word info,
103 Elf_Word align,
104 Elf_Word entsize)
105 : OutputStream(name),
106 owner_(owner),
107 header_(),
108 section_index_(0),
109 name_(name),
110 link_(link),
111 started_(false),
112 finished_(false),
113 phdr_flags_(PF_R),
114 phdr_type_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000115 DCHECK_GE(align, 1u);
David Srbecky491a7fe2015-05-28 00:59:08 +0100116 header_.sh_type = type;
117 header_.sh_flags = flags;
118 header_.sh_info = info;
119 header_.sh_addralign = align;
120 header_.sh_entsize = entsize;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100121 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100122
David Srbecky6d8c8f02015-10-26 10:57:09 +0000123 // Start writing of this section.
124 void Start() {
125 CHECK(!started_);
126 CHECK(!finished_);
127 started_ = true;
128 auto& sections = owner_->sections_;
129 // Check that the previous section is complete.
130 CHECK(sections.empty() || sections.back()->finished_);
131 // The first ELF section index is 1. Index 0 is reserved for NULL.
132 section_index_ = sections.size() + 1;
David Srbecky579942f2016-01-28 20:01:28 +0000133 // Page-align if we switch between allocated and non-allocated sections,
134 // or if we change the type of allocation (e.g. executable vs non-executable).
135 if (!sections.empty()) {
136 if (header_.sh_flags != sections.back()->header_.sh_flags) {
137 header_.sh_addralign = kPageSize;
138 }
139 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000140 // Align file position.
141 if (header_.sh_type != SHT_NOBITS) {
David Srbecky579942f2016-01-28 20:01:28 +0000142 header_.sh_offset = owner_->AlignFileOffset(header_.sh_addralign);
143 } else {
144 header_.sh_offset = 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000145 }
146 // Align virtual memory address.
147 if ((header_.sh_flags & SHF_ALLOC) != 0) {
David Srbecky579942f2016-01-28 20:01:28 +0000148 header_.sh_addr = owner_->AlignVirtualAddress(header_.sh_addralign);
149 } else {
150 header_.sh_addr = 0;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000151 }
David Srbecky579942f2016-01-28 20:01:28 +0000152 // Push this section on the list of written sections.
153 sections.push_back(this);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100154 }
155
David Srbecky6d8c8f02015-10-26 10:57:09 +0000156 // Finish writing of this section.
157 void End() {
158 CHECK(started_);
159 CHECK(!finished_);
160 finished_ = true;
161 if (header_.sh_type == SHT_NOBITS) {
162 CHECK_GT(header_.sh_size, 0u);
163 } else {
164 // Use the current file position to determine section size.
Vladimir Marko131980f2015-12-03 18:29:23 +0000165 off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000166 CHECK_GE(file_offset, (off_t)header_.sh_offset);
167 header_.sh_size = file_offset - header_.sh_offset;
168 }
169 if ((header_.sh_flags & SHF_ALLOC) != 0) {
170 owner_->virtual_address_ += header_.sh_size;
171 }
172 }
173
174 // Get the location of this section in virtual memory.
175 Elf_Addr GetAddress() const {
176 CHECK(started_);
177 return header_.sh_addr;
178 }
179
180 // Returns the size of the content of this section.
181 Elf_Word GetSize() const {
David Srbeckyb851b492015-11-11 20:19:38 +0000182 if (finished_) {
183 return header_.sh_size;
184 } else {
185 CHECK(started_);
186 CHECK_NE(header_.sh_type, (Elf_Word)SHT_NOBITS);
Vladimir Marko131980f2015-12-03 18:29:23 +0000187 return owner_->stream_.Seek(0, kSeekCurrent) - header_.sh_offset;
David Srbeckyb851b492015-11-11 20:19:38 +0000188 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000189 }
190
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000191 // Write this section as "NOBITS" section. (used for the .bss section)
192 // This means that the ELF file does not contain the initial data for this section
193 // and it will be zero-initialized when the ELF file is loaded in the running program.
194 void WriteNoBitsSection(Elf_Word size) {
195 DCHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000196 header_.sh_type = SHT_NOBITS;
David Srbecky579942f2016-01-28 20:01:28 +0000197 Start();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000198 header_.sh_size = size;
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000199 End();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000200 }
201
202 // This function always succeeds to simplify code.
203 // Use builder's Good() to check the actual status.
204 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
205 CHECK(started_);
206 CHECK(!finished_);
Vladimir Marko131980f2015-12-03 18:29:23 +0000207 return owner_->stream_.WriteFully(buffer, byte_count);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000208 }
209
210 // This function always succeeds to simplify code.
211 // Use builder's Good() to check the actual status.
212 off_t Seek(off_t offset, Whence whence) OVERRIDE {
213 // Forward the seek as-is and trust the caller to use it reasonably.
Vladimir Marko131980f2015-12-03 18:29:23 +0000214 return owner_->stream_.Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100215 }
216
Vladimir Marko10c13562015-11-25 14:33:36 +0000217 // This function flushes the output and returns whether it succeeded.
218 // If there was a previous failure, this does nothing and returns false, i.e. failed.
219 bool Flush() OVERRIDE {
Vladimir Marko131980f2015-12-03 18:29:23 +0000220 return owner_->stream_.Flush();
Vladimir Marko10c13562015-11-25 14:33:36 +0000221 }
222
David Srbecky0c5bbc12015-04-28 17:54:52 +0100223 Elf_Word GetSectionIndex() const {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000224 DCHECK(started_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100225 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100226 return section_index_;
227 }
228
David Srbecky0c5bbc12015-04-28 17:54:52 +0100229 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000230 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100231 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100232 Elf_Word section_index_;
233 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100234 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000235 bool started_;
236 bool finished_;
237 Elf_Word phdr_flags_;
238 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100239
David Srbecky6d8c8f02015-10-26 10:57:09 +0000240 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000241
242 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100243 };
244
Vladimir Marko944da602016-02-19 12:27:55 +0000245 class CachedSection : public Section {
246 public:
247 CachedSection(ElfBuilder<ElfTypes>* owner,
248 const std::string& name,
249 Elf_Word type,
250 Elf_Word flags,
251 const Section* link,
252 Elf_Word info,
253 Elf_Word align,
254 Elf_Word entsize)
255 : Section(owner, name, type, flags, link, info, align, entsize), cache_() { }
256
257 Elf_Word Add(const void* data, size_t length) {
258 Elf_Word offset = cache_.size();
259 const uint8_t* d = reinterpret_cast<const uint8_t*>(data);
260 cache_.insert(cache_.end(), d, d + length);
261 return offset;
262 }
263
264 Elf_Word GetCacheSize() {
265 return cache_.size();
266 }
267
268 void Write() {
269 this->WriteFully(cache_.data(), cache_.size());
270 cache_.clear();
271 cache_.shrink_to_fit();
272 }
273
274 void WriteCachedSection() {
275 this->Start();
276 Write();
277 this->End();
278 }
279
280 private:
281 std::vector<uint8_t> cache_;
282 };
283
284 // Writer of .dynstr section.
285 class CachedStringSection FINAL : public CachedSection {
286 public:
287 CachedStringSection(ElfBuilder<ElfTypes>* owner,
288 const std::string& name,
289 Elf_Word flags,
290 Elf_Word align)
291 : CachedSection(owner,
292 name,
293 SHT_STRTAB,
294 flags,
295 /* link */ nullptr,
296 /* info */ 0,
297 align,
298 /* entsize */ 0) { }
299
300 Elf_Word Add(const std::string& name) {
301 if (CachedSection::GetCacheSize() == 0u) {
302 DCHECK(name.empty());
303 }
304 return CachedSection::Add(name.c_str(), name.length() + 1);
305 }
306 };
307
308 // Writer of .strtab and .shstrtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000309 class StringSection FINAL : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100310 public:
Vladimir Marko944da602016-02-19 12:27:55 +0000311 StringSection(ElfBuilder<ElfTypes>* owner,
312 const std::string& name,
313 Elf_Word flags,
314 Elf_Word align)
315 : Section(owner,
316 name,
317 SHT_STRTAB,
318 flags,
319 /* link */ nullptr,
320 /* info */ 0,
321 align,
322 /* entsize */ 0),
David Srbecky6d8c8f02015-10-26 10:57:09 +0000323 current_offset_(0) {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100324 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100325
David Srbecky6d8c8f02015-10-26 10:57:09 +0000326 Elf_Word Write(const std::string& name) {
327 if (current_offset_ == 0) {
328 DCHECK(name.empty());
329 }
330 Elf_Word offset = current_offset_;
331 this->WriteFully(name.c_str(), name.length() + 1);
332 current_offset_ += name.length() + 1;
David Srbeckybc90fd02015-04-22 19:40:27 +0100333 return offset;
334 }
335
David Srbeckybc90fd02015-04-22 19:40:27 +0100336 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000337 Elf_Word current_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100338 };
339
David Srbeckybc90fd02015-04-22 19:40:27 +0100340 // Writer of .dynsym and .symtab sections.
Vladimir Marko944da602016-02-19 12:27:55 +0000341 class SymbolSection FINAL : public CachedSection {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100342 public:
Vladimir Marko944da602016-02-19 12:27:55 +0000343 SymbolSection(ElfBuilder<ElfTypes>* owner,
344 const std::string& name,
345 Elf_Word type,
346 Elf_Word flags,
347 Section* strtab)
348 : CachedSection(owner,
349 name,
350 type,
351 flags,
352 strtab,
353 /* info */ 0,
354 sizeof(Elf_Off),
355 sizeof(Elf_Sym)) {
356 // The symbol table always has to start with NULL symbol.
357 Elf_Sym null_symbol = Elf_Sym();
358 CachedSection::Add(&null_symbol, sizeof(null_symbol));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000359 }
360
361 // Buffer symbol for this section. It will be written later.
David Srbecky5cc349f2015-12-18 15:04:48 +0000362 // If the symbol's section is null, it will be considered absolute (SHN_ABS).
363 // (we use this in JIT to reference code which is stored outside the debug ELF file)
Vladimir Marko944da602016-02-19 12:27:55 +0000364 void Add(Elf_Word name,
365 const Section* section,
366 Elf_Addr addr,
Vladimir Marko944da602016-02-19 12:27:55 +0000367 Elf_Word size,
368 uint8_t binding,
David Srbecky197160d2016-03-07 17:33:57 +0000369 uint8_t type) {
370 Elf_Word section_index;
371 if (section != nullptr) {
372 DCHECK_LE(section->GetAddress(), addr);
373 DCHECK_LE(addr, section->GetAddress() + section->GetSize());
374 section_index = section->GetSectionIndex();
375 } else {
376 section_index = static_cast<Elf_Word>(SHN_ABS);
377 }
378 Add(name, section_index, addr, size, binding, type);
Vladimir Marko944da602016-02-19 12:27:55 +0000379 }
380
381 void Add(Elf_Word name,
382 Elf_Word section_index,
383 Elf_Addr addr,
384 Elf_Word size,
385 uint8_t binding,
David Srbecky197160d2016-03-07 17:33:57 +0000386 uint8_t type) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000387 Elf_Sym sym = Elf_Sym();
388 sym.st_name = name;
Vladimir Marko944da602016-02-19 12:27:55 +0000389 sym.st_value = addr;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000390 sym.st_size = size;
David Srbecky197160d2016-03-07 17:33:57 +0000391 sym.st_other = 0;
Vladimir Marko944da602016-02-19 12:27:55 +0000392 sym.st_shndx = section_index;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000393 sym.st_info = (binding << 4) + (type & 0xf);
Vladimir Marko944da602016-02-19 12:27:55 +0000394 CachedSection::Add(&sym, sizeof(sym));
David Srbecky0c5bbc12015-04-28 17:54:52 +0100395 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100396 };
397
Douglas Leung316a2182015-09-17 15:26:25 -0700398 class AbiflagsSection FINAL : public Section {
399 public:
400 // Section with Mips abiflag info.
401 static constexpr uint8_t MIPS_AFL_REG_NONE = 0; // no registers
402 static constexpr uint8_t MIPS_AFL_REG_32 = 1; // 32-bit registers
403 static constexpr uint8_t MIPS_AFL_REG_64 = 2; // 64-bit registers
404 static constexpr uint32_t MIPS_AFL_FLAGS1_ODDSPREG = 1; // Uses odd single-prec fp regs
405 static constexpr uint8_t MIPS_ABI_FP_DOUBLE = 1; // -mdouble-float
406 static constexpr uint8_t MIPS_ABI_FP_XX = 5; // -mfpxx
407 static constexpr uint8_t MIPS_ABI_FP_64A = 7; // -mips32r* -mfp64 -mno-odd-spreg
408
409 AbiflagsSection(ElfBuilder<ElfTypes>* owner,
410 const std::string& name,
411 Elf_Word type,
412 Elf_Word flags,
413 const Section* link,
414 Elf_Word info,
415 Elf_Word align,
416 Elf_Word entsize,
417 InstructionSet isa,
418 const InstructionSetFeatures* features)
419 : Section(owner, name, type, flags, link, info, align, entsize) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000420 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700421 bool fpu32 = false; // assume mips64 values
422 uint8_t isa_rev = 6; // assume mips64 values
Vladimir Marko33bff252017-11-01 14:35:42 +0000423 if (isa == InstructionSet::kMips) {
Douglas Leung316a2182015-09-17 15:26:25 -0700424 // adjust for mips32 values
425 fpu32 = features->AsMipsInstructionSetFeatures()->Is32BitFloatingPoint();
426 isa_rev = features->AsMipsInstructionSetFeatures()->IsR6()
427 ? 6
428 : features->AsMipsInstructionSetFeatures()->IsMipsIsaRevGreaterThanEqual2()
429 ? (fpu32 ? 2 : 5)
430 : 1;
431 }
432 abiflags_.version = 0; // version of flags structure
Vladimir Marko33bff252017-11-01 14:35:42 +0000433 abiflags_.isa_level = (isa == InstructionSet::kMips) ? 32 : 64;
Douglas Leung316a2182015-09-17 15:26:25 -0700434 abiflags_.isa_rev = isa_rev;
Vladimir Marko33bff252017-11-01 14:35:42 +0000435 abiflags_.gpr_size = (isa == InstructionSet::kMips) ? MIPS_AFL_REG_32 : MIPS_AFL_REG_64;
Douglas Leung316a2182015-09-17 15:26:25 -0700436 abiflags_.cpr1_size = fpu32 ? MIPS_AFL_REG_32 : MIPS_AFL_REG_64;
437 abiflags_.cpr2_size = MIPS_AFL_REG_NONE;
438 // Set the fp_abi to MIPS_ABI_FP_64A for mips32 with 64-bit FPUs (ie: mips32 R5 and R6).
439 // Otherwise set to MIPS_ABI_FP_DOUBLE.
Vladimir Marko33bff252017-11-01 14:35:42 +0000440 abiflags_.fp_abi =
441 (isa == InstructionSet::kMips && !fpu32) ? MIPS_ABI_FP_64A : MIPS_ABI_FP_DOUBLE;
Douglas Leung316a2182015-09-17 15:26:25 -0700442 abiflags_.isa_ext = 0;
443 abiflags_.ases = 0;
444 // To keep the code simple, we are not using odd FP reg for single floats for both
445 // mips32 and mips64 ART. Therefore we are not setting the MIPS_AFL_FLAGS1_ODDSPREG bit.
446 abiflags_.flags1 = 0;
447 abiflags_.flags2 = 0;
448 }
449 }
450
451 Elf_Word GetSize() const {
452 return sizeof(abiflags_);
453 }
454
455 void Write() {
456 this->WriteFully(&abiflags_, sizeof(abiflags_));
457 }
458
459 private:
460 struct {
461 uint16_t version; // version of this structure
462 uint8_t isa_level, isa_rev, gpr_size, cpr1_size, cpr2_size;
463 uint8_t fp_abi;
464 uint32_t isa_ext, ases, flags1, flags2;
465 } abiflags_;
466 };
467
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700468 class BuildIdSection FINAL : public Section {
469 public:
470 BuildIdSection(ElfBuilder<ElfTypes>* owner,
471 const std::string& name,
472 Elf_Word type,
473 Elf_Word flags,
474 const Section* link,
475 Elf_Word info,
476 Elf_Word align,
477 Elf_Word entsize)
478 : Section(owner, name, type, flags, link, info, align, entsize),
479 digest_start_(-1) {
480 }
481
482 void Write() {
483 // The size fields are 32-bit on both 32-bit and 64-bit systems, confirmed
484 // with the 64-bit linker and libbfd code. The size of name and desc must
485 // be a multiple of 4 and it currently is.
486 this->WriteUint32(4); // namesz.
487 this->WriteUint32(kBuildIdLen); // descsz.
488 this->WriteUint32(3); // type = NT_GNU_BUILD_ID.
489 this->WriteFully("GNU", 4); // name.
490 digest_start_ = this->Seek(0, kSeekCurrent);
491 static_assert(kBuildIdLen % 4 == 0, "expecting a mutliple of 4 for build ID length");
492 this->WriteFully(std::string(kBuildIdLen, '\0').c_str(), kBuildIdLen); // desc.
493 }
494
495 off_t GetDigestStart() {
496 CHECK_GT(digest_start_, 0);
497 return digest_start_;
498 }
499
500 private:
501 bool WriteUint32(uint32_t v) {
502 return this->WriteFully(&v, sizeof(v));
503 }
504
505 // File offset where the build ID digest starts.
506 // Populated with zeros first, then updated with the actual value as the
507 // very last thing in the output file creation.
508 off_t digest_start_;
509 };
510
David Srbecky5d811202016-03-08 13:21:22 +0000511 ElfBuilder(InstructionSet isa, const InstructionSetFeatures* features, OutputStream* output)
Vladimir Marko131980f2015-12-03 18:29:23 +0000512 : isa_(isa),
David Srbecky5d811202016-03-08 13:21:22 +0000513 features_(features),
Vladimir Marko131980f2015-12-03 18:29:23 +0000514 stream_(output),
515 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
516 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
517 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
518 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
519 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
520 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
521 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
522 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
523 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
David Srbecky579942f2016-01-28 20:01:28 +0000524 strtab_(this, ".strtab", 0, 1),
Vladimir Marko131980f2015-12-03 18:29:23 +0000525 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
526 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
527 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
528 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
529 shstrtab_(this, ".shstrtab", 0, 1),
Douglas Leung316a2182015-09-17 15:26:25 -0700530 abiflags_(this, ".MIPS.abiflags", SHT_MIPS_ABIFLAGS, SHF_ALLOC, nullptr, 0, kPageSize, 0,
531 isa, features),
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700532 build_id_(this, ".note.gnu.build-id", SHT_NOTE, SHF_ALLOC, nullptr, 0, 4, 0),
David Srbecky579942f2016-01-28 20:01:28 +0000533 started_(false),
Vladimir Marko944da602016-02-19 12:27:55 +0000534 write_program_headers_(false),
535 loaded_size_(0u),
Vladimir Marko131980f2015-12-03 18:29:23 +0000536 virtual_address_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000537 text_.phdr_flags_ = PF_R | PF_X;
538 bss_.phdr_flags_ = PF_R | PF_W;
539 dynamic_.phdr_flags_ = PF_R | PF_W;
540 dynamic_.phdr_type_ = PT_DYNAMIC;
541 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Douglas Leung316a2182015-09-17 15:26:25 -0700542 abiflags_.phdr_type_ = PT_MIPS_ABIFLAGS;
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700543 build_id_.phdr_type_ = PT_NOTE;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700544 }
545 ~ElfBuilder() {}
546
David Srbecky6d8c8f02015-10-26 10:57:09 +0000547 InstructionSet GetIsa() { return isa_; }
548 Section* GetRoData() { return &rodata_; }
549 Section* GetText() { return &text_; }
550 Section* GetBss() { return &bss_; }
551 StringSection* GetStrTab() { return &strtab_; }
552 SymbolSection* GetSymTab() { return &symtab_; }
553 Section* GetEhFrame() { return &eh_frame_; }
554 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
555 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000556 Section* GetDebugInfo() { return &debug_info_; }
557 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700558
David Srbecky6d8c8f02015-10-26 10:57:09 +0000559 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
560 // (exposed publicly for tests)
Vladimir Marko10c13562015-11-25 14:33:36 +0000561 static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000562 std::vector<uint8_t>* buffer) {
563 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
564 uintptr_t address = 0; // relative to start of section.
565 for (uintptr_t location : locations) {
566 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
567 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
568 address = location;
569 }
570 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700571
Vladimir Marko10c13562015-11-25 14:33:36 +0000572 void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000573 std::vector<uint8_t> buffer;
Vladimir Marko10c13562015-11-25 14:33:36 +0000574 EncodeOatPatches(patch_locations, &buffer);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000575 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
576 s->Start();
577 s->WriteFully(buffer.data(), buffer.size());
578 s->End();
579 other_sections_.push_back(std::move(s));
580 }
David Srbecky527c9c72015-04-17 21:14:10 +0100581
David Srbecky6d8c8f02015-10-26 10:57:09 +0000582 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
583 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
584 s->Start();
585 s->WriteFully(buffer->data(), buffer->size());
586 s->End();
587 other_sections_.push_back(std::move(s));
588 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700589
David Srbecky579942f2016-01-28 20:01:28 +0000590 // Reserve space for ELF header and program headers.
591 // We do not know the number of headers until later, so
592 // it is easiest to just reserve a fixed amount of space.
593 // Program headers are required for loading by the linker.
594 // It is possible to omit them for ELF files used for debugging.
595 void Start(bool write_program_headers = true) {
596 int size = sizeof(Elf_Ehdr);
597 if (write_program_headers) {
598 size += sizeof(Elf_Phdr) * kMaxProgramHeaders;
599 }
Vladimir Marko131980f2015-12-03 18:29:23 +0000600 stream_.Seek(size, kSeekSet);
David Srbecky579942f2016-01-28 20:01:28 +0000601 started_ = true;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000602 virtual_address_ += size;
David Srbecky579942f2016-01-28 20:01:28 +0000603 write_program_headers_ = write_program_headers;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000604 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700605
David Srbecky6d8c8f02015-10-26 10:57:09 +0000606 void End() {
David Srbecky579942f2016-01-28 20:01:28 +0000607 DCHECK(started_);
608
Vladimir Marko944da602016-02-19 12:27:55 +0000609 // Note: loaded_size_ == 0 for tests that don't write .rodata, .text, .bss,
610 // .dynstr, dynsym, .hash and .dynamic. These tests should not read loaded_size_.
611 // TODO: Either refactor the .eh_frame creation so that it counts towards loaded_size_,
612 // or remove all support for .eh_frame. (The currently unused .eh_frame counts towards
613 // the virtual_address_ but we don't consider it for loaded_size_.)
614 CHECK(loaded_size_ == 0 || loaded_size_ == RoundUp(virtual_address_, kPageSize))
615 << loaded_size_ << " " << virtual_address_;
616
David Srbecky6d8c8f02015-10-26 10:57:09 +0000617 // Write section names and finish the section headers.
618 shstrtab_.Start();
619 shstrtab_.Write("");
620 for (auto* section : sections_) {
621 section->header_.sh_name = shstrtab_.Write(section->name_);
622 if (section->link_ != nullptr) {
623 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100624 }
David Srbecky527c9c72015-04-17 21:14:10 +0100625 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000626 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100627
David Srbecky6d8c8f02015-10-26 10:57:09 +0000628 // Write section headers at the end of the ELF file.
629 std::vector<Elf_Shdr> shdrs;
630 shdrs.reserve(1u + sections_.size());
631 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
632 for (auto* section : sections_) {
633 shdrs.push_back(section->header_);
634 }
635 Elf_Off section_headers_offset;
David Srbecky579942f2016-01-28 20:01:28 +0000636 section_headers_offset = AlignFileOffset(sizeof(Elf_Off));
Vladimir Marko131980f2015-12-03 18:29:23 +0000637 stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
638
639 // Flush everything else before writing the program headers. This should prevent
640 // the OS from reordering writes, so that we don't end up with valid headers
641 // and partially written data if we suddenly lose power, for example.
642 stream_.Flush();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000643
David Srbecky579942f2016-01-28 20:01:28 +0000644 // The main ELF header.
Douglas Leung316a2182015-09-17 15:26:25 -0700645 Elf_Ehdr elf_header = MakeElfHeader(isa_, features_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100646 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000647 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100648 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
David Srbecky579942f2016-01-28 20:01:28 +0000649
650 // Program headers (i.e. mmap instructions).
651 std::vector<Elf_Phdr> phdrs;
652 if (write_program_headers_) {
653 phdrs = MakeProgramHeaders();
654 CHECK_LE(phdrs.size(), kMaxProgramHeaders);
655 elf_header.e_phoff = sizeof(Elf_Ehdr);
656 elf_header.e_phnum = phdrs.size();
657 }
658
Vladimir Marko131980f2015-12-03 18:29:23 +0000659 stream_.Seek(0, kSeekSet);
660 stream_.WriteFully(&elf_header, sizeof(elf_header));
661 stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
662 stream_.Flush();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700663 }
664
David Srbecky6d8c8f02015-10-26 10:57:09 +0000665 // The running program does not have access to section headers
666 // and the loader is not supposed to use them either.
667 // The dynamic sections therefore replicates some of the layout
668 // information like the address and size of .rodata and .text.
669 // It also contains other metadata like the SONAME.
670 // The .dynamic section is found using the PT_DYNAMIC program header.
Vladimir Marko944da602016-02-19 12:27:55 +0000671 void PrepareDynamicSection(const std::string& elf_file_path,
672 Elf_Word rodata_size,
673 Elf_Word text_size,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000674 Elf_Word bss_size,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100675 Elf_Word bss_methods_offset,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000676 Elf_Word bss_roots_offset) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000677 std::string soname(elf_file_path);
678 size_t directory_separator_pos = soname.rfind('/');
679 if (directory_separator_pos != std::string::npos) {
680 soname = soname.substr(directory_separator_pos + 1);
681 }
682
Vladimir Marko944da602016-02-19 12:27:55 +0000683 // Calculate addresses of .text, .bss and .dynstr.
684 DCHECK_EQ(rodata_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
685 DCHECK_EQ(text_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
686 DCHECK_EQ(bss_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
687 DCHECK_EQ(dynstr_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
688 Elf_Word rodata_address = rodata_.GetAddress();
689 Elf_Word text_address = RoundUp(rodata_address + rodata_size, kPageSize);
690 Elf_Word bss_address = RoundUp(text_address + text_size, kPageSize);
Douglas Leung316a2182015-09-17 15:26:25 -0700691 Elf_Word abiflags_address = RoundUp(bss_address + bss_size, kPageSize);
692 Elf_Word abiflags_size = 0;
Vladimir Marko33bff252017-11-01 14:35:42 +0000693 if (isa_ == InstructionSet::kMips || isa_ == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700694 abiflags_size = abiflags_.GetSize();
695 }
696 Elf_Word dynstr_address = RoundUp(abiflags_address + abiflags_size, kPageSize);
Vladimir Marko45724f92016-02-17 17:46:10 +0000697
Vladimir Marko944da602016-02-19 12:27:55 +0000698 // Cache .dynstr, .dynsym and .hash data.
699 dynstr_.Add(""); // dynstr should start with empty string.
700 Elf_Word rodata_index = rodata_.GetSectionIndex();
701 Elf_Word oatdata = dynstr_.Add("oatdata");
702 dynsym_.Add(oatdata, rodata_index, rodata_address, rodata_size, STB_GLOBAL, STT_OBJECT);
703 if (text_size != 0u) {
704 Elf_Word text_index = rodata_index + 1u;
705 Elf_Word oatexec = dynstr_.Add("oatexec");
706 dynsym_.Add(oatexec, text_index, text_address, text_size, STB_GLOBAL, STT_OBJECT);
707 Elf_Word oatlastword = dynstr_.Add("oatlastword");
708 Elf_Word oatlastword_address = text_address + text_size - 4;
709 dynsym_.Add(oatlastword, text_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
710 } else if (rodata_size != 0) {
711 // rodata_ can be size 0 for dwarf_test.
712 Elf_Word oatlastword = dynstr_.Add("oatlastword");
713 Elf_Word oatlastword_address = rodata_address + rodata_size - 4;
714 dynsym_.Add(oatlastword, rodata_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
715 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000716 DCHECK_LE(bss_roots_offset, bss_size);
Vladimir Marko944da602016-02-19 12:27:55 +0000717 if (bss_size != 0u) {
718 Elf_Word bss_index = rodata_index + 1u + (text_size != 0 ? 1u : 0u);
719 Elf_Word oatbss = dynstr_.Add("oatbss");
Vladimir Markoaad75c62016-10-03 08:46:48 +0000720 dynsym_.Add(oatbss, bss_index, bss_address, bss_roots_offset, STB_GLOBAL, STT_OBJECT);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100721 DCHECK_LE(bss_methods_offset, bss_roots_offset);
722 DCHECK_LE(bss_roots_offset, bss_size);
723 // Add a symbol marking the start of the methods part of the .bss, if not empty.
724 if (bss_methods_offset != bss_roots_offset) {
725 Elf_Word bss_methods_address = bss_address + bss_methods_offset;
726 Elf_Word bss_methods_size = bss_roots_offset - bss_methods_offset;
727 Elf_Word oatbssroots = dynstr_.Add("oatbssmethods");
728 dynsym_.Add(
729 oatbssroots, bss_index, bss_methods_address, bss_methods_size, STB_GLOBAL, STT_OBJECT);
730 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000731 // Add a symbol marking the start of the GC roots part of the .bss, if not empty.
732 if (bss_roots_offset != bss_size) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000733 Elf_Word bss_roots_address = bss_address + bss_roots_offset;
734 Elf_Word bss_roots_size = bss_size - bss_roots_offset;
735 Elf_Word oatbssroots = dynstr_.Add("oatbssroots");
736 dynsym_.Add(
737 oatbssroots, bss_index, bss_roots_address, bss_roots_size, STB_GLOBAL, STT_OBJECT);
738 }
Vladimir Marko944da602016-02-19 12:27:55 +0000739 Elf_Word oatbsslastword = dynstr_.Add("oatbsslastword");
740 Elf_Word bsslastword_address = bss_address + bss_size - 4;
741 dynsym_.Add(oatbsslastword, bss_index, bsslastword_address, 4, STB_GLOBAL, STT_OBJECT);
742 }
743 Elf_Word soname_offset = dynstr_.Add(soname);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000744
745 // We do not really need a hash-table since there is so few entries.
746 // However, the hash-table is the only way the linker can actually
747 // determine the number of symbols in .dynsym so it is required.
Vladimir Marko944da602016-02-19 12:27:55 +0000748 int count = dynsym_.GetCacheSize() / sizeof(Elf_Sym); // Includes NULL.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000749 std::vector<Elf_Word> hash;
750 hash.push_back(1); // Number of buckets.
751 hash.push_back(count); // Number of chains.
752 // Buckets. Having just one makes it linear search.
753 hash.push_back(1); // Point to first non-NULL symbol.
754 // Chains. This creates linked list of symbols.
755 hash.push_back(0); // Dummy entry for the NULL symbol.
756 for (int i = 1; i < count - 1; i++) {
757 hash.push_back(i + 1); // Each symbol points to the next one.
758 }
759 hash.push_back(0); // Last symbol terminates the chain.
Vladimir Marko944da602016-02-19 12:27:55 +0000760 hash_.Add(hash.data(), hash.size() * sizeof(hash[0]));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000761
Vladimir Marko944da602016-02-19 12:27:55 +0000762 // Calculate addresses of .dynsym, .hash and .dynamic.
763 DCHECK_EQ(dynstr_.header_.sh_flags, dynsym_.header_.sh_flags);
764 DCHECK_EQ(dynsym_.header_.sh_flags, hash_.header_.sh_flags);
765 Elf_Word dynsym_address =
766 RoundUp(dynstr_address + dynstr_.GetCacheSize(), dynsym_.header_.sh_addralign);
767 Elf_Word hash_address =
768 RoundUp(dynsym_address + dynsym_.GetCacheSize(), hash_.header_.sh_addralign);
769 DCHECK_EQ(dynamic_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
770 Elf_Word dynamic_address = RoundUp(hash_address + dynsym_.GetCacheSize(), kPageSize);
771
David Srbecky6d8c8f02015-10-26 10:57:09 +0000772 Elf_Dyn dyns[] = {
Vladimir Marko944da602016-02-19 12:27:55 +0000773 { DT_HASH, { hash_address } },
774 { DT_STRTAB, { dynstr_address } },
775 { DT_SYMTAB, { dynsym_address } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000776 { DT_SYMENT, { sizeof(Elf_Sym) } },
Vladimir Marko944da602016-02-19 12:27:55 +0000777 { DT_STRSZ, { dynstr_.GetCacheSize() } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000778 { DT_SONAME, { soname_offset } },
779 { DT_NULL, { 0 } },
780 };
Vladimir Marko944da602016-02-19 12:27:55 +0000781 dynamic_.Add(&dyns, sizeof(dyns));
782
783 loaded_size_ = RoundUp(dynamic_address + dynamic_.GetCacheSize(), kPageSize);
784 }
785
786 void WriteDynamicSection() {
787 dynstr_.WriteCachedSection();
788 dynsym_.WriteCachedSection();
789 hash_.WriteCachedSection();
790 dynamic_.WriteCachedSection();
791
792 CHECK_EQ(loaded_size_, RoundUp(dynamic_.GetAddress() + dynamic_.GetSize(), kPageSize));
793 }
794
795 Elf_Word GetLoadedSize() {
796 CHECK_NE(loaded_size_, 0u);
797 return loaded_size_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700798 }
799
Douglas Leung316a2182015-09-17 15:26:25 -0700800 void WriteMIPSabiflagsSection() {
801 abiflags_.Start();
802 abiflags_.Write();
803 abiflags_.End();
804 }
805
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700806 void WriteBuildIdSection() {
807 build_id_.Start();
808 build_id_.Write();
809 build_id_.End();
810 }
811
812 void WriteBuildId(uint8_t build_id[kBuildIdLen]) {
813 stream_.Seek(build_id_.GetDigestStart(), kSeekSet);
814 stream_.WriteFully(build_id, kBuildIdLen);
815 }
816
David Srbecky6d8c8f02015-10-26 10:57:09 +0000817 // Returns true if all writes and seeks on the output stream succeeded.
818 bool Good() {
Vladimir Marko131980f2015-12-03 18:29:23 +0000819 return stream_.Good();
820 }
821
822 // Returns the builder's internal stream.
823 OutputStream* GetStream() {
824 return &stream_;
David Srbecky527c9c72015-04-17 21:14:10 +0100825 }
826
David Srbecky579942f2016-01-28 20:01:28 +0000827 off_t AlignFileOffset(size_t alignment) {
828 return stream_.Seek(RoundUp(stream_.Seek(0, kSeekCurrent), alignment), kSeekSet);
829 }
830
831 Elf_Addr AlignVirtualAddress(size_t alignment) {
832 return virtual_address_ = RoundUp(virtual_address_, alignment);
833 }
834
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700835 private:
Douglas Leung316a2182015-09-17 15:26:25 -0700836 static Elf_Ehdr MakeElfHeader(InstructionSet isa, const InstructionSetFeatures* features) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100837 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700838 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000839 case InstructionSet::kArm:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700840 // Fall through.
Vladimir Marko33bff252017-11-01 14:35:42 +0000841 case InstructionSet::kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100842 elf_header.e_machine = EM_ARM;
843 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700844 break;
845 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000846 case InstructionSet::kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100847 elf_header.e_machine = EM_AARCH64;
848 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700849 break;
850 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000851 case InstructionSet::kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100852 elf_header.e_machine = EM_386;
853 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700854 break;
855 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000856 case InstructionSet::kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100857 elf_header.e_machine = EM_X86_64;
858 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700859 break;
860 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000861 case InstructionSet::kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100862 elf_header.e_machine = EM_MIPS;
863 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700864 EF_MIPS_PIC |
865 EF_MIPS_CPIC |
866 EF_MIPS_ABI_O32 |
Greg Kaiser81a18992016-06-16 15:55:15 -0700867 (features->AsMipsInstructionSetFeatures()->IsR6()
868 ? EF_MIPS_ARCH_32R6
869 : EF_MIPS_ARCH_32R2));
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700870 break;
871 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000872 case InstructionSet::kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100873 elf_header.e_machine = EM_MIPS;
874 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700875 EF_MIPS_PIC |
876 EF_MIPS_CPIC |
877 EF_MIPS_ARCH_64R6);
Andreas Gampe57b34292015-01-14 15:45:59 -0800878 break;
879 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000880 case InstructionSet::kNone: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100881 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000882 break;
883 }
884 default: {
885 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700886 }
887 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700888
David Srbeckybc90fd02015-04-22 19:40:27 +0100889 elf_header.e_ident[EI_MAG0] = ELFMAG0;
890 elf_header.e_ident[EI_MAG1] = ELFMAG1;
891 elf_header.e_ident[EI_MAG2] = ELFMAG2;
892 elf_header.e_ident[EI_MAG3] = ELFMAG3;
893 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Mathieu Chartier6beced42016-11-15 15:51:31 -0800894 ? ELFCLASS32 : ELFCLASS64;
David Srbeckybc90fd02015-04-22 19:40:27 +0100895 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
896 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
897 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
898 elf_header.e_ident[EI_ABIVERSION] = 0;
899 elf_header.e_type = ET_DYN;
900 elf_header.e_version = 1;
901 elf_header.e_entry = 0;
902 elf_header.e_ehsize = sizeof(Elf_Ehdr);
903 elf_header.e_phentsize = sizeof(Elf_Phdr);
904 elf_header.e_shentsize = sizeof(Elf_Shdr);
905 elf_header.e_phoff = sizeof(Elf_Ehdr);
906 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700907 }
908
David Srbecky6d8c8f02015-10-26 10:57:09 +0000909 // Create program headers based on written sections.
910 std::vector<Elf_Phdr> MakeProgramHeaders() {
911 CHECK(!sections_.empty());
912 std::vector<Elf_Phdr> phdrs;
913 {
914 // The program headers must start with PT_PHDR which is used in
915 // loaded process to determine the number of program headers.
916 Elf_Phdr phdr = Elf_Phdr();
917 phdr.p_type = PT_PHDR;
918 phdr.p_flags = PF_R;
919 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
920 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
921 phdr.p_align = sizeof(Elf_Off);
922 phdrs.push_back(phdr);
923 // Tell the linker to mmap the start of file to memory.
924 Elf_Phdr load = Elf_Phdr();
925 load.p_type = PT_LOAD;
926 load.p_flags = PF_R;
927 load.p_offset = load.p_vaddr = load.p_paddr = 0;
David Srbecky2fdd03c2016-03-10 15:32:37 +0000928 load.p_filesz = load.p_memsz = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000929 load.p_align = kPageSize;
930 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100931 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000932 // Create program headers for sections.
933 for (auto* section : sections_) {
934 const Elf_Shdr& shdr = section->header_;
935 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
936 // PT_LOAD tells the linker to mmap part of the file.
937 // The linker can only mmap page-aligned sections.
938 // Single PT_LOAD may contain several ELF sections.
939 Elf_Phdr& prev = phdrs.back();
940 Elf_Phdr load = Elf_Phdr();
941 load.p_type = PT_LOAD;
942 load.p_flags = section->phdr_flags_;
943 load.p_offset = shdr.sh_offset;
944 load.p_vaddr = load.p_paddr = shdr.sh_addr;
945 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
946 load.p_memsz = shdr.sh_size;
947 load.p_align = shdr.sh_addralign;
948 if (prev.p_type == load.p_type &&
949 prev.p_flags == load.p_flags &&
950 prev.p_filesz == prev.p_memsz && // Do not merge .bss
951 load.p_filesz == load.p_memsz) { // Do not merge .bss
952 // Merge this PT_LOAD with the previous one.
953 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
954 prev.p_filesz = size;
955 prev.p_memsz = size;
956 } else {
957 // If we are adding new load, it must be aligned.
958 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
959 phdrs.push_back(load);
960 }
961 }
962 }
963 for (auto* section : sections_) {
964 const Elf_Shdr& shdr = section->header_;
965 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
966 // Other PT_* types allow the program to locate interesting
967 // parts of memory at runtime. They must overlap with PT_LOAD.
968 if (section->phdr_type_ != 0) {
969 Elf_Phdr phdr = Elf_Phdr();
970 phdr.p_type = section->phdr_type_;
971 phdr.p_flags = section->phdr_flags_;
972 phdr.p_offset = shdr.sh_offset;
973 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
974 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
975 phdr.p_align = shdr.sh_addralign;
976 phdrs.push_back(phdr);
977 }
978 }
979 }
980 // Set the size of the initial PT_PHDR.
981 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
982 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100983
David Srbecky6d8c8f02015-10-26 10:57:09 +0000984 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700985 }
986
David Srbeckybc90fd02015-04-22 19:40:27 +0100987 InstructionSet isa_;
David Srbecky5d811202016-03-08 13:21:22 +0000988 const InstructionSetFeatures* features_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000989
Vladimir Marko131980f2015-12-03 18:29:23 +0000990 ErrorDelayingOutputStream stream_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000991
992 Section rodata_;
993 Section text_;
994 Section bss_;
Vladimir Marko944da602016-02-19 12:27:55 +0000995 CachedStringSection dynstr_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000996 SymbolSection dynsym_;
Vladimir Marko944da602016-02-19 12:27:55 +0000997 CachedSection hash_;
998 CachedSection dynamic_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000999 Section eh_frame_;
1000 Section eh_frame_hdr_;
1001 StringSection strtab_;
1002 SymbolSection symtab_;
1003 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +00001004 Section debug_info_;
1005 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001006 StringSection shstrtab_;
Douglas Leung316a2182015-09-17 15:26:25 -07001007 AbiflagsSection abiflags_;
Alexey Alexandrovab40c112016-09-19 09:33:49 -07001008 BuildIdSection build_id_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001009 std::vector<std::unique_ptr<Section>> other_sections_;
1010
1011 // List of used section in the order in which they were written.
1012 std::vector<Section*> sections_;
1013
David Srbecky579942f2016-01-28 20:01:28 +00001014 bool started_;
Vladimir Marko944da602016-02-19 12:27:55 +00001015 bool write_program_headers_;
1016
1017 // The size of the memory taken by the ELF file when loaded.
1018 size_t loaded_size_;
David Srbecky579942f2016-01-28 20:01:28 +00001019
David Srbecky6d8c8f02015-10-26 10:57:09 +00001020 // Used for allocation of virtual address space.
1021 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -07001022
1023 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001024};
1025
Vladimir Marko74527972016-11-29 15:57:32 +00001026} // namespace linker
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001027} // namespace art
1028
Vladimir Marko74527972016-11-29 15:57:32 +00001029#endif // ART_COMPILER_LINKER_ELF_BUILDER_H_