blob: bb07cc291338d864c2e9b89a0fe481a28afc82ac [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
Vladimir Marko10c13562015-11-25 14:33:36 +0000103 ~Section() OVERRIDE {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000104 if (started_) {
105 CHECK(finished_);
106 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100107 }
108
David Srbecky6d8c8f02015-10-26 10:57:09 +0000109 // Start writing of this section.
110 void Start() {
111 CHECK(!started_);
112 CHECK(!finished_);
113 started_ = true;
114 auto& sections = owner_->sections_;
115 // Check that the previous section is complete.
116 CHECK(sections.empty() || sections.back()->finished_);
117 // The first ELF section index is 1. Index 0 is reserved for NULL.
118 section_index_ = sections.size() + 1;
119 // Push this section on the list of written sections.
120 sections.push_back(this);
121 // Align file position.
122 if (header_.sh_type != SHT_NOBITS) {
Vladimir Marko131980f2015-12-03 18:29:23 +0000123 header_.sh_offset = RoundUp(owner_->stream_.Seek(0, kSeekCurrent), header_.sh_addralign);
124 owner_->stream_.Seek(header_.sh_offset, kSeekSet);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000125 }
126 // Align virtual memory address.
127 if ((header_.sh_flags & SHF_ALLOC) != 0) {
128 header_.sh_addr = RoundUp(owner_->virtual_address_, header_.sh_addralign);
129 owner_->virtual_address_ = header_.sh_addr;
130 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100131 }
132
David Srbecky6d8c8f02015-10-26 10:57:09 +0000133 // Finish writing of this section.
134 void End() {
135 CHECK(started_);
136 CHECK(!finished_);
137 finished_ = true;
138 if (header_.sh_type == SHT_NOBITS) {
139 CHECK_GT(header_.sh_size, 0u);
140 } else {
141 // Use the current file position to determine section size.
Vladimir Marko131980f2015-12-03 18:29:23 +0000142 off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000143 CHECK_GE(file_offset, (off_t)header_.sh_offset);
144 header_.sh_size = file_offset - header_.sh_offset;
145 }
146 if ((header_.sh_flags & SHF_ALLOC) != 0) {
147 owner_->virtual_address_ += header_.sh_size;
148 }
149 }
150
151 // 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
168 // Set desired allocation size for .bss section.
169 void SetSize(Elf_Word size) {
170 CHECK_EQ(header_.sh_type, (Elf_Word)SHT_NOBITS);
171 header_.sh_size = size;
172 }
173
174 // This function always succeeds to simplify code.
175 // Use builder's Good() to check the actual status.
176 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
177 CHECK(started_);
178 CHECK(!finished_);
Vladimir Marko131980f2015-12-03 18:29:23 +0000179 return owner_->stream_.WriteFully(buffer, byte_count);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000180 }
181
182 // This function always succeeds to simplify code.
183 // Use builder's Good() to check the actual status.
184 off_t Seek(off_t offset, Whence whence) OVERRIDE {
185 // Forward the seek as-is and trust the caller to use it reasonably.
Vladimir Marko131980f2015-12-03 18:29:23 +0000186 return owner_->stream_.Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100187 }
188
Vladimir Marko10c13562015-11-25 14:33:36 +0000189 // This function flushes the output and returns whether it succeeded.
190 // If there was a previous failure, this does nothing and returns false, i.e. failed.
191 bool Flush() OVERRIDE {
Vladimir Marko131980f2015-12-03 18:29:23 +0000192 return owner_->stream_.Flush();
Vladimir Marko10c13562015-11-25 14:33:36 +0000193 }
194
David Srbecky0c5bbc12015-04-28 17:54:52 +0100195 Elf_Word GetSectionIndex() const {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000196 DCHECK(started_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100197 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100198 return section_index_;
199 }
200
David Srbecky0c5bbc12015-04-28 17:54:52 +0100201 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000202 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100203 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100204 Elf_Word section_index_;
205 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100206 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000207 bool started_;
208 bool finished_;
209 Elf_Word phdr_flags_;
210 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100211
David Srbecky6d8c8f02015-10-26 10:57:09 +0000212 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000213
214 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100215 };
216
David Srbeckybc90fd02015-04-22 19:40:27 +0100217 // Writer of .dynstr .strtab and .shstrtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000218 class StringSection FINAL : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100219 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000220 StringSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
221 Elf_Word flags, Elf_Word align)
222 : Section(owner, name, SHT_STRTAB, flags, nullptr, 0, align, 0),
223 current_offset_(0) {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100224 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100225
David Srbecky6d8c8f02015-10-26 10:57:09 +0000226 Elf_Word Write(const std::string& name) {
227 if (current_offset_ == 0) {
228 DCHECK(name.empty());
229 }
230 Elf_Word offset = current_offset_;
231 this->WriteFully(name.c_str(), name.length() + 1);
232 current_offset_ += name.length() + 1;
David Srbeckybc90fd02015-04-22 19:40:27 +0100233 return offset;
234 }
235
David Srbeckybc90fd02015-04-22 19:40:27 +0100236 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000237 Elf_Word current_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100238 };
239
David Srbeckybc90fd02015-04-22 19:40:27 +0100240 // Writer of .dynsym and .symtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000241 class SymbolSection FINAL : public Section {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100242 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000243 SymbolSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
244 Elf_Word type, Elf_Word flags, StringSection* strtab)
245 : Section(owner, name, type, flags, strtab, 0,
246 sizeof(Elf_Off), sizeof(Elf_Sym)) {
247 }
248
249 // Buffer symbol for this section. It will be written later.
250 void Add(Elf_Word name, const Section* section,
251 Elf_Addr addr, bool is_relative, Elf_Word size,
252 uint8_t binding, uint8_t type, uint8_t other = 0) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100253 CHECK(section != nullptr);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000254 Elf_Sym sym = Elf_Sym();
255 sym.st_name = name;
256 sym.st_value = addr + (is_relative ? section->GetAddress() : 0);
257 sym.st_size = size;
258 sym.st_other = other;
259 sym.st_shndx = section->GetSectionIndex();
260 sym.st_info = (binding << 4) + (type & 0xf);
261 symbols_.push_back(sym);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100262 }
263
David Srbecky6d8c8f02015-10-26 10:57:09 +0000264 void Write() {
265 // The symbol table always has to start with NULL symbol.
266 Elf_Sym null_symbol = Elf_Sym();
267 this->WriteFully(&null_symbol, sizeof(null_symbol));
268 this->WriteFully(symbols_.data(), symbols_.size() * sizeof(symbols_[0]));
269 symbols_.clear();
270 symbols_.shrink_to_fit();
David Srbeckybc90fd02015-04-22 19:40:27 +0100271 }
272
273 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000274 std::vector<Elf_Sym> symbols_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100275 };
276
David Srbecky6d8c8f02015-10-26 10:57:09 +0000277 ElfBuilder(InstructionSet isa, OutputStream* output)
Vladimir Marko131980f2015-12-03 18:29:23 +0000278 : isa_(isa),
279 stream_(output),
280 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
281 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
282 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
283 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
284 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
285 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
286 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
287 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
288 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
289 strtab_(this, ".strtab", 0, kPageSize),
290 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
291 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
292 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
293 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
294 shstrtab_(this, ".shstrtab", 0, 1),
295 virtual_address_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000296 text_.phdr_flags_ = PF_R | PF_X;
297 bss_.phdr_flags_ = PF_R | PF_W;
298 dynamic_.phdr_flags_ = PF_R | PF_W;
299 dynamic_.phdr_type_ = PT_DYNAMIC;
300 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700301 }
302 ~ElfBuilder() {}
303
David Srbecky6d8c8f02015-10-26 10:57:09 +0000304 InstructionSet GetIsa() { return isa_; }
305 Section* GetRoData() { return &rodata_; }
306 Section* GetText() { return &text_; }
307 Section* GetBss() { return &bss_; }
308 StringSection* GetStrTab() { return &strtab_; }
309 SymbolSection* GetSymTab() { return &symtab_; }
310 Section* GetEhFrame() { return &eh_frame_; }
311 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
312 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000313 Section* GetDebugInfo() { return &debug_info_; }
314 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700315
David Srbecky6d8c8f02015-10-26 10:57:09 +0000316 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
317 // (exposed publicly for tests)
Vladimir Marko10c13562015-11-25 14:33:36 +0000318 static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000319 std::vector<uint8_t>* buffer) {
320 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
321 uintptr_t address = 0; // relative to start of section.
322 for (uintptr_t location : locations) {
323 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
324 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
325 address = location;
326 }
327 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700328
Vladimir Marko10c13562015-11-25 14:33:36 +0000329 void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000330 std::vector<uint8_t> buffer;
Vladimir Marko10c13562015-11-25 14:33:36 +0000331 EncodeOatPatches(patch_locations, &buffer);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000332 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
333 s->Start();
334 s->WriteFully(buffer.data(), buffer.size());
335 s->End();
336 other_sections_.push_back(std::move(s));
337 }
David Srbecky527c9c72015-04-17 21:14:10 +0100338
David Srbecky6d8c8f02015-10-26 10:57:09 +0000339 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
340 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
341 s->Start();
342 s->WriteFully(buffer->data(), buffer->size());
343 s->End();
344 other_sections_.push_back(std::move(s));
345 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700346
David Srbecky6d8c8f02015-10-26 10:57:09 +0000347 void Start() {
348 // Reserve space for ELF header and program headers.
349 // We do not know the number of headers until later, so
350 // it is easiest to just reserve a fixed amount of space.
351 int size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
Vladimir Marko131980f2015-12-03 18:29:23 +0000352 stream_.Seek(size, kSeekSet);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000353 virtual_address_ += size;
354 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700355
David Srbecky6d8c8f02015-10-26 10:57:09 +0000356 void End() {
357 // Write section names and finish the section headers.
358 shstrtab_.Start();
359 shstrtab_.Write("");
360 for (auto* section : sections_) {
361 section->header_.sh_name = shstrtab_.Write(section->name_);
362 if (section->link_ != nullptr) {
363 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100364 }
David Srbecky527c9c72015-04-17 21:14:10 +0100365 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000366 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100367
David Srbecky6d8c8f02015-10-26 10:57:09 +0000368 // Write section headers at the end of the ELF file.
369 std::vector<Elf_Shdr> shdrs;
370 shdrs.reserve(1u + sections_.size());
371 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
372 for (auto* section : sections_) {
373 shdrs.push_back(section->header_);
374 }
375 Elf_Off section_headers_offset;
Vladimir Marko131980f2015-12-03 18:29:23 +0000376 section_headers_offset = RoundUp(stream_.Seek(0, kSeekCurrent), sizeof(Elf_Off));
377 stream_.Seek(section_headers_offset, kSeekSet);
378 stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
379
380 // Flush everything else before writing the program headers. This should prevent
381 // the OS from reordering writes, so that we don't end up with valid headers
382 // and partially written data if we suddenly lose power, for example.
383 stream_.Flush();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000384
385 // Write the initial file headers.
386 std::vector<Elf_Phdr> phdrs = MakeProgramHeaders();
David Srbeckybc90fd02015-04-22 19:40:27 +0100387 Elf_Ehdr elf_header = MakeElfHeader(isa_);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000388 elf_header.e_phoff = sizeof(Elf_Ehdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100389 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000390 elf_header.e_phnum = phdrs.size();
391 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100392 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
Vladimir Marko131980f2015-12-03 18:29:23 +0000393 stream_.Seek(0, kSeekSet);
394 stream_.WriteFully(&elf_header, sizeof(elf_header));
395 stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
396 stream_.Flush();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700397 }
398
David Srbecky6d8c8f02015-10-26 10:57:09 +0000399 // The running program does not have access to section headers
400 // and the loader is not supposed to use them either.
401 // The dynamic sections therefore replicates some of the layout
402 // information like the address and size of .rodata and .text.
403 // It also contains other metadata like the SONAME.
404 // The .dynamic section is found using the PT_DYNAMIC program header.
405 void WriteDynamicSection(const std::string& elf_file_path) {
406 std::string soname(elf_file_path);
407 size_t directory_separator_pos = soname.rfind('/');
408 if (directory_separator_pos != std::string::npos) {
409 soname = soname.substr(directory_separator_pos + 1);
410 }
411
412 dynstr_.Start();
413 dynstr_.Write(""); // dynstr should start with empty string.
414 dynsym_.Add(dynstr_.Write("oatdata"), &rodata_, 0, true,
415 rodata_.GetSize(), STB_GLOBAL, STT_OBJECT);
416 if (text_.GetSize() != 0u) {
417 dynsym_.Add(dynstr_.Write("oatexec"), &text_, 0, true,
418 text_.GetSize(), STB_GLOBAL, STT_OBJECT);
419 dynsym_.Add(dynstr_.Write("oatlastword"), &text_, text_.GetSize() - 4,
420 true, 4, STB_GLOBAL, STT_OBJECT);
421 } else if (rodata_.GetSize() != 0) {
422 // rodata_ can be size 0 for dwarf_test.
423 dynsym_.Add(dynstr_.Write("oatlastword"), &rodata_, rodata_.GetSize() - 4,
424 true, 4, STB_GLOBAL, STT_OBJECT);
425 }
426 if (bss_.finished_) {
427 dynsym_.Add(dynstr_.Write("oatbss"), &bss_,
428 0, true, bss_.GetSize(), STB_GLOBAL, STT_OBJECT);
429 dynsym_.Add(dynstr_.Write("oatbsslastword"), &bss_,
430 bss_.GetSize() - 4, true, 4, STB_GLOBAL, STT_OBJECT);
431 }
432 Elf_Word soname_offset = dynstr_.Write(soname);
433 dynstr_.End();
434
435 dynsym_.Start();
436 dynsym_.Write();
437 dynsym_.End();
438
439 // We do not really need a hash-table since there is so few entries.
440 // However, the hash-table is the only way the linker can actually
441 // determine the number of symbols in .dynsym so it is required.
442 hash_.Start();
443 int count = dynsym_.GetSize() / sizeof(Elf_Sym); // Includes NULL.
444 std::vector<Elf_Word> hash;
445 hash.push_back(1); // Number of buckets.
446 hash.push_back(count); // Number of chains.
447 // Buckets. Having just one makes it linear search.
448 hash.push_back(1); // Point to first non-NULL symbol.
449 // Chains. This creates linked list of symbols.
450 hash.push_back(0); // Dummy entry for the NULL symbol.
451 for (int i = 1; i < count - 1; i++) {
452 hash.push_back(i + 1); // Each symbol points to the next one.
453 }
454 hash.push_back(0); // Last symbol terminates the chain.
455 hash_.WriteFully(hash.data(), hash.size() * sizeof(hash[0]));
456 hash_.End();
457
458 dynamic_.Start();
459 Elf_Dyn dyns[] = {
460 { DT_HASH, { hash_.GetAddress() } },
461 { DT_STRTAB, { dynstr_.GetAddress() } },
462 { DT_SYMTAB, { dynsym_.GetAddress() } },
463 { DT_SYMENT, { sizeof(Elf_Sym) } },
464 { DT_STRSZ, { dynstr_.GetSize() } },
465 { DT_SONAME, { soname_offset } },
466 { DT_NULL, { 0 } },
467 };
468 dynamic_.WriteFully(&dyns, sizeof(dyns));
469 dynamic_.End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700470 }
471
David Srbecky6d8c8f02015-10-26 10:57:09 +0000472 // Returns true if all writes and seeks on the output stream succeeded.
473 bool Good() {
Vladimir Marko131980f2015-12-03 18:29:23 +0000474 return stream_.Good();
475 }
476
477 // Returns the builder's internal stream.
478 OutputStream* GetStream() {
479 return &stream_;
David Srbecky527c9c72015-04-17 21:14:10 +0100480 }
481
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700482 private:
David Srbeckybc90fd02015-04-22 19:40:27 +0100483 static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
484 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700485 switch (isa) {
486 case kArm:
487 // Fall through.
488 case kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100489 elf_header.e_machine = EM_ARM;
490 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700491 break;
492 }
493 case kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100494 elf_header.e_machine = EM_AARCH64;
495 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700496 break;
497 }
498 case kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100499 elf_header.e_machine = EM_386;
500 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700501 break;
502 }
503 case kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100504 elf_header.e_machine = EM_X86_64;
505 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700506 break;
507 }
508 case kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100509 elf_header.e_machine = EM_MIPS;
510 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700511 EF_MIPS_PIC |
512 EF_MIPS_CPIC |
513 EF_MIPS_ABI_O32 |
514 EF_MIPS_ARCH_32R2);
515 break;
516 }
Andreas Gampe57b34292015-01-14 15:45:59 -0800517 case kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100518 elf_header.e_machine = EM_MIPS;
519 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe57b34292015-01-14 15:45:59 -0800520 EF_MIPS_PIC |
521 EF_MIPS_CPIC |
522 EF_MIPS_ARCH_64R6);
523 break;
524 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100525 case kNone: {
526 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000527 break;
528 }
529 default: {
530 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700531 }
532 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700533
David Srbeckybc90fd02015-04-22 19:40:27 +0100534 elf_header.e_ident[EI_MAG0] = ELFMAG0;
535 elf_header.e_ident[EI_MAG1] = ELFMAG1;
536 elf_header.e_ident[EI_MAG2] = ELFMAG2;
537 elf_header.e_ident[EI_MAG3] = ELFMAG3;
538 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Tong Shen62d1ca32014-09-03 17:24:56 -0700539 ? ELFCLASS32 : ELFCLASS64;;
David Srbeckybc90fd02015-04-22 19:40:27 +0100540 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
541 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
542 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
543 elf_header.e_ident[EI_ABIVERSION] = 0;
544 elf_header.e_type = ET_DYN;
545 elf_header.e_version = 1;
546 elf_header.e_entry = 0;
547 elf_header.e_ehsize = sizeof(Elf_Ehdr);
548 elf_header.e_phentsize = sizeof(Elf_Phdr);
549 elf_header.e_shentsize = sizeof(Elf_Shdr);
550 elf_header.e_phoff = sizeof(Elf_Ehdr);
551 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700552 }
553
David Srbecky6d8c8f02015-10-26 10:57:09 +0000554 // Create program headers based on written sections.
555 std::vector<Elf_Phdr> MakeProgramHeaders() {
556 CHECK(!sections_.empty());
557 std::vector<Elf_Phdr> phdrs;
558 {
559 // The program headers must start with PT_PHDR which is used in
560 // loaded process to determine the number of program headers.
561 Elf_Phdr phdr = Elf_Phdr();
562 phdr.p_type = PT_PHDR;
563 phdr.p_flags = PF_R;
564 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
565 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
566 phdr.p_align = sizeof(Elf_Off);
567 phdrs.push_back(phdr);
568 // Tell the linker to mmap the start of file to memory.
569 Elf_Phdr load = Elf_Phdr();
570 load.p_type = PT_LOAD;
571 load.p_flags = PF_R;
572 load.p_offset = load.p_vaddr = load.p_paddr = 0;
573 load.p_filesz = load.p_memsz = sections_[0]->header_.sh_offset;
574 load.p_align = kPageSize;
575 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100576 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000577 // Create program headers for sections.
578 for (auto* section : sections_) {
579 const Elf_Shdr& shdr = section->header_;
580 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
581 // PT_LOAD tells the linker to mmap part of the file.
582 // The linker can only mmap page-aligned sections.
583 // Single PT_LOAD may contain several ELF sections.
584 Elf_Phdr& prev = phdrs.back();
585 Elf_Phdr load = Elf_Phdr();
586 load.p_type = PT_LOAD;
587 load.p_flags = section->phdr_flags_;
588 load.p_offset = shdr.sh_offset;
589 load.p_vaddr = load.p_paddr = shdr.sh_addr;
590 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
591 load.p_memsz = shdr.sh_size;
592 load.p_align = shdr.sh_addralign;
593 if (prev.p_type == load.p_type &&
594 prev.p_flags == load.p_flags &&
595 prev.p_filesz == prev.p_memsz && // Do not merge .bss
596 load.p_filesz == load.p_memsz) { // Do not merge .bss
597 // Merge this PT_LOAD with the previous one.
598 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
599 prev.p_filesz = size;
600 prev.p_memsz = size;
601 } else {
602 // If we are adding new load, it must be aligned.
603 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
604 phdrs.push_back(load);
605 }
606 }
607 }
608 for (auto* section : sections_) {
609 const Elf_Shdr& shdr = section->header_;
610 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
611 // Other PT_* types allow the program to locate interesting
612 // parts of memory at runtime. They must overlap with PT_LOAD.
613 if (section->phdr_type_ != 0) {
614 Elf_Phdr phdr = Elf_Phdr();
615 phdr.p_type = section->phdr_type_;
616 phdr.p_flags = section->phdr_flags_;
617 phdr.p_offset = shdr.sh_offset;
618 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
619 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
620 phdr.p_align = shdr.sh_addralign;
621 phdrs.push_back(phdr);
622 }
623 }
624 }
625 // Set the size of the initial PT_PHDR.
626 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
627 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100628
David Srbecky6d8c8f02015-10-26 10:57:09 +0000629 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700630 }
631
David Srbeckybc90fd02015-04-22 19:40:27 +0100632 InstructionSet isa_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000633
Vladimir Marko131980f2015-12-03 18:29:23 +0000634 ErrorDelayingOutputStream stream_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000635
636 Section rodata_;
637 Section text_;
638 Section bss_;
639 StringSection dynstr_;
640 SymbolSection dynsym_;
641 Section hash_;
642 Section dynamic_;
643 Section eh_frame_;
644 Section eh_frame_hdr_;
645 StringSection strtab_;
646 SymbolSection symtab_;
647 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +0000648 Section debug_info_;
649 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000650 StringSection shstrtab_;
651 std::vector<std::unique_ptr<Section>> other_sections_;
652
653 // List of used section in the order in which they were written.
654 std::vector<Section*> sections_;
655
656 // Used for allocation of virtual address space.
657 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700658
659 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700660};
661
662} // namespace art
663
664#endif // ART_COMPILER_ELF_BUILDER_H_