blob: c19bc3db5ce757ab66eec8351f2840aa480f5750 [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"
Vladimir Marko10c13562015-11-25 14:33:36 +000030#include "utils/array_ref.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070031
32namespace art {
33
David Srbeckybc90fd02015-04-22 19:40:27 +010034// Writes ELF file.
David Srbecky6d8c8f02015-10-26 10:57:09 +000035//
36// The basic layout of the elf file:
37// Elf_Ehdr - The ELF header.
38// Elf_Phdr[] - Program headers for the linker.
39// .rodata - DEX files and oat metadata.
40// .text - Compiled code.
41// .bss - Zero-initialized writeable section.
42// .dynstr - Names for .dynsym.
43// .dynsym - A few oat-specific dynamic symbols.
44// .hash - Hash-table for .dynsym.
45// .dynamic - Tags which let the linker locate .dynsym.
46// .strtab - Names for .symtab.
47// .symtab - Debug symbols.
48// .eh_frame - Unwind information (CFI).
49// .eh_frame_hdr - Index of .eh_frame.
50// .debug_frame - Unwind information (CFI).
51// .debug_frame.oat_patches - Addresses for relocation.
52// .debug_info - Debug information.
53// .debug_info.oat_patches - Addresses for relocation.
54// .debug_abbrev - Decoding information for .debug_info.
55// .debug_str - Strings for .debug_info.
56// .debug_line - Line number tables.
57// .debug_line.oat_patches - Addresses for relocation.
58// .text.oat_patches - Addresses for relocation.
59// .shstrtab - Names of ELF sections.
60// Elf_Shdr[] - Section headers.
61//
62// Some section are optional (the debug sections in particular).
63//
64// We try write the section data directly into the file without much
65// in-memory buffering. This means we generally write sections based on the
66// dependency order (e.g. .dynamic points to .dynsym which points to .text).
67//
68// In the cases where we need to buffer, we write the larger section first
69// and buffer the smaller one (e.g. .strtab is bigger than .symtab).
70//
71// The debug sections are written last for easier stripping.
72//
David Srbecky533c2072015-04-22 12:20:22 +010073template <typename ElfTypes>
Andreas Gampe54fc26c2014-09-04 21:47:42 -070074class ElfBuilder FINAL {
75 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000076 static constexpr size_t kMaxProgramHeaders = 16;
David Srbecky533c2072015-04-22 12:20:22 +010077 using Elf_Addr = typename ElfTypes::Addr;
David Srbeckybc90fd02015-04-22 19:40:27 +010078 using Elf_Off = typename ElfTypes::Off;
David Srbecky533c2072015-04-22 12:20:22 +010079 using Elf_Word = typename ElfTypes::Word;
80 using Elf_Sword = typename ElfTypes::Sword;
81 using Elf_Ehdr = typename ElfTypes::Ehdr;
82 using Elf_Shdr = typename ElfTypes::Shdr;
83 using Elf_Sym = typename ElfTypes::Sym;
84 using Elf_Phdr = typename ElfTypes::Phdr;
85 using Elf_Dyn = typename ElfTypes::Dyn;
86
David Srbeckybc90fd02015-04-22 19:40:27 +010087 // Base class of all sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +000088 class Section : public OutputStream {
David Srbecky0c5bbc12015-04-28 17:54:52 +010089 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000090 Section(ElfBuilder<ElfTypes>* owner, const std::string& name,
91 Elf_Word type, Elf_Word flags, const Section* link,
92 Elf_Word info, Elf_Word align, Elf_Word entsize)
93 : OutputStream(name), owner_(owner), header_(),
94 section_index_(0), name_(name), link_(link),
95 started_(false), finished_(false), phdr_flags_(PF_R), phdr_type_(0) {
96 DCHECK_GE(align, 1u);
David Srbecky491a7fe2015-05-28 00:59:08 +010097 header_.sh_type = type;
98 header_.sh_flags = flags;
99 header_.sh_info = info;
100 header_.sh_addralign = align;
101 header_.sh_entsize = entsize;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100102 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100103
Vladimir Marko10c13562015-11-25 14:33:36 +0000104 ~Section() OVERRIDE {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000105 if (started_) {
106 CHECK(finished_);
107 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100108 }
109
David Srbecky6d8c8f02015-10-26 10:57:09 +0000110 // Start writing of this section.
111 void Start() {
112 CHECK(!started_);
113 CHECK(!finished_);
114 started_ = true;
115 auto& sections = owner_->sections_;
116 // Check that the previous section is complete.
117 CHECK(sections.empty() || sections.back()->finished_);
118 // The first ELF section index is 1. Index 0 is reserved for NULL.
119 section_index_ = sections.size() + 1;
120 // Push this section on the list of written sections.
121 sections.push_back(this);
122 // Align file position.
123 if (header_.sh_type != SHT_NOBITS) {
124 header_.sh_offset = RoundUp(owner_->Seek(0, kSeekCurrent), header_.sh_addralign);
125 owner_->Seek(header_.sh_offset, kSeekSet);
126 }
127 // Align virtual memory address.
128 if ((header_.sh_flags & SHF_ALLOC) != 0) {
129 header_.sh_addr = RoundUp(owner_->virtual_address_, header_.sh_addralign);
130 owner_->virtual_address_ = header_.sh_addr;
131 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100132 }
133
David Srbecky6d8c8f02015-10-26 10:57:09 +0000134 // Finish writing of this section.
135 void End() {
136 CHECK(started_);
137 CHECK(!finished_);
138 finished_ = true;
139 if (header_.sh_type == SHT_NOBITS) {
140 CHECK_GT(header_.sh_size, 0u);
141 } else {
142 // Use the current file position to determine section size.
143 off_t file_offset = owner_->Seek(0, kSeekCurrent);
144 CHECK_GE(file_offset, (off_t)header_.sh_offset);
145 header_.sh_size = file_offset - header_.sh_offset;
146 }
147 if ((header_.sh_flags & SHF_ALLOC) != 0) {
148 owner_->virtual_address_ += header_.sh_size;
149 }
150 }
151
152 // Get the location of this section in virtual memory.
153 Elf_Addr GetAddress() const {
154 CHECK(started_);
155 return header_.sh_addr;
156 }
157
158 // Returns the size of the content of this section.
159 Elf_Word GetSize() const {
David Srbeckyb851b492015-11-11 20:19:38 +0000160 if (finished_) {
161 return header_.sh_size;
162 } else {
163 CHECK(started_);
164 CHECK_NE(header_.sh_type, (Elf_Word)SHT_NOBITS);
165 return owner_->Seek(0, kSeekCurrent) - header_.sh_offset;
166 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000167 }
168
169 // Set desired allocation size for .bss section.
170 void SetSize(Elf_Word size) {
171 CHECK_EQ(header_.sh_type, (Elf_Word)SHT_NOBITS);
172 header_.sh_size = size;
173 }
174
175 // This function always succeeds to simplify code.
176 // Use builder's Good() to check the actual status.
177 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
178 CHECK(started_);
179 CHECK(!finished_);
180 owner_->WriteFully(buffer, byte_count);
181 return true;
182 }
183
184 // This function always succeeds to simplify code.
185 // Use builder's Good() to check the actual status.
186 off_t Seek(off_t offset, Whence whence) OVERRIDE {
187 // Forward the seek as-is and trust the caller to use it reasonably.
188 return owner_->Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100189 }
190
Vladimir Marko10c13562015-11-25 14:33:36 +0000191 // This function flushes the output and returns whether it succeeded.
192 // If there was a previous failure, this does nothing and returns false, i.e. failed.
193 bool Flush() OVERRIDE {
194 return owner_->Flush();
195 }
196
David Srbecky0c5bbc12015-04-28 17:54:52 +0100197 Elf_Word GetSectionIndex() const {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000198 DCHECK(started_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100199 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100200 return section_index_;
201 }
202
David Srbecky0c5bbc12015-04-28 17:54:52 +0100203 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000204 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100205 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100206 Elf_Word section_index_;
207 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100208 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000209 bool started_;
210 bool finished_;
211 Elf_Word phdr_flags_;
212 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100213
David Srbecky6d8c8f02015-10-26 10:57:09 +0000214 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000215
216 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100217 };
218
David Srbeckybc90fd02015-04-22 19:40:27 +0100219 // Writer of .dynstr .strtab and .shstrtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000220 class StringSection FINAL : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100221 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000222 StringSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
223 Elf_Word flags, Elf_Word align)
224 : Section(owner, name, SHT_STRTAB, flags, nullptr, 0, align, 0),
225 current_offset_(0) {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100226 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100227
David Srbecky6d8c8f02015-10-26 10:57:09 +0000228 Elf_Word Write(const std::string& name) {
229 if (current_offset_ == 0) {
230 DCHECK(name.empty());
231 }
232 Elf_Word offset = current_offset_;
233 this->WriteFully(name.c_str(), name.length() + 1);
234 current_offset_ += name.length() + 1;
David Srbeckybc90fd02015-04-22 19:40:27 +0100235 return offset;
236 }
237
David Srbeckybc90fd02015-04-22 19:40:27 +0100238 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000239 Elf_Word current_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100240 };
241
David Srbeckybc90fd02015-04-22 19:40:27 +0100242 // Writer of .dynsym and .symtab sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000243 class SymbolSection FINAL : public Section {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100244 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000245 SymbolSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
246 Elf_Word type, Elf_Word flags, StringSection* strtab)
247 : Section(owner, name, type, flags, strtab, 0,
248 sizeof(Elf_Off), sizeof(Elf_Sym)) {
249 }
250
251 // Buffer symbol for this section. It will be written later.
252 void Add(Elf_Word name, const Section* section,
253 Elf_Addr addr, bool is_relative, Elf_Word size,
254 uint8_t binding, uint8_t type, uint8_t other = 0) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100255 CHECK(section != nullptr);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000256 Elf_Sym sym = Elf_Sym();
257 sym.st_name = name;
258 sym.st_value = addr + (is_relative ? section->GetAddress() : 0);
259 sym.st_size = size;
260 sym.st_other = other;
261 sym.st_shndx = section->GetSectionIndex();
262 sym.st_info = (binding << 4) + (type & 0xf);
263 symbols_.push_back(sym);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100264 }
265
David Srbecky6d8c8f02015-10-26 10:57:09 +0000266 void Write() {
267 // The symbol table always has to start with NULL symbol.
268 Elf_Sym null_symbol = Elf_Sym();
269 this->WriteFully(&null_symbol, sizeof(null_symbol));
270 this->WriteFully(symbols_.data(), symbols_.size() * sizeof(symbols_[0]));
271 symbols_.clear();
272 symbols_.shrink_to_fit();
David Srbeckybc90fd02015-04-22 19:40:27 +0100273 }
274
275 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000276 std::vector<Elf_Sym> symbols_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100277 };
278
David Srbecky6d8c8f02015-10-26 10:57:09 +0000279 ElfBuilder(InstructionSet isa, OutputStream* output)
David Srbeckybc90fd02015-04-22 19:40:27 +0100280 : isa_(isa),
David Srbecky6d8c8f02015-10-26 10:57:09 +0000281 output_(output),
282 output_good_(true),
283 output_offset_(0),
284 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
285 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
286 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
287 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
288 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
289 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
290 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
291 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
292 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
293 strtab_(this, ".strtab", 0, kPageSize),
294 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
295 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
David Srbeckyb851b492015-11-11 20:19:38 +0000296 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
297 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
David Srbecky6d8c8f02015-10-26 10:57:09 +0000298 shstrtab_(this, ".shstrtab", 0, 1),
299 virtual_address_(0) {
300 text_.phdr_flags_ = PF_R | PF_X;
301 bss_.phdr_flags_ = PF_R | PF_W;
302 dynamic_.phdr_flags_ = PF_R | PF_W;
303 dynamic_.phdr_type_ = PT_DYNAMIC;
304 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700305 }
306 ~ElfBuilder() {}
307
David Srbecky6d8c8f02015-10-26 10:57:09 +0000308 InstructionSet GetIsa() { return isa_; }
309 Section* GetRoData() { return &rodata_; }
310 Section* GetText() { return &text_; }
311 Section* GetBss() { return &bss_; }
312 StringSection* GetStrTab() { return &strtab_; }
313 SymbolSection* GetSymTab() { return &symtab_; }
314 Section* GetEhFrame() { return &eh_frame_; }
315 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
316 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000317 Section* GetDebugInfo() { return &debug_info_; }
318 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700319
David Srbecky6d8c8f02015-10-26 10:57:09 +0000320 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
321 // (exposed publicly for tests)
Vladimir Marko10c13562015-11-25 14:33:36 +0000322 static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000323 std::vector<uint8_t>* buffer) {
324 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
325 uintptr_t address = 0; // relative to start of section.
326 for (uintptr_t location : locations) {
327 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
328 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
329 address = location;
330 }
331 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700332
Vladimir Marko10c13562015-11-25 14:33:36 +0000333 void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000334 std::vector<uint8_t> buffer;
Vladimir Marko10c13562015-11-25 14:33:36 +0000335 EncodeOatPatches(patch_locations, &buffer);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000336 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
337 s->Start();
338 s->WriteFully(buffer.data(), buffer.size());
339 s->End();
340 other_sections_.push_back(std::move(s));
341 }
David Srbecky527c9c72015-04-17 21:14:10 +0100342
David Srbecky6d8c8f02015-10-26 10:57:09 +0000343 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
344 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
345 s->Start();
346 s->WriteFully(buffer->data(), buffer->size());
347 s->End();
348 other_sections_.push_back(std::move(s));
349 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700350
David Srbecky6d8c8f02015-10-26 10:57:09 +0000351 void Start() {
352 // Reserve space for ELF header and program headers.
353 // We do not know the number of headers until later, so
354 // it is easiest to just reserve a fixed amount of space.
355 int size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
356 Seek(size, kSeekSet);
357 virtual_address_ += size;
358 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700359
David Srbecky6d8c8f02015-10-26 10:57:09 +0000360 void End() {
361 // Write section names and finish the section headers.
362 shstrtab_.Start();
363 shstrtab_.Write("");
364 for (auto* section : sections_) {
365 section->header_.sh_name = shstrtab_.Write(section->name_);
366 if (section->link_ != nullptr) {
367 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100368 }
David Srbecky527c9c72015-04-17 21:14:10 +0100369 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000370 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100371
David Srbecky6d8c8f02015-10-26 10:57:09 +0000372 // Write section headers at the end of the ELF file.
373 std::vector<Elf_Shdr> shdrs;
374 shdrs.reserve(1u + sections_.size());
375 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
376 for (auto* section : sections_) {
377 shdrs.push_back(section->header_);
378 }
379 Elf_Off section_headers_offset;
380 section_headers_offset = RoundUp(Seek(0, kSeekCurrent), sizeof(Elf_Off));
381 Seek(section_headers_offset, kSeekSet);
382 WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
383
384 // Write the initial file headers.
385 std::vector<Elf_Phdr> phdrs = MakeProgramHeaders();
David Srbeckybc90fd02015-04-22 19:40:27 +0100386 Elf_Ehdr elf_header = MakeElfHeader(isa_);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000387 elf_header.e_phoff = sizeof(Elf_Ehdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100388 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000389 elf_header.e_phnum = phdrs.size();
390 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100391 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000392 Seek(0, kSeekSet);
393 WriteFully(&elf_header, sizeof(elf_header));
394 WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
Vladimir Marko10c13562015-11-25 14:33:36 +0000395 Flush();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700396 }
397
David Srbecky6d8c8f02015-10-26 10:57:09 +0000398 // The running program does not have access to section headers
399 // and the loader is not supposed to use them either.
400 // The dynamic sections therefore replicates some of the layout
401 // information like the address and size of .rodata and .text.
402 // It also contains other metadata like the SONAME.
403 // The .dynamic section is found using the PT_DYNAMIC program header.
404 void WriteDynamicSection(const std::string& elf_file_path) {
405 std::string soname(elf_file_path);
406 size_t directory_separator_pos = soname.rfind('/');
407 if (directory_separator_pos != std::string::npos) {
408 soname = soname.substr(directory_separator_pos + 1);
409 }
410
411 dynstr_.Start();
412 dynstr_.Write(""); // dynstr should start with empty string.
413 dynsym_.Add(dynstr_.Write("oatdata"), &rodata_, 0, true,
414 rodata_.GetSize(), STB_GLOBAL, STT_OBJECT);
415 if (text_.GetSize() != 0u) {
416 dynsym_.Add(dynstr_.Write("oatexec"), &text_, 0, true,
417 text_.GetSize(), STB_GLOBAL, STT_OBJECT);
418 dynsym_.Add(dynstr_.Write("oatlastword"), &text_, text_.GetSize() - 4,
419 true, 4, STB_GLOBAL, STT_OBJECT);
420 } else if (rodata_.GetSize() != 0) {
421 // rodata_ can be size 0 for dwarf_test.
422 dynsym_.Add(dynstr_.Write("oatlastword"), &rodata_, rodata_.GetSize() - 4,
423 true, 4, STB_GLOBAL, STT_OBJECT);
424 }
425 if (bss_.finished_) {
426 dynsym_.Add(dynstr_.Write("oatbss"), &bss_,
427 0, true, bss_.GetSize(), STB_GLOBAL, STT_OBJECT);
428 dynsym_.Add(dynstr_.Write("oatbsslastword"), &bss_,
429 bss_.GetSize() - 4, true, 4, STB_GLOBAL, STT_OBJECT);
430 }
431 Elf_Word soname_offset = dynstr_.Write(soname);
432 dynstr_.End();
433
434 dynsym_.Start();
435 dynsym_.Write();
436 dynsym_.End();
437
438 // We do not really need a hash-table since there is so few entries.
439 // However, the hash-table is the only way the linker can actually
440 // determine the number of symbols in .dynsym so it is required.
441 hash_.Start();
442 int count = dynsym_.GetSize() / sizeof(Elf_Sym); // Includes NULL.
443 std::vector<Elf_Word> hash;
444 hash.push_back(1); // Number of buckets.
445 hash.push_back(count); // Number of chains.
446 // Buckets. Having just one makes it linear search.
447 hash.push_back(1); // Point to first non-NULL symbol.
448 // Chains. This creates linked list of symbols.
449 hash.push_back(0); // Dummy entry for the NULL symbol.
450 for (int i = 1; i < count - 1; i++) {
451 hash.push_back(i + 1); // Each symbol points to the next one.
452 }
453 hash.push_back(0); // Last symbol terminates the chain.
454 hash_.WriteFully(hash.data(), hash.size() * sizeof(hash[0]));
455 hash_.End();
456
457 dynamic_.Start();
458 Elf_Dyn dyns[] = {
459 { DT_HASH, { hash_.GetAddress() } },
460 { DT_STRTAB, { dynstr_.GetAddress() } },
461 { DT_SYMTAB, { dynsym_.GetAddress() } },
462 { DT_SYMENT, { sizeof(Elf_Sym) } },
463 { DT_STRSZ, { dynstr_.GetSize() } },
464 { DT_SONAME, { soname_offset } },
465 { DT_NULL, { 0 } },
466 };
467 dynamic_.WriteFully(&dyns, sizeof(dyns));
468 dynamic_.End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700469 }
470
David Srbecky6d8c8f02015-10-26 10:57:09 +0000471 // Returns true if all writes and seeks on the output stream succeeded.
472 bool Good() {
473 return output_good_;
David Srbecky527c9c72015-04-17 21:14:10 +0100474 }
475
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700476 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000477 // This function always succeeds to simplify code.
478 // Use Good() to check the actual status of the output stream.
479 void WriteFully(const void* buffer, size_t byte_count) {
480 if (output_good_) {
481 if (!output_->WriteFully(buffer, byte_count)) {
482 PLOG(ERROR) << "Failed to write " << byte_count
483 << " bytes to ELF file at offset " << output_offset_;
484 output_good_ = false;
David Srbeckyf8980872015-05-22 17:04:47 +0100485 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100486 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000487 output_offset_ += byte_count;
David Srbeckybc90fd02015-04-22 19:40:27 +0100488 }
489
David Srbecky6d8c8f02015-10-26 10:57:09 +0000490 // This function always succeeds to simplify code.
491 // Use Good() to check the actual status of the output stream.
492 off_t Seek(off_t offset, Whence whence) {
493 // We keep shadow copy of the offset so that we return
494 // the expected value even if the output stream failed.
495 off_t new_offset;
496 switch (whence) {
497 case kSeekSet:
498 new_offset = offset;
499 break;
500 case kSeekCurrent:
501 new_offset = output_offset_ + offset;
502 break;
503 default:
504 LOG(FATAL) << "Unsupported seek type: " << whence;
505 UNREACHABLE();
506 }
507 if (output_good_) {
508 off_t actual_offset = output_->Seek(offset, whence);
509 if (actual_offset == (off_t)-1) {
510 PLOG(ERROR) << "Failed to seek in ELF file. Offset=" << offset
511 << " whence=" << whence << " new_offset=" << new_offset;
512 output_good_ = false;
513 }
514 DCHECK_EQ(actual_offset, new_offset);
515 }
516 output_offset_ = new_offset;
517 return new_offset;
David Srbeckybc90fd02015-04-22 19:40:27 +0100518 }
519
Vladimir Marko10c13562015-11-25 14:33:36 +0000520 bool Flush() {
521 if (output_good_) {
522 output_good_ = output_->Flush();
523 }
524 return output_good_;
525 }
526
David Srbeckybc90fd02015-04-22 19:40:27 +0100527 static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
528 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700529 switch (isa) {
530 case kArm:
531 // Fall through.
532 case kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100533 elf_header.e_machine = EM_ARM;
534 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700535 break;
536 }
537 case kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100538 elf_header.e_machine = EM_AARCH64;
539 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700540 break;
541 }
542 case kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100543 elf_header.e_machine = EM_386;
544 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700545 break;
546 }
547 case kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100548 elf_header.e_machine = EM_X86_64;
549 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700550 break;
551 }
552 case kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100553 elf_header.e_machine = EM_MIPS;
554 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700555 EF_MIPS_PIC |
556 EF_MIPS_CPIC |
557 EF_MIPS_ABI_O32 |
558 EF_MIPS_ARCH_32R2);
559 break;
560 }
Andreas Gampe57b34292015-01-14 15:45:59 -0800561 case kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100562 elf_header.e_machine = EM_MIPS;
563 elf_header.e_flags = (EF_MIPS_NOREORDER |
Andreas Gampe57b34292015-01-14 15:45:59 -0800564 EF_MIPS_PIC |
565 EF_MIPS_CPIC |
566 EF_MIPS_ARCH_64R6);
567 break;
568 }
David Srbeckybc90fd02015-04-22 19:40:27 +0100569 case kNone: {
570 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000571 break;
572 }
573 default: {
574 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700575 }
576 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700577
David Srbeckybc90fd02015-04-22 19:40:27 +0100578 elf_header.e_ident[EI_MAG0] = ELFMAG0;
579 elf_header.e_ident[EI_MAG1] = ELFMAG1;
580 elf_header.e_ident[EI_MAG2] = ELFMAG2;
581 elf_header.e_ident[EI_MAG3] = ELFMAG3;
582 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Tong Shen62d1ca32014-09-03 17:24:56 -0700583 ? ELFCLASS32 : ELFCLASS64;;
David Srbeckybc90fd02015-04-22 19:40:27 +0100584 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
585 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
586 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
587 elf_header.e_ident[EI_ABIVERSION] = 0;
588 elf_header.e_type = ET_DYN;
589 elf_header.e_version = 1;
590 elf_header.e_entry = 0;
591 elf_header.e_ehsize = sizeof(Elf_Ehdr);
592 elf_header.e_phentsize = sizeof(Elf_Phdr);
593 elf_header.e_shentsize = sizeof(Elf_Shdr);
594 elf_header.e_phoff = sizeof(Elf_Ehdr);
595 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700596 }
597
David Srbecky6d8c8f02015-10-26 10:57:09 +0000598 // Create program headers based on written sections.
599 std::vector<Elf_Phdr> MakeProgramHeaders() {
600 CHECK(!sections_.empty());
601 std::vector<Elf_Phdr> phdrs;
602 {
603 // The program headers must start with PT_PHDR which is used in
604 // loaded process to determine the number of program headers.
605 Elf_Phdr phdr = Elf_Phdr();
606 phdr.p_type = PT_PHDR;
607 phdr.p_flags = PF_R;
608 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
609 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
610 phdr.p_align = sizeof(Elf_Off);
611 phdrs.push_back(phdr);
612 // Tell the linker to mmap the start of file to memory.
613 Elf_Phdr load = Elf_Phdr();
614 load.p_type = PT_LOAD;
615 load.p_flags = PF_R;
616 load.p_offset = load.p_vaddr = load.p_paddr = 0;
617 load.p_filesz = load.p_memsz = sections_[0]->header_.sh_offset;
618 load.p_align = kPageSize;
619 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +0100620 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000621 // Create program headers for sections.
622 for (auto* section : sections_) {
623 const Elf_Shdr& shdr = section->header_;
624 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
625 // PT_LOAD tells the linker to mmap part of the file.
626 // The linker can only mmap page-aligned sections.
627 // Single PT_LOAD may contain several ELF sections.
628 Elf_Phdr& prev = phdrs.back();
629 Elf_Phdr load = Elf_Phdr();
630 load.p_type = PT_LOAD;
631 load.p_flags = section->phdr_flags_;
632 load.p_offset = shdr.sh_offset;
633 load.p_vaddr = load.p_paddr = shdr.sh_addr;
634 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
635 load.p_memsz = shdr.sh_size;
636 load.p_align = shdr.sh_addralign;
637 if (prev.p_type == load.p_type &&
638 prev.p_flags == load.p_flags &&
639 prev.p_filesz == prev.p_memsz && // Do not merge .bss
640 load.p_filesz == load.p_memsz) { // Do not merge .bss
641 // Merge this PT_LOAD with the previous one.
642 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
643 prev.p_filesz = size;
644 prev.p_memsz = size;
645 } else {
646 // If we are adding new load, it must be aligned.
647 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
648 phdrs.push_back(load);
649 }
650 }
651 }
652 for (auto* section : sections_) {
653 const Elf_Shdr& shdr = section->header_;
654 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
655 // Other PT_* types allow the program to locate interesting
656 // parts of memory at runtime. They must overlap with PT_LOAD.
657 if (section->phdr_type_ != 0) {
658 Elf_Phdr phdr = Elf_Phdr();
659 phdr.p_type = section->phdr_type_;
660 phdr.p_flags = section->phdr_flags_;
661 phdr.p_offset = shdr.sh_offset;
662 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
663 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
664 phdr.p_align = shdr.sh_addralign;
665 phdrs.push_back(phdr);
666 }
667 }
668 }
669 // Set the size of the initial PT_PHDR.
670 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
671 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100672
David Srbecky6d8c8f02015-10-26 10:57:09 +0000673 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700674 }
675
David Srbeckybc90fd02015-04-22 19:40:27 +0100676 InstructionSet isa_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000677
678 OutputStream* output_;
679 bool output_good_; // True if all writes to output succeeded.
680 off_t output_offset_; // Keep track of the current position in the stream.
681
682 Section rodata_;
683 Section text_;
684 Section bss_;
685 StringSection dynstr_;
686 SymbolSection dynsym_;
687 Section hash_;
688 Section dynamic_;
689 Section eh_frame_;
690 Section eh_frame_hdr_;
691 StringSection strtab_;
692 SymbolSection symtab_;
693 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +0000694 Section debug_info_;
695 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000696 StringSection shstrtab_;
697 std::vector<std::unique_ptr<Section>> other_sections_;
698
699 // List of used section in the order in which they were written.
700 std::vector<Section*> sections_;
701
702 // Used for allocation of virtual address space.
703 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -0700704
705 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700706};
707
708} // namespace art
709
710#endif // ART_COMPILER_ELF_BUILDER_H_