blob: 3d24d1991994f8d5dc8f5bd11d20ccffafc2934b [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"
Vladimir Marko80afd022015-05-19 18:08:00 +010023#include "base/bit_utils.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000024#include "base/casts.h"
David Srbeckybc90fd02015-04-22 19:40:27 +010025#include "base/unix_file/fd_file.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070026#include "elf_utils.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000027#include "leb128.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000028#include "linker/error_delaying_output_stream.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000029#include "utils/array_ref.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070030
31namespace art {
32
David Srbeckybc90fd02015-04-22 19:40:27 +010033// Writes ELF file.
David Srbecky6d8c8f02015-10-26 10:57:09 +000034//
35// The basic layout of the elf file:
36// Elf_Ehdr - The ELF header.
37// Elf_Phdr[] - Program headers for the linker.
38// .rodata - DEX files and oat metadata.
39// .text - Compiled code.
40// .bss - Zero-initialized writeable section.
41// .dynstr - Names for .dynsym.
42// .dynsym - A few oat-specific dynamic symbols.
43// .hash - Hash-table for .dynsym.
44// .dynamic - Tags which let the linker locate .dynsym.
45// .strtab - Names for .symtab.
46// .symtab - Debug symbols.
47// .eh_frame - Unwind information (CFI).
48// .eh_frame_hdr - Index of .eh_frame.
49// .debug_frame - Unwind information (CFI).
50// .debug_frame.oat_patches - Addresses for relocation.
51// .debug_info - Debug information.
52// .debug_info.oat_patches - Addresses for relocation.
53// .debug_abbrev - Decoding information for .debug_info.
54// .debug_str - Strings for .debug_info.
55// .debug_line - Line number tables.
56// .debug_line.oat_patches - Addresses for relocation.
57// .text.oat_patches - Addresses for relocation.
58// .shstrtab - Names of ELF sections.
59// Elf_Shdr[] - Section headers.
60//
61// Some section are optional (the debug sections in particular).
62//
63// We try write the section data directly into the file without much
64// in-memory buffering. This means we generally write sections based on the
65// dependency order (e.g. .dynamic points to .dynsym which points to .text).
66//
67// In the cases where we need to buffer, we write the larger section first
68// and buffer the smaller one (e.g. .strtab is bigger than .symtab).
69//
70// The debug sections are written last for easier stripping.
71//
David Srbecky533c2072015-04-22 12:20:22 +010072template <typename ElfTypes>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070073class ElfBuilder FINAL {
74 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000075 static constexpr size_t kMaxProgramHeaders = 16;
David Srbecky533c2072015-04-22 12:20:22 +010076 using Elf_Addr = typename ElfTypes::Addr;
David Srbeckybc90fd02015-04-22 19:40:27 +010077 using Elf_Off = typename ElfTypes::Off;
David Srbecky533c2072015-04-22 12:20:22 +010078 using Elf_Word = typename ElfTypes::Word;
79 using Elf_Sword = typename ElfTypes::Sword;
80 using Elf_Ehdr = typename ElfTypes::Ehdr;
81 using Elf_Shdr = typename ElfTypes::Shdr;
82 using Elf_Sym = typename ElfTypes::Sym;
83 using Elf_Phdr = typename ElfTypes::Phdr;
84 using Elf_Dyn = typename ElfTypes::Dyn;
85
David Srbeckybc90fd02015-04-22 19:40:27 +010086 // Base class of all sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +000087 class Section : public OutputStream {
David Srbecky0c5bbc12015-04-28 17:54:52 +010088 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000089 Section(ElfBuilder<ElfTypes>* owner, const std::string& name,
90 Elf_Word type, Elf_Word flags, const Section* link,
91 Elf_Word info, Elf_Word align, Elf_Word entsize)
92 : OutputStream(name), owner_(owner), header_(),
93 section_index_(0), name_(name), link_(link),
94 started_(false), finished_(false), phdr_flags_(PF_R), phdr_type_(0) {
95 DCHECK_GE(align, 1u);
David Srbecky491a7fe2015-05-28 00:59:08 +010096 header_.sh_type = type;
97 header_.sh_flags = flags;
98 header_.sh_info = info;
99 header_.sh_addralign = align;
100 header_.sh_entsize = entsize;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100101 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100102
David Srbecky6d8c8f02015-10-26 10:57:09 +0000103 // Start writing of this section.
104 void Start() {
105 CHECK(!started_);
106 CHECK(!finished_);
107 started_ = true;
108 auto& sections = owner_->sections_;
109 // Check that the previous section is complete.
110 CHECK(sections.empty() || sections.back()->finished_);
111 // The first ELF section index is 1. Index 0 is reserved for NULL.
112 section_index_ = sections.size() + 1;
113 // Push this section on the list of written sections.
114 sections.push_back(this);
115 // Align file position.
116 if (header_.sh_type != SHT_NOBITS) {
Vladimir Marko131980f2015-12-03 18:29:23 +0000117 header_.sh_offset = RoundUp(owner_->stream_.Seek(0, kSeekCurrent), header_.sh_addralign);
118 owner_->stream_.Seek(header_.sh_offset, kSeekSet);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000119 }
120 // Align virtual memory address.
121 if ((header_.sh_flags & SHF_ALLOC) != 0) {
122 header_.sh_addr = RoundUp(owner_->virtual_address_, header_.sh_addralign);
123 owner_->virtual_address_ = header_.sh_addr;
124 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100125 }
126
David Srbecky6d8c8f02015-10-26 10:57:09 +0000127 // Finish writing of this section.
128 void End() {
129 CHECK(started_);
130 CHECK(!finished_);
131 finished_ = true;
132 if (header_.sh_type == SHT_NOBITS) {
133 CHECK_GT(header_.sh_size, 0u);
134 } else {
135 // Use the current file position to determine section size.
Vladimir Marko131980f2015-12-03 18:29:23 +0000136 off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000137 CHECK_GE(file_offset, (off_t)header_.sh_offset);
138 header_.sh_size = file_offset - header_.sh_offset;
139 }
140 if ((header_.sh_flags & SHF_ALLOC) != 0) {
141 owner_->virtual_address_ += header_.sh_size;
142 }
143 }
144
David Srbecky5cc349f2015-12-18 15:04:48 +0000145 // Returns true if the section was written to disk.
146 // (Used to check whether we have .text when writing JIT debug info)
147 bool Exists() const {
148 return finished_;
149 }
150
David Srbecky6d8c8f02015-10-26 10:57:09 +0000151 // Get the location of this section in virtual memory.
152 Elf_Addr GetAddress() const {
153 CHECK(started_);
154 return header_.sh_addr;
155 }
156
157 // Returns the size of the content of this section.
158 Elf_Word GetSize() const {
David Srbeckyb851b492015-11-11 20:19:38 +0000159 if (finished_) {
160 return header_.sh_size;
161 } else {
162 CHECK(started_);
163 CHECK_NE(header_.sh_type, (Elf_Word)SHT_NOBITS);
Vladimir Marko131980f2015-12-03 18:29:23 +0000164 return owner_->stream_.Seek(0, kSeekCurrent) - header_.sh_offset;
David Srbeckyb851b492015-11-11 20:19:38 +0000165 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000166 }
167
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000168 // Write this section as "NOBITS" section. (used for the .bss section)
169 // This means that the ELF file does not contain the initial data for this section
170 // and it will be zero-initialized when the ELF file is loaded in the running program.
171 void WriteNoBitsSection(Elf_Word size) {
172 DCHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
173 Start();
174 header_.sh_type = SHT_NOBITS;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000175 header_.sh_size = size;
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000176 End();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000177 }
178
179 // This function always succeeds to simplify code.
180 // Use builder's Good() to check the actual status.
181 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
182 CHECK(started_);
183 CHECK(!finished_);
Vladimir Marko131980f2015-12-03 18:29:23 +0000184 return owner_->stream_.WriteFully(buffer, byte_count);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000185 }
186
187 // This function always succeeds to simplify code.
188 // Use builder's Good() to check the actual status.
189 off_t Seek(off_t offset, Whence whence) OVERRIDE {
190 // Forward the seek as-is and trust the caller to use it reasonably.
Vladimir Marko131980f2015-12-03 18:29:23 +0000191 return owner_->stream_.Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100192 }
193
Vladimir Marko10c13562015-11-25 14:33:36 +0000194 // This function flushes the output and returns whether it succeeded.
195 // If there was a previous failure, this does nothing and returns false, i.e. failed.
196 bool Flush() OVERRIDE {
Vladimir Marko131980f2015-12-03 18:29:23 +0000197 return owner_->stream_.Flush();
Vladimir Marko10c13562015-11-25 14:33:36 +0000198 }
199
David Srbecky0c5bbc12015-04-28 17:54:52 +0100200 Elf_Word GetSectionIndex() const {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000201 DCHECK(started_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100202 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100203 return section_index_;
204 }
205
David Srbecky0c5bbc12015-04-28 17:54:52 +0100206 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000207 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100208 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100209 Elf_Word section_index_;
210 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100211 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000212 bool started_;
213 bool finished_;
214 Elf_Word phdr_flags_;
215 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100216
David Srbecky6d8c8f02015-10-26 10:57:09 +0000217 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000218
219 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100220 };
221
David Srbeckybc90fd02015-04-22 19:40:27 +0100222 // Writer of .dynstr .strtab and .shstrtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000223 class StringSection FINAL : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100224 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000225 StringSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
226 Elf_Word flags, Elf_Word align)
227 : Section(owner, name, SHT_STRTAB, flags, nullptr, 0, align, 0),
228 current_offset_(0) {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100229 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100230
David Srbecky6d8c8f02015-10-26 10:57:09 +0000231 Elf_Word Write(const std::string& name) {
232 if (current_offset_ == 0) {
233 DCHECK(name.empty());
234 }
235 Elf_Word offset = current_offset_;
236 this->WriteFully(name.c_str(), name.length() + 1);
237 current_offset_ += name.length() + 1;
David Srbeckybc90fd02015-04-22 19:40:27 +0100238 return offset;
239 }
240
David Srbeckybc90fd02015-04-22 19:40:27 +0100241 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000242 Elf_Word current_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100243 };
244
David Srbeckybc90fd02015-04-22 19:40:27 +0100245 // Writer of .dynsym and .symtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000246 class SymbolSection FINAL : public Section {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100247 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000248 SymbolSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
249 Elf_Word type, Elf_Word flags, StringSection* strtab)
250 : Section(owner, name, type, flags, strtab, 0,
251 sizeof(Elf_Off), sizeof(Elf_Sym)) {
252 }
253
254 // Buffer symbol for this section. It will be written later.
David Srbecky5cc349f2015-12-18 15:04:48 +0000255 // If the symbol's section is null, it will be considered absolute (SHN_ABS).
256 // (we use this in JIT to reference code which is stored outside the debug ELF file)
David Srbecky6d8c8f02015-10-26 10:57:09 +0000257 void Add(Elf_Word name, const Section* section,
258 Elf_Addr addr, bool is_relative, Elf_Word size,
259 uint8_t binding, uint8_t type, uint8_t other = 0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000260 Elf_Sym sym = Elf_Sym();
261 sym.st_name = name;
262 sym.st_value = addr + (is_relative ? section->GetAddress() : 0);
263 sym.st_size = size;
264 sym.st_other = other;
David Srbecky5cc349f2015-12-18 15:04:48 +0000265 sym.st_shndx = (section != nullptr ? section->GetSectionIndex()
266 : static_cast<Elf_Word>(SHN_ABS));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000267 sym.st_info = (binding << 4) + (type & 0xf);
268 symbols_.push_back(sym);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100269 }
270
David Srbecky6d8c8f02015-10-26 10:57:09 +0000271 void Write() {
272 // The symbol table always has to start with NULL symbol.
273 Elf_Sym null_symbol = Elf_Sym();
274 this->WriteFully(&null_symbol, sizeof(null_symbol));
275 this->WriteFully(symbols_.data(), symbols_.size() * sizeof(symbols_[0]));
276 symbols_.clear();
277 symbols_.shrink_to_fit();
David Srbeckybc90fd02015-04-22 19:40:27 +0100278 }
279
280 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000281 std::vector<Elf_Sym> symbols_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100282 };
283
David Srbecky6d8c8f02015-10-26 10:57:09 +0000284 ElfBuilder(InstructionSet isa, OutputStream* output)
Vladimir Marko131980f2015-12-03 18:29:23 +0000285 : isa_(isa),
286 stream_(output),
287 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
288 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
289 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
290 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
291 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
292 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
293 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
294 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
295 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
296 strtab_(this, ".strtab", 0, kPageSize),
297 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
298 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
299 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
300 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
301 shstrtab_(this, ".shstrtab", 0, 1),
302 virtual_address_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000303 text_.phdr_flags_ = PF_R | PF_X;
304 bss_.phdr_flags_ = PF_R | PF_W;
305 dynamic_.phdr_flags_ = PF_R | PF_W;
306 dynamic_.phdr_type_ = PT_DYNAMIC;
307 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700308 }
309 ~ElfBuilder() {}
310
David Srbecky6d8c8f02015-10-26 10:57:09 +0000311 InstructionSet GetIsa() { return isa_; }
312 Section* GetRoData() { return &rodata_; }
313 Section* GetText() { return &text_; }
314 Section* GetBss() { return &bss_; }
315 StringSection* GetStrTab() { return &strtab_; }
316 SymbolSection* GetSymTab() { return &symtab_; }
317 Section* GetEhFrame() { return &eh_frame_; }
318 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
319 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000320 Section* GetDebugInfo() { return &debug_info_; }
321 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700322
David Srbecky6d8c8f02015-10-26 10:57:09 +0000323 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
324 // (exposed publicly for tests)
Vladimir Marko10c13562015-11-25 14:33:36 +0000325 static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000326 std::vector<uint8_t>* buffer) {
327 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
328 uintptr_t address = 0; // relative to start of section.
329 for (uintptr_t location : locations) {
330 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
331 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
332 address = location;
333 }
334 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700335
Vladimir Marko10c13562015-11-25 14:33:36 +0000336 void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000337 std::vector<uint8_t> buffer;
Vladimir Marko10c13562015-11-25 14:33:36 +0000338 EncodeOatPatches(patch_locations, &buffer);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000339 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
340 s->Start();
341 s->WriteFully(buffer.data(), buffer.size());
342 s->End();
343 other_sections_.push_back(std::move(s));
344 }
David Srbecky527c9c72015-04-17 21:14:10 +0100345
David Srbecky6d8c8f02015-10-26 10:57:09 +0000346 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
347 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
348 s->Start();
349 s->WriteFully(buffer->data(), buffer->size());
350 s->End();
351 other_sections_.push_back(std::move(s));
352 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700353
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000354 // Set where the next section will be allocated in the virtual address space.
355 void SetVirtualAddress(Elf_Addr address) {
356 DCHECK_GE(address, virtual_address_);
357 virtual_address_ = address;
358 }
359
David Srbecky6d8c8f02015-10-26 10:57:09 +0000360 void Start() {
361 // Reserve space for ELF header and program headers.
362 // We do not know the number of headers until later, so
363 // it is easiest to just reserve a fixed amount of space.
364 int size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
Vladimir Marko131980f2015-12-03 18:29:23 +0000365 stream_.Seek(size, kSeekSet);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000366 virtual_address_ += size;
367 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700368
David Srbecky6d8c8f02015-10-26 10:57:09 +0000369 void End() {
370 // Write section names and finish the section headers.
371 shstrtab_.Start();
372 shstrtab_.Write("");
373 for (auto* section : sections_) {
374 section->header_.sh_name = shstrtab_.Write(section->name_);
375 if (section->link_ != nullptr) {
376 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100377 }
David Srbecky527c9c72015-04-17 21:14:10 +0100378 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000379 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100380
David Srbecky6d8c8f02015-10-26 10:57:09 +0000381 // Write section headers at the end of the ELF file.
382 std::vector<Elf_Shdr> shdrs;
383 shdrs.reserve(1u + sections_.size());
384 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
385 for (auto* section : sections_) {
386 shdrs.push_back(section->header_);
387 }
388 Elf_Off section_headers_offset;
Vladimir Marko131980f2015-12-03 18:29:23 +0000389 section_headers_offset = RoundUp(stream_.Seek(0, kSeekCurrent), sizeof(Elf_Off));
390 stream_.Seek(section_headers_offset, kSeekSet);
391 stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
392
393 // Flush everything else before writing the program headers. This should prevent
394 // the OS from reordering writes, so that we don't end up with valid headers
395 // and partially written data if we suddenly lose power, for example.
396 stream_.Flush();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000397
398 // Write the initial file headers.
399 std::vector<Elf_Phdr> phdrs = MakeProgramHeaders();
David Srbeckybc90fd02015-04-22 19:40:27 +0100400 Elf_Ehdr elf_header = MakeElfHeader(isa_);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000401 elf_header.e_phoff = sizeof(Elf_Ehdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100402 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000403 elf_header.e_phnum = phdrs.size();
404 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100405 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
Vladimir Marko131980f2015-12-03 18:29:23 +0000406 stream_.Seek(0, kSeekSet);
407 stream_.WriteFully(&elf_header, sizeof(elf_header));
408 stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
409 stream_.Flush();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700410 }
411
David Srbecky6d8c8f02015-10-26 10:57:09 +0000412 // The running program does not have access to section headers
413 // and the loader is not supposed to use them either.
414 // The dynamic sections therefore replicates some of the layout
415 // information like the address and size of .rodata and .text.
416 // It also contains other metadata like the SONAME.
417 // The .dynamic section is found using the PT_DYNAMIC program header.
418 void WriteDynamicSection(const std::string& elf_file_path) {
419 std::string soname(elf_file_path);
420 size_t directory_separator_pos = soname.rfind('/');
421 if (directory_separator_pos != std::string::npos) {
422 soname = soname.substr(directory_separator_pos + 1);
423 }
424
425 dynstr_.Start();
426 dynstr_.Write(""); // dynstr should start with empty string.
427 dynsym_.Add(dynstr_.Write("oatdata"), &rodata_, 0, true,
428 rodata_.GetSize(), STB_GLOBAL, STT_OBJECT);
429 if (text_.GetSize() != 0u) {
430 dynsym_.Add(dynstr_.Write("oatexec"), &text_, 0, true,
431 text_.GetSize(), STB_GLOBAL, STT_OBJECT);
432 dynsym_.Add(dynstr_.Write("oatlastword"), &text_, text_.GetSize() - 4,
433 true, 4, STB_GLOBAL, STT_OBJECT);
434 } else if (rodata_.GetSize() != 0) {
435 // rodata_ can be size 0 for dwarf_test.
436 dynsym_.Add(dynstr_.Write("oatlastword"), &rodata_, rodata_.GetSize() - 4,
437 true, 4, STB_GLOBAL, STT_OBJECT);
438 }
439 if (bss_.finished_) {
440 dynsym_.Add(dynstr_.Write("oatbss"), &bss_,
441 0, true, bss_.GetSize(), STB_GLOBAL, STT_OBJECT);
442 dynsym_.Add(dynstr_.Write("oatbsslastword"), &bss_,
443 bss_.GetSize() - 4, true, 4, STB_GLOBAL, STT_OBJECT);
444 }
445 Elf_Word soname_offset = dynstr_.Write(soname);
446 dynstr_.End();
447
448 dynsym_.Start();
449 dynsym_.Write();
450 dynsym_.End();
451
452 // We do not really need a hash-table since there is so few entries.
453 // However, the hash-table is the only way the linker can actually
454 // determine the number of symbols in .dynsym so it is required.
455 hash_.Start();
456 int count = dynsym_.GetSize() / sizeof(Elf_Sym); // Includes NULL.
457 std::vector<Elf_Word> hash;
458 hash.push_back(1); // Number of buckets.
459 hash.push_back(count); // Number of chains.
460 // Buckets. Having just one makes it linear search.
461 hash.push_back(1); // Point to first non-NULL symbol.
462 // Chains. This creates linked list of symbols.
463 hash.push_back(0); // Dummy entry for the NULL symbol.
464 for (int i = 1; i < count - 1; i++) {
465 hash.push_back(i + 1); // Each symbol points to the next one.
466 }
467 hash.push_back(0); // Last symbol terminates the chain.
468 hash_.WriteFully(hash.data(), hash.size() * sizeof(hash[0]));
469 hash_.End();
470
471 dynamic_.Start();
472 Elf_Dyn dyns[] = {
473 { DT_HASH, { hash_.GetAddress() } },
474 { DT_STRTAB, { dynstr_.GetAddress() } },
475 { DT_SYMTAB, { dynsym_.GetAddress() } },
476 { DT_SYMENT, { sizeof(Elf_Sym) } },
477 { DT_STRSZ, { dynstr_.GetSize() } },
478 { DT_SONAME, { soname_offset } },
479 { DT_NULL, { 0 } },
480 };
481 dynamic_.WriteFully(&dyns, sizeof(dyns));
482 dynamic_.End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700483 }
484
David Srbecky6d8c8f02015-10-26 10:57:09 +0000485 // Returns true if all writes and seeks on the output stream succeeded.
486 bool Good() {
Vladimir Marko131980f2015-12-03 18:29:23 +0000487 return stream_.Good();
488 }
489
490 // Returns the builder's internal stream.
491 OutputStream* GetStream() {
492 return &stream_;
David Srbecky527c9c72015-04-17 21:14:10 +0100493 }
494
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700495 private:
David Srbeckybc90fd02015-04-22 19:40:27 +0100496 static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
497 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700498 switch (isa) {
499 case kArm:
500 // Fall through.
501 case kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100502 elf_header.e_machine = EM_ARM;
503 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700504 break;
505 }
506 case kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100507 elf_header.e_machine = EM_AARCH64;
508 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700509 break;
510 }
511 case kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100512 elf_header.e_machine = EM_386;
513 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700514 break;
515 }
516 case kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100517 elf_header.e_machine = EM_X86_64;
518 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700519 break;
520 }
521 case kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100522 elf_header.e_machine = EM_MIPS;
523 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700524 EF_MIPS_PIC |
525 EF_MIPS_CPIC |
526 EF_MIPS_ABI_O32 |
527 EF_MIPS_ARCH_32R2);
528 break;
529 }
Andreas Gampe57b34292015-01-14 15:45:59 -0800530 case kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100531 elf_header.e_machine = EM_MIPS;
532 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe57b34292015-01-14 15:45:59 -0800533 EF_MIPS_PIC |
534 EF_MIPS_CPIC |
535 EF_MIPS_ARCH_64R6);
536 break;
537 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100538 case kNone: {
539 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000540 break;
541 }
542 default: {
543 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700544 }
545 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700546
David Srbeckybc90fd02015-04-22 19:40:27 +0100547 elf_header.e_ident[EI_MAG0] = ELFMAG0;
548 elf_header.e_ident[EI_MAG1] = ELFMAG1;
549 elf_header.e_ident[EI_MAG2] = ELFMAG2;
550 elf_header.e_ident[EI_MAG3] = ELFMAG3;
551 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Tong Shen62d1ca32014-09-03 17:24:56 -0700552 ? ELFCLASS32 : ELFCLASS64;;
David Srbeckybc90fd02015-04-22 19:40:27 +0100553 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
554 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
555 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
556 elf_header.e_ident[EI_ABIVERSION] = 0;
557 elf_header.e_type = ET_DYN;
558 elf_header.e_version = 1;
559 elf_header.e_entry = 0;
560 elf_header.e_ehsize = sizeof(Elf_Ehdr);
561 elf_header.e_phentsize = sizeof(Elf_Phdr);
562 elf_header.e_shentsize = sizeof(Elf_Shdr);
563 elf_header.e_phoff = sizeof(Elf_Ehdr);
564 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700565 }
566
David Srbecky6d8c8f02015-10-26 10:57:09 +0000567 // Create program headers based on written sections.
568 std::vector<Elf_Phdr> MakeProgramHeaders() {
569 CHECK(!sections_.empty());
570 std::vector<Elf_Phdr> phdrs;
571 {
572 // The program headers must start with PT_PHDR which is used in
573 // loaded process to determine the number of program headers.
574 Elf_Phdr phdr = Elf_Phdr();
575 phdr.p_type = PT_PHDR;
576 phdr.p_flags = PF_R;
577 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
578 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
579 phdr.p_align = sizeof(Elf_Off);
580 phdrs.push_back(phdr);
581 // Tell the linker to mmap the start of file to memory.
582 Elf_Phdr load = Elf_Phdr();
583 load.p_type = PT_LOAD;
584 load.p_flags = PF_R;
585 load.p_offset = load.p_vaddr = load.p_paddr = 0;
586 load.p_filesz = load.p_memsz = sections_[0]->header_.sh_offset;
587 load.p_align = kPageSize;
588 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100589 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000590 // Create program headers for sections.
591 for (auto* section : sections_) {
592 const Elf_Shdr& shdr = section->header_;
593 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
594 // PT_LOAD tells the linker to mmap part of the file.
595 // The linker can only mmap page-aligned sections.
596 // Single PT_LOAD may contain several ELF sections.
597 Elf_Phdr& prev = phdrs.back();
598 Elf_Phdr load = Elf_Phdr();
599 load.p_type = PT_LOAD;
600 load.p_flags = section->phdr_flags_;
601 load.p_offset = shdr.sh_offset;
602 load.p_vaddr = load.p_paddr = shdr.sh_addr;
603 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
604 load.p_memsz = shdr.sh_size;
605 load.p_align = shdr.sh_addralign;
606 if (prev.p_type == load.p_type &&
607 prev.p_flags == load.p_flags &&
608 prev.p_filesz == prev.p_memsz && // Do not merge .bss
609 load.p_filesz == load.p_memsz) { // Do not merge .bss
610 // Merge this PT_LOAD with the previous one.
611 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
612 prev.p_filesz = size;
613 prev.p_memsz = size;
614 } else {
615 // If we are adding new load, it must be aligned.
616 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
617 phdrs.push_back(load);
618 }
619 }
620 }
621 for (auto* section : sections_) {
622 const Elf_Shdr& shdr = section->header_;
623 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
624 // Other PT_* types allow the program to locate interesting
625 // parts of memory at runtime. They must overlap with PT_LOAD.
626 if (section->phdr_type_ != 0) {
627 Elf_Phdr phdr = Elf_Phdr();
628 phdr.p_type = section->phdr_type_;
629 phdr.p_flags = section->phdr_flags_;
630 phdr.p_offset = shdr.sh_offset;
631 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
632 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
633 phdr.p_align = shdr.sh_addralign;
634 phdrs.push_back(phdr);
635 }
636 }
637 }
638 // Set the size of the initial PT_PHDR.
639 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
640 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100641
David Srbecky6d8c8f02015-10-26 10:57:09 +0000642 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700643 }
644
David Srbeckybc90fd02015-04-22 19:40:27 +0100645 InstructionSet isa_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000646
Vladimir Marko131980f2015-12-03 18:29:23 +0000647 ErrorDelayingOutputStream stream_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000648
649 Section rodata_;
650 Section text_;
651 Section bss_;
652 StringSection dynstr_;
653 SymbolSection dynsym_;
654 Section hash_;
655 Section dynamic_;
656 Section eh_frame_;
657 Section eh_frame_hdr_;
658 StringSection strtab_;
659 SymbolSection symtab_;
660 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +0000661 Section debug_info_;
662 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000663 StringSection shstrtab_;
664 std::vector<std::unique_ptr<Section>> other_sections_;
665
666 // List of used section in the order in which they were written.
667 std::vector<Section*> sections_;
668
669 // Used for allocation of virtual address space.
670 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700671
672 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700673};
674
675} // namespace art
676
677#endif // ART_COMPILER_ELF_BUILDER_H_