blob: 6e8dfd60fb60380321b4564fb01dd5d8eb460f2e [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 "buffered_output_stream.h"
27#include "elf_utils.h"
28#include "file_output_stream.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000029#include "leb128.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 virtual ~Section() {
104 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) {
123 header_.sh_offset = RoundUp(owner_->Seek(0, kSeekCurrent), header_.sh_addralign);
124 owner_->Seek(header_.sh_offset, kSeekSet);
125 }
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.
142 off_t file_offset = owner_->Seek(0, kSeekCurrent);
143 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);
164 return owner_->Seek(0, kSeekCurrent) - header_.sh_offset;
165 }
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_);
179 owner_->WriteFully(buffer, byte_count);
180 return true;
181 }
182
183 // This function always succeeds to simplify code.
184 // Use builder's Good() to check the actual status.
185 off_t Seek(off_t offset, Whence whence) OVERRIDE {
186 // Forward the seek as-is and trust the caller to use it reasonably.
187 return owner_->Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100188 }
189
190 Elf_Word GetSectionIndex() const {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000191 DCHECK(started_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100192 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100193 return section_index_;
194 }
195
David Srbecky0c5bbc12015-04-28 17:54:52 +0100196 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000197 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100198 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100199 Elf_Word section_index_;
200 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100201 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000202 bool started_;
203 bool finished_;
204 Elf_Word phdr_flags_;
205 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100206
David Srbecky6d8c8f02015-10-26 10:57:09 +0000207 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000208
209 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100210 };
211
David Srbeckybc90fd02015-04-22 19:40:27 +0100212 // Writer of .dynstr .strtab and .shstrtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000213 class StringSection FINAL : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100214 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000215 StringSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
216 Elf_Word flags, Elf_Word align)
217 : Section(owner, name, SHT_STRTAB, flags, nullptr, 0, align, 0),
218 current_offset_(0) {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100219 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100220
David Srbecky6d8c8f02015-10-26 10:57:09 +0000221 Elf_Word Write(const std::string& name) {
222 if (current_offset_ == 0) {
223 DCHECK(name.empty());
224 }
225 Elf_Word offset = current_offset_;
226 this->WriteFully(name.c_str(), name.length() + 1);
227 current_offset_ += name.length() + 1;
David Srbeckybc90fd02015-04-22 19:40:27 +0100228 return offset;
229 }
230
David Srbeckybc90fd02015-04-22 19:40:27 +0100231 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000232 Elf_Word current_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100233 };
234
David Srbeckybc90fd02015-04-22 19:40:27 +0100235 // Writer of .dynsym and .symtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000236 class SymbolSection FINAL : public Section {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100237 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000238 SymbolSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
239 Elf_Word type, Elf_Word flags, StringSection* strtab)
240 : Section(owner, name, type, flags, strtab, 0,
241 sizeof(Elf_Off), sizeof(Elf_Sym)) {
242 }
243
244 // Buffer symbol for this section. It will be written later.
245 void Add(Elf_Word name, const Section* section,
246 Elf_Addr addr, bool is_relative, Elf_Word size,
247 uint8_t binding, uint8_t type, uint8_t other = 0) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100248 CHECK(section != nullptr);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000249 Elf_Sym sym = Elf_Sym();
250 sym.st_name = name;
251 sym.st_value = addr + (is_relative ? section->GetAddress() : 0);
252 sym.st_size = size;
253 sym.st_other = other;
254 sym.st_shndx = section->GetSectionIndex();
255 sym.st_info = (binding << 4) + (type & 0xf);
256 symbols_.push_back(sym);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100257 }
258
David Srbecky6d8c8f02015-10-26 10:57:09 +0000259 void Write() {
260 // The symbol table always has to start with NULL symbol.
261 Elf_Sym null_symbol = Elf_Sym();
262 this->WriteFully(&null_symbol, sizeof(null_symbol));
263 this->WriteFully(symbols_.data(), symbols_.size() * sizeof(symbols_[0]));
264 symbols_.clear();
265 symbols_.shrink_to_fit();
David Srbeckybc90fd02015-04-22 19:40:27 +0100266 }
267
268 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000269 std::vector<Elf_Sym> symbols_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100270 };
271
David Srbecky6d8c8f02015-10-26 10:57:09 +0000272 ElfBuilder(InstructionSet isa, OutputStream* output)
David Srbeckybc90fd02015-04-22 19:40:27 +0100273 : isa_(isa),
David Srbecky6d8c8f02015-10-26 10:57:09 +0000274 output_(output),
275 output_good_(true),
276 output_offset_(0),
277 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
278 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
279 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
280 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
281 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
282 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
283 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
284 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
285 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
286 strtab_(this, ".strtab", 0, kPageSize),
287 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
288 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
David Srbeckyb851b492015-11-11 20:19:38 +0000289 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
290 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
David Srbecky6d8c8f02015-10-26 10:57:09 +0000291 shstrtab_(this, ".shstrtab", 0, 1),
292 virtual_address_(0) {
293 text_.phdr_flags_ = PF_R | PF_X;
294 bss_.phdr_flags_ = PF_R | PF_W;
295 dynamic_.phdr_flags_ = PF_R | PF_W;
296 dynamic_.phdr_type_ = PT_DYNAMIC;
297 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700298 }
299 ~ElfBuilder() {}
300
David Srbecky6d8c8f02015-10-26 10:57:09 +0000301 InstructionSet GetIsa() { return isa_; }
302 Section* GetRoData() { return &rodata_; }
303 Section* GetText() { return &text_; }
304 Section* GetBss() { return &bss_; }
305 StringSection* GetStrTab() { return &strtab_; }
306 SymbolSection* GetSymTab() { return &symtab_; }
307 Section* GetEhFrame() { return &eh_frame_; }
308 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
309 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000310 Section* GetDebugInfo() { return &debug_info_; }
311 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700312
David Srbecky6d8c8f02015-10-26 10:57:09 +0000313 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
314 // (exposed publicly for tests)
315 static void EncodeOatPatches(const std::vector<uintptr_t>& locations,
316 std::vector<uint8_t>* buffer) {
317 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
318 uintptr_t address = 0; // relative to start of section.
319 for (uintptr_t location : locations) {
320 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
321 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
322 address = location;
323 }
324 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700325
David Srbecky6d8c8f02015-10-26 10:57:09 +0000326 void WritePatches(const char* name, const std::vector<uintptr_t>* patch_locations) {
327 std::vector<uint8_t> buffer;
328 EncodeOatPatches(*patch_locations, &buffer);
329 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
330 s->Start();
331 s->WriteFully(buffer.data(), buffer.size());
332 s->End();
333 other_sections_.push_back(std::move(s));
334 }
David Srbecky527c9c72015-04-17 21:14:10 +0100335
David Srbecky6d8c8f02015-10-26 10:57:09 +0000336 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
337 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
338 s->Start();
339 s->WriteFully(buffer->data(), buffer->size());
340 s->End();
341 other_sections_.push_back(std::move(s));
342 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700343
David Srbecky6d8c8f02015-10-26 10:57:09 +0000344 void Start() {
345 // Reserve space for ELF header and program headers.
346 // We do not know the number of headers until later, so
347 // it is easiest to just reserve a fixed amount of space.
348 int size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
349 Seek(size, kSeekSet);
350 virtual_address_ += size;
351 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700352
David Srbecky6d8c8f02015-10-26 10:57:09 +0000353 void End() {
354 // Write section names and finish the section headers.
355 shstrtab_.Start();
356 shstrtab_.Write("");
357 for (auto* section : sections_) {
358 section->header_.sh_name = shstrtab_.Write(section->name_);
359 if (section->link_ != nullptr) {
360 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100361 }
David Srbecky527c9c72015-04-17 21:14:10 +0100362 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000363 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100364
David Srbecky6d8c8f02015-10-26 10:57:09 +0000365 // Write section headers at the end of the ELF file.
366 std::vector<Elf_Shdr> shdrs;
367 shdrs.reserve(1u + sections_.size());
368 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
369 for (auto* section : sections_) {
370 shdrs.push_back(section->header_);
371 }
372 Elf_Off section_headers_offset;
373 section_headers_offset = RoundUp(Seek(0, kSeekCurrent), sizeof(Elf_Off));
374 Seek(section_headers_offset, kSeekSet);
375 WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
376
377 // Write the initial file headers.
378 std::vector<Elf_Phdr> phdrs = MakeProgramHeaders();
David Srbeckybc90fd02015-04-22 19:40:27 +0100379 Elf_Ehdr elf_header = MakeElfHeader(isa_);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000380 elf_header.e_phoff = sizeof(Elf_Ehdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100381 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000382 elf_header.e_phnum = phdrs.size();
383 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100384 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000385 Seek(0, kSeekSet);
386 WriteFully(&elf_header, sizeof(elf_header));
387 WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700388 }
389
David Srbecky6d8c8f02015-10-26 10:57:09 +0000390 // The running program does not have access to section headers
391 // and the loader is not supposed to use them either.
392 // The dynamic sections therefore replicates some of the layout
393 // information like the address and size of .rodata and .text.
394 // It also contains other metadata like the SONAME.
395 // The .dynamic section is found using the PT_DYNAMIC program header.
396 void WriteDynamicSection(const std::string& elf_file_path) {
397 std::string soname(elf_file_path);
398 size_t directory_separator_pos = soname.rfind('/');
399 if (directory_separator_pos != std::string::npos) {
400 soname = soname.substr(directory_separator_pos + 1);
401 }
402
403 dynstr_.Start();
404 dynstr_.Write(""); // dynstr should start with empty string.
405 dynsym_.Add(dynstr_.Write("oatdata"), &rodata_, 0, true,
406 rodata_.GetSize(), STB_GLOBAL, STT_OBJECT);
407 if (text_.GetSize() != 0u) {
408 dynsym_.Add(dynstr_.Write("oatexec"), &text_, 0, true,
409 text_.GetSize(), STB_GLOBAL, STT_OBJECT);
410 dynsym_.Add(dynstr_.Write("oatlastword"), &text_, text_.GetSize() - 4,
411 true, 4, STB_GLOBAL, STT_OBJECT);
412 } else if (rodata_.GetSize() != 0) {
413 // rodata_ can be size 0 for dwarf_test.
414 dynsym_.Add(dynstr_.Write("oatlastword"), &rodata_, rodata_.GetSize() - 4,
415 true, 4, STB_GLOBAL, STT_OBJECT);
416 }
417 if (bss_.finished_) {
418 dynsym_.Add(dynstr_.Write("oatbss"), &bss_,
419 0, true, bss_.GetSize(), STB_GLOBAL, STT_OBJECT);
420 dynsym_.Add(dynstr_.Write("oatbsslastword"), &bss_,
421 bss_.GetSize() - 4, true, 4, STB_GLOBAL, STT_OBJECT);
422 }
423 Elf_Word soname_offset = dynstr_.Write(soname);
424 dynstr_.End();
425
426 dynsym_.Start();
427 dynsym_.Write();
428 dynsym_.End();
429
430 // We do not really need a hash-table since there is so few entries.
431 // However, the hash-table is the only way the linker can actually
432 // determine the number of symbols in .dynsym so it is required.
433 hash_.Start();
434 int count = dynsym_.GetSize() / sizeof(Elf_Sym); // Includes NULL.
435 std::vector<Elf_Word> hash;
436 hash.push_back(1); // Number of buckets.
437 hash.push_back(count); // Number of chains.
438 // Buckets. Having just one makes it linear search.
439 hash.push_back(1); // Point to first non-NULL symbol.
440 // Chains. This creates linked list of symbols.
441 hash.push_back(0); // Dummy entry for the NULL symbol.
442 for (int i = 1; i < count - 1; i++) {
443 hash.push_back(i + 1); // Each symbol points to the next one.
444 }
445 hash.push_back(0); // Last symbol terminates the chain.
446 hash_.WriteFully(hash.data(), hash.size() * sizeof(hash[0]));
447 hash_.End();
448
449 dynamic_.Start();
450 Elf_Dyn dyns[] = {
451 { DT_HASH, { hash_.GetAddress() } },
452 { DT_STRTAB, { dynstr_.GetAddress() } },
453 { DT_SYMTAB, { dynsym_.GetAddress() } },
454 { DT_SYMENT, { sizeof(Elf_Sym) } },
455 { DT_STRSZ, { dynstr_.GetSize() } },
456 { DT_SONAME, { soname_offset } },
457 { DT_NULL, { 0 } },
458 };
459 dynamic_.WriteFully(&dyns, sizeof(dyns));
460 dynamic_.End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700461 }
462
David Srbecky6d8c8f02015-10-26 10:57:09 +0000463 // Returns true if all writes and seeks on the output stream succeeded.
464 bool Good() {
465 return output_good_;
David Srbecky527c9c72015-04-17 21:14:10 +0100466 }
467
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700468 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000469 // This function always succeeds to simplify code.
470 // Use Good() to check the actual status of the output stream.
471 void WriteFully(const void* buffer, size_t byte_count) {
472 if (output_good_) {
473 if (!output_->WriteFully(buffer, byte_count)) {
474 PLOG(ERROR) << "Failed to write " << byte_count
475 << " bytes to ELF file at offset " << output_offset_;
476 output_good_ = false;
David Srbeckyf8980872015-05-22 17:04:47 +0100477 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100478 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000479 output_offset_ += byte_count;
David Srbeckybc90fd02015-04-22 19:40:27 +0100480 }
481
David Srbecky6d8c8f02015-10-26 10:57:09 +0000482 // This function always succeeds to simplify code.
483 // Use Good() to check the actual status of the output stream.
484 off_t Seek(off_t offset, Whence whence) {
485 // We keep shadow copy of the offset so that we return
486 // the expected value even if the output stream failed.
487 off_t new_offset;
488 switch (whence) {
489 case kSeekSet:
490 new_offset = offset;
491 break;
492 case kSeekCurrent:
493 new_offset = output_offset_ + offset;
494 break;
495 default:
496 LOG(FATAL) << "Unsupported seek type: " << whence;
497 UNREACHABLE();
498 }
499 if (output_good_) {
500 off_t actual_offset = output_->Seek(offset, whence);
501 if (actual_offset == (off_t)-1) {
502 PLOG(ERROR) << "Failed to seek in ELF file. Offset=" << offset
503 << " whence=" << whence << " new_offset=" << new_offset;
504 output_good_ = false;
505 }
506 DCHECK_EQ(actual_offset, new_offset);
507 }
508 output_offset_ = new_offset;
509 return new_offset;
David Srbeckybc90fd02015-04-22 19:40:27 +0100510 }
511
512 static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
513 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700514 switch (isa) {
515 case kArm:
516 // Fall through.
517 case kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100518 elf_header.e_machine = EM_ARM;
519 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700520 break;
521 }
522 case kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100523 elf_header.e_machine = EM_AARCH64;
524 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700525 break;
526 }
527 case kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100528 elf_header.e_machine = EM_386;
529 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700530 break;
531 }
532 case kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100533 elf_header.e_machine = EM_X86_64;
534 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700535 break;
536 }
537 case kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100538 elf_header.e_machine = EM_MIPS;
539 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700540 EF_MIPS_PIC |
541 EF_MIPS_CPIC |
542 EF_MIPS_ABI_O32 |
543 EF_MIPS_ARCH_32R2);
544 break;
545 }
Andreas Gampe57b34292015-01-14 15:45:59 -0800546 case kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100547 elf_header.e_machine = EM_MIPS;
548 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe57b34292015-01-14 15:45:59 -0800549 EF_MIPS_PIC |
550 EF_MIPS_CPIC |
551 EF_MIPS_ARCH_64R6);
552 break;
553 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100554 case kNone: {
555 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000556 break;
557 }
558 default: {
559 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700560 }
561 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700562
David Srbeckybc90fd02015-04-22 19:40:27 +0100563 elf_header.e_ident[EI_MAG0] = ELFMAG0;
564 elf_header.e_ident[EI_MAG1] = ELFMAG1;
565 elf_header.e_ident[EI_MAG2] = ELFMAG2;
566 elf_header.e_ident[EI_MAG3] = ELFMAG3;
567 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Tong Shen62d1ca32014-09-03 17:24:56 -0700568 ? ELFCLASS32 : ELFCLASS64;;
David Srbeckybc90fd02015-04-22 19:40:27 +0100569 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
570 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
571 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
572 elf_header.e_ident[EI_ABIVERSION] = 0;
573 elf_header.e_type = ET_DYN;
574 elf_header.e_version = 1;
575 elf_header.e_entry = 0;
576 elf_header.e_ehsize = sizeof(Elf_Ehdr);
577 elf_header.e_phentsize = sizeof(Elf_Phdr);
578 elf_header.e_shentsize = sizeof(Elf_Shdr);
579 elf_header.e_phoff = sizeof(Elf_Ehdr);
580 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700581 }
582
David Srbecky6d8c8f02015-10-26 10:57:09 +0000583 // Create program headers based on written sections.
584 std::vector<Elf_Phdr> MakeProgramHeaders() {
585 CHECK(!sections_.empty());
586 std::vector<Elf_Phdr> phdrs;
587 {
588 // The program headers must start with PT_PHDR which is used in
589 // loaded process to determine the number of program headers.
590 Elf_Phdr phdr = Elf_Phdr();
591 phdr.p_type = PT_PHDR;
592 phdr.p_flags = PF_R;
593 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
594 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
595 phdr.p_align = sizeof(Elf_Off);
596 phdrs.push_back(phdr);
597 // Tell the linker to mmap the start of file to memory.
598 Elf_Phdr load = Elf_Phdr();
599 load.p_type = PT_LOAD;
600 load.p_flags = PF_R;
601 load.p_offset = load.p_vaddr = load.p_paddr = 0;
602 load.p_filesz = load.p_memsz = sections_[0]->header_.sh_offset;
603 load.p_align = kPageSize;
604 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100605 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000606 // Create program headers for sections.
607 for (auto* section : sections_) {
608 const Elf_Shdr& shdr = section->header_;
609 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
610 // PT_LOAD tells the linker to mmap part of the file.
611 // The linker can only mmap page-aligned sections.
612 // Single PT_LOAD may contain several ELF sections.
613 Elf_Phdr& prev = phdrs.back();
614 Elf_Phdr load = Elf_Phdr();
615 load.p_type = PT_LOAD;
616 load.p_flags = section->phdr_flags_;
617 load.p_offset = shdr.sh_offset;
618 load.p_vaddr = load.p_paddr = shdr.sh_addr;
619 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
620 load.p_memsz = shdr.sh_size;
621 load.p_align = shdr.sh_addralign;
622 if (prev.p_type == load.p_type &&
623 prev.p_flags == load.p_flags &&
624 prev.p_filesz == prev.p_memsz && // Do not merge .bss
625 load.p_filesz == load.p_memsz) { // Do not merge .bss
626 // Merge this PT_LOAD with the previous one.
627 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
628 prev.p_filesz = size;
629 prev.p_memsz = size;
630 } else {
631 // If we are adding new load, it must be aligned.
632 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
633 phdrs.push_back(load);
634 }
635 }
636 }
637 for (auto* section : sections_) {
638 const Elf_Shdr& shdr = section->header_;
639 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
640 // Other PT_* types allow the program to locate interesting
641 // parts of memory at runtime. They must overlap with PT_LOAD.
642 if (section->phdr_type_ != 0) {
643 Elf_Phdr phdr = Elf_Phdr();
644 phdr.p_type = section->phdr_type_;
645 phdr.p_flags = section->phdr_flags_;
646 phdr.p_offset = shdr.sh_offset;
647 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
648 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
649 phdr.p_align = shdr.sh_addralign;
650 phdrs.push_back(phdr);
651 }
652 }
653 }
654 // Set the size of the initial PT_PHDR.
655 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
656 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100657
David Srbecky6d8c8f02015-10-26 10:57:09 +0000658 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700659 }
660
David Srbeckybc90fd02015-04-22 19:40:27 +0100661 InstructionSet isa_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000662
663 OutputStream* output_;
664 bool output_good_; // True if all writes to output succeeded.
665 off_t output_offset_; // Keep track of the current position in the stream.
666
667 Section rodata_;
668 Section text_;
669 Section bss_;
670 StringSection dynstr_;
671 SymbolSection dynsym_;
672 Section hash_;
673 Section dynamic_;
674 Section eh_frame_;
675 Section eh_frame_hdr_;
676 StringSection strtab_;
677 SymbolSection symtab_;
678 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +0000679 Section debug_info_;
680 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000681 StringSection shstrtab_;
682 std::vector<std::unique_ptr<Section>> other_sections_;
683
684 // List of used section in the order in which they were written.
685 std::vector<Section*> sections_;
686
687 // Used for allocation of virtual address space.
688 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700689
690 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700691};
692
693} // namespace art
694
695#endif // ART_COMPILER_ELF_BUILDER_H_