blob: 81ecc175b5e0134f7089542f914cd0fbfde0bbc5 [file] [log] [blame]
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001/*
David Srbeckybc90fd02015-04-22 19:40:27 +01002 * Copyright (C) 2015 The Android Open Source Project
Andreas Gampe54fc26c2014-09-04 21:47:42 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Vladimir Marko74527972016-11-29 15:57:32 +000017#ifndef ART_COMPILER_LINKER_ELF_BUILDER_H_
18#define ART_COMPILER_LINKER_ELF_BUILDER_H_
Andreas Gampe54fc26c2014-09-04 21:47:42 -070019
David Srbeckybc90fd02015-04-22 19:40:27 +010020#include <vector>
21
Ian Rogersd582fa42014-11-05 23:46:43 -080022#include "arch/instruction_set.h"
David Srbecky5d811202016-03-08 13:21:22 +000023#include "arch/mips/instruction_set_features_mips.h"
David Brazdild9c90372016-09-14 16:53:55 +010024#include "base/array_ref.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010025#include "base/bit_utils.h"
David Srbecky6d8c8f02015-10-26 10:57:09 +000026#include "base/casts.h"
David Sehr67bf42e2018-02-26 16:43:04 -080027#include "base/leb128.h"
David Srbeckybc90fd02015-04-22 19:40:27 +010028#include "base/unix_file/fd_file.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070029#include "elf_utils.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000030#include "linker/error_delaying_output_stream.h"
Andreas Gampe54fc26c2014-09-04 21:47:42 -070031
32namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000033namespace linker {
Andreas Gampe54fc26c2014-09-04 21:47:42 -070034
David Srbeckybc90fd02015-04-22 19:40:27 +010035// Writes ELF file.
David Srbecky6d8c8f02015-10-26 10:57:09 +000036//
37// The basic layout of the elf file:
38// Elf_Ehdr - The ELF header.
39// Elf_Phdr[] - Program headers for the linker.
Alexey Alexandrovab40c112016-09-19 09:33:49 -070040// .note.gnu.build-id - Optional build ID section (SHA-1 digest).
David Srbeckyec2cdf42017-12-08 16:21:25 +000041// .rodata - Oat metadata.
David Srbecky6d8c8f02015-10-26 10:57:09 +000042// .text - Compiled code.
43// .bss - Zero-initialized writeable section.
David Srbeckyec2cdf42017-12-08 16:21:25 +000044// .dex - Reserved NOBITS space for dex-related data.
Douglas Leung316a2182015-09-17 15:26:25 -070045// .MIPS.abiflags - MIPS specific section.
David Srbecky6d8c8f02015-10-26 10:57:09 +000046// .dynstr - Names for .dynsym.
47// .dynsym - A few oat-specific dynamic symbols.
48// .hash - Hash-table for .dynsym.
49// .dynamic - Tags which let the linker locate .dynsym.
50// .strtab - Names for .symtab.
51// .symtab - Debug symbols.
52// .eh_frame - Unwind information (CFI).
53// .eh_frame_hdr - Index of .eh_frame.
54// .debug_frame - Unwind information (CFI).
55// .debug_frame.oat_patches - Addresses for relocation.
56// .debug_info - Debug information.
57// .debug_info.oat_patches - Addresses for relocation.
58// .debug_abbrev - Decoding information for .debug_info.
59// .debug_str - Strings for .debug_info.
60// .debug_line - Line number tables.
61// .debug_line.oat_patches - Addresses for relocation.
62// .text.oat_patches - Addresses for relocation.
63// .shstrtab - Names of ELF sections.
64// Elf_Shdr[] - Section headers.
65//
66// Some section are optional (the debug sections in particular).
67//
68// We try write the section data directly into the file without much
69// in-memory buffering. This means we generally write sections based on the
70// dependency order (e.g. .dynamic points to .dynsym which points to .text).
71//
72// In the cases where we need to buffer, we write the larger section first
73// and buffer the smaller one (e.g. .strtab is bigger than .symtab).
74//
75// The debug sections are written last for easier stripping.
76//
David Srbecky533c2072015-04-22 12:20:22 +010077template <typename ElfTypes>
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010078class ElfBuilder final {
Andreas Gampe54fc26c2014-09-04 21:47:42 -070079 public:
David Srbecky6d8c8f02015-10-26 10:57:09 +000080 static constexpr size_t kMaxProgramHeaders = 16;
Alexey Alexandrovab40c112016-09-19 09:33:49 -070081 // SHA-1 digest. Not using SHA_DIGEST_LENGTH from openssl/sha.h to avoid
82 // spreading this header dependency for just this single constant.
83 static constexpr size_t kBuildIdLen = 20;
84
David Srbecky533c2072015-04-22 12:20:22 +010085 using Elf_Addr = typename ElfTypes::Addr;
David Srbeckybc90fd02015-04-22 19:40:27 +010086 using Elf_Off = typename ElfTypes::Off;
David Srbecky533c2072015-04-22 12:20:22 +010087 using Elf_Word = typename ElfTypes::Word;
88 using Elf_Sword = typename ElfTypes::Sword;
89 using Elf_Ehdr = typename ElfTypes::Ehdr;
90 using Elf_Shdr = typename ElfTypes::Shdr;
91 using Elf_Sym = typename ElfTypes::Sym;
92 using Elf_Phdr = typename ElfTypes::Phdr;
93 using Elf_Dyn = typename ElfTypes::Dyn;
94
David Srbeckybc90fd02015-04-22 19:40:27 +010095 // Base class of all sections.
David Srbecky6d8c8f02015-10-26 10:57:09 +000096 class Section : public OutputStream {
David Srbecky0c5bbc12015-04-28 17:54:52 +010097 public:
Vladimir Marko944da602016-02-19 12:27:55 +000098 Section(ElfBuilder<ElfTypes>* owner,
99 const std::string& name,
100 Elf_Word type,
101 Elf_Word flags,
102 const Section* link,
103 Elf_Word info,
104 Elf_Word align,
105 Elf_Word entsize)
106 : OutputStream(name),
107 owner_(owner),
108 header_(),
109 section_index_(0),
110 name_(name),
111 link_(link),
Vladimir Marko944da602016-02-19 12:27:55 +0000112 phdr_flags_(PF_R),
113 phdr_type_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000114 DCHECK_GE(align, 1u);
David Srbecky491a7fe2015-05-28 00:59:08 +0100115 header_.sh_type = type;
116 header_.sh_flags = flags;
117 header_.sh_info = info;
118 header_.sh_addralign = align;
119 header_.sh_entsize = entsize;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100120 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100121
David Srbeckye155f4b2017-12-06 15:18:38 +0000122 // Allocate chunk of virtual memory for this section from the owning ElfBuilder.
123 // This must be done at the start for all SHF_ALLOC sections (i.e. mmaped by linker).
124 // It is fine to allocate section but never call Start/End() (e.g. the .bss section).
125 void AllocateVirtualMemory(Elf_Word size) {
126 AllocateVirtualMemory(owner_->virtual_address_, size);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100127 }
128
David Srbeckye155f4b2017-12-06 15:18:38 +0000129 void AllocateVirtualMemory(Elf_Addr addr, Elf_Word size) {
130 CHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
131 Elf_Word align = AddSection();
132 CHECK_EQ(header_.sh_addr, 0u);
133 header_.sh_addr = RoundUp(addr, align);
134 CHECK(header_.sh_size == 0u || header_.sh_size == size);
135 header_.sh_size = size;
136 CHECK_LE(owner_->virtual_address_, header_.sh_addr);
137 owner_->virtual_address_ = header_.sh_addr + header_.sh_size;
138 }
139
140 // Start writing file data of this section.
141 void Start() {
142 CHECK(owner_->current_section_ == nullptr);
143 Elf_Word align = AddSection();
144 CHECK_EQ(header_.sh_offset, 0u);
145 header_.sh_offset = owner_->AlignFileOffset(align);
146 owner_->current_section_ = this;
147 }
148
149 // Finish writing file data of this section.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000150 void End() {
David Srbeckye155f4b2017-12-06 15:18:38 +0000151 CHECK(owner_->current_section_ == this);
152 Elf_Word position = GetPosition();
153 CHECK(header_.sh_size == 0u || header_.sh_size == position);
154 header_.sh_size = position;
155 owner_->current_section_ = nullptr;
156 }
157
158 // Get the number of bytes written so far.
159 // Only valid while writing the section.
160 Elf_Word GetPosition() const {
161 CHECK(owner_->current_section_ == this);
162 off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
163 DCHECK_GE(file_offset, (off_t)header_.sh_offset);
164 return file_offset - header_.sh_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000165 }
166
167 // Get the location of this section in virtual memory.
168 Elf_Addr GetAddress() const {
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000169 DCHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
David Srbeckye155f4b2017-12-06 15:18:38 +0000170 DCHECK_NE(header_.sh_addr, 0u);
171 return header_.sh_addr;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000172 }
173
174 // This function always succeeds to simplify code.
175 // Use builder's Good() to check the actual status.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100176 bool WriteFully(const void* buffer, size_t byte_count) override {
David Srbeckye155f4b2017-12-06 15:18:38 +0000177 CHECK(owner_->current_section_ == this);
Vladimir Marko131980f2015-12-03 18:29:23 +0000178 return owner_->stream_.WriteFully(buffer, byte_count);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000179 }
180
181 // This function always succeeds to simplify code.
182 // Use builder's Good() to check the actual status.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100183 off_t Seek(off_t offset, Whence whence) override {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000184 // Forward the seek as-is and trust the caller to use it reasonably.
Vladimir Marko131980f2015-12-03 18:29:23 +0000185 return owner_->stream_.Seek(offset, whence);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100186 }
187
Vladimir Marko10c13562015-11-25 14:33:36 +0000188 // This function flushes the output and returns whether it succeeded.
189 // If there was a previous failure, this does nothing and returns false, i.e. failed.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100190 bool Flush() override {
Vladimir Marko131980f2015-12-03 18:29:23 +0000191 return owner_->stream_.Flush();
Vladimir Marko10c13562015-11-25 14:33:36 +0000192 }
193
David Srbecky0c5bbc12015-04-28 17:54:52 +0100194 Elf_Word GetSectionIndex() const {
David Srbeckybc90fd02015-04-22 19:40:27 +0100195 DCHECK_NE(section_index_, 0u);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100196 return section_index_;
197 }
198
David Srbecky32210b92017-12-04 14:39:21 +0000199 // Returns true if this section has been added.
200 bool Exists() const {
201 return section_index_ != 0;
202 }
203
David Srbeckyd2645a32018-02-16 16:16:39 +0000204 protected:
David Srbeckye155f4b2017-12-06 15:18:38 +0000205 // Add this section to the list of generated ELF sections (if not there already).
206 // It also ensures the alignment is sufficient to generate valid program headers,
207 // since that depends on the previous section. It returns the required alignment.
208 Elf_Word AddSection() {
209 if (section_index_ == 0) {
210 std::vector<Section*>& sections = owner_->sections_;
211 Elf_Word last = sections.empty() ? PF_R : sections.back()->phdr_flags_;
David Srbeckyf4886df2017-12-11 16:06:29 +0000212 if (phdr_flags_ != last) {
David Srbeckye155f4b2017-12-06 15:18:38 +0000213 header_.sh_addralign = kPageSize; // Page-align if R/W/X flags changed.
214 }
215 sections.push_back(this);
216 section_index_ = sections.size(); // First ELF section has index 1.
217 }
David Srbeckyf4886df2017-12-11 16:06:29 +0000218 return owner_->write_program_headers_ ? header_.sh_addralign : 1;
David Srbeckye155f4b2017-12-06 15:18:38 +0000219 }
220
David Srbecky6d8c8f02015-10-26 10:57:09 +0000221 ElfBuilder<ElfTypes>* owner_;
David Srbecky491a7fe2015-05-28 00:59:08 +0100222 Elf_Shdr header_;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100223 Elf_Word section_index_;
224 const std::string name_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100225 const Section* const link_;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000226 Elf_Word phdr_flags_;
227 Elf_Word phdr_type_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100228
David Srbecky6d8c8f02015-10-26 10:57:09 +0000229 friend class ElfBuilder;
David Srbecky4d247f72015-11-09 11:56:52 +0000230
231 DISALLOW_COPY_AND_ASSIGN(Section);
David Srbecky0c5bbc12015-04-28 17:54:52 +0100232 };
233
Vladimir Marko944da602016-02-19 12:27:55 +0000234 class CachedSection : public Section {
235 public:
236 CachedSection(ElfBuilder<ElfTypes>* owner,
237 const std::string& name,
238 Elf_Word type,
239 Elf_Word flags,
240 const Section* link,
241 Elf_Word info,
242 Elf_Word align,
243 Elf_Word entsize)
244 : Section(owner, name, type, flags, link, info, align, entsize), cache_() { }
245
246 Elf_Word Add(const void* data, size_t length) {
247 Elf_Word offset = cache_.size();
248 const uint8_t* d = reinterpret_cast<const uint8_t*>(data);
249 cache_.insert(cache_.end(), d, d + length);
250 return offset;
251 }
252
253 Elf_Word GetCacheSize() {
254 return cache_.size();
255 }
256
257 void Write() {
258 this->WriteFully(cache_.data(), cache_.size());
259 cache_.clear();
260 cache_.shrink_to_fit();
261 }
262
263 void WriteCachedSection() {
264 this->Start();
265 Write();
266 this->End();
267 }
268
269 private:
270 std::vector<uint8_t> cache_;
271 };
272
273 // Writer of .dynstr section.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100274 class CachedStringSection final : public CachedSection {
Vladimir Marko944da602016-02-19 12:27:55 +0000275 public:
276 CachedStringSection(ElfBuilder<ElfTypes>* owner,
277 const std::string& name,
278 Elf_Word flags,
279 Elf_Word align)
280 : CachedSection(owner,
281 name,
282 SHT_STRTAB,
283 flags,
284 /* link */ nullptr,
285 /* info */ 0,
286 align,
287 /* entsize */ 0) { }
288
289 Elf_Word Add(const std::string& name) {
290 if (CachedSection::GetCacheSize() == 0u) {
291 DCHECK(name.empty());
292 }
293 return CachedSection::Add(name.c_str(), name.length() + 1);
294 }
295 };
296
297 // Writer of .strtab and .shstrtab sections.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100298 class StringSection final : public Section {
David Srbeckybc90fd02015-04-22 19:40:27 +0100299 public:
Vladimir Marko944da602016-02-19 12:27:55 +0000300 StringSection(ElfBuilder<ElfTypes>* owner,
301 const std::string& name,
302 Elf_Word flags,
303 Elf_Word align)
304 : Section(owner,
305 name,
306 SHT_STRTAB,
307 flags,
308 /* link */ nullptr,
309 /* info */ 0,
310 align,
David Srbeckyde91fd42018-07-05 22:27:08 +0100311 /* entsize */ 0) {
312 Reset();
313 }
314
315 void Reset() {
316 current_offset_ = 0;
317 last_name_ = "";
318 last_offset_ = 0;
David Srbecky0c5bbc12015-04-28 17:54:52 +0100319 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100320
David Srbecky6d8c8f02015-10-26 10:57:09 +0000321 Elf_Word Write(const std::string& name) {
322 if (current_offset_ == 0) {
323 DCHECK(name.empty());
David Srbecky3f427c42018-02-05 15:49:10 +0000324 } else if (name == last_name_) {
325 return last_offset_; // Very simple string de-duplication.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000326 }
David Srbecky3f427c42018-02-05 15:49:10 +0000327 last_name_ = name;
328 last_offset_ = current_offset_;
329 this->WriteFully(name.c_str(), name.length() + 1);
330 current_offset_ += name.length() + 1;
331 return last_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100332 }
333
David Srbeckybc90fd02015-04-22 19:40:27 +0100334 private:
David Srbecky6d8c8f02015-10-26 10:57:09 +0000335 Elf_Word current_offset_;
David Srbecky3f427c42018-02-05 15:49:10 +0000336 std::string last_name_;
337 Elf_Word last_offset_;
David Srbeckybc90fd02015-04-22 19:40:27 +0100338 };
339
David Srbeckybc90fd02015-04-22 19:40:27 +0100340 // Writer of .dynsym and .symtab sections.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100341 class SymbolSection final : public Section {
David Srbecky0c5bbc12015-04-28 17:54:52 +0100342 public:
Vladimir Marko944da602016-02-19 12:27:55 +0000343 SymbolSection(ElfBuilder<ElfTypes>* owner,
344 const std::string& name,
345 Elf_Word type,
346 Elf_Word flags,
347 Section* strtab)
David Srbecky32210b92017-12-04 14:39:21 +0000348 : Section(owner,
349 name,
350 type,
351 flags,
352 strtab,
David Srbeckyd2645a32018-02-16 16:16:39 +0000353 /* info */ 1,
David Srbecky32210b92017-12-04 14:39:21 +0000354 sizeof(Elf_Off),
355 sizeof(Elf_Sym)) {
356 syms_.push_back(Elf_Sym()); // The symbol table always has to start with NULL symbol.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000357 }
358
359 // Buffer symbol for this section. It will be written later.
David Srbecky5cc349f2015-12-18 15:04:48 +0000360 // If the symbol's section is null, it will be considered absolute (SHN_ABS).
361 // (we use this in JIT to reference code which is stored outside the debug ELF file)
Vladimir Marko944da602016-02-19 12:27:55 +0000362 void Add(Elf_Word name,
363 const Section* section,
364 Elf_Addr addr,
Vladimir Marko944da602016-02-19 12:27:55 +0000365 Elf_Word size,
366 uint8_t binding,
David Srbecky197160d2016-03-07 17:33:57 +0000367 uint8_t type) {
368 Elf_Word section_index;
369 if (section != nullptr) {
370 DCHECK_LE(section->GetAddress(), addr);
David Srbeckye155f4b2017-12-06 15:18:38 +0000371 DCHECK_LE(addr, section->GetAddress() + section->header_.sh_size);
David Srbecky197160d2016-03-07 17:33:57 +0000372 section_index = section->GetSectionIndex();
373 } else {
374 section_index = static_cast<Elf_Word>(SHN_ABS);
375 }
376 Add(name, section_index, addr, size, binding, type);
Vladimir Marko944da602016-02-19 12:27:55 +0000377 }
378
David Srbecky32210b92017-12-04 14:39:21 +0000379 // Buffer symbol for this section. It will be written later.
Vladimir Marko944da602016-02-19 12:27:55 +0000380 void Add(Elf_Word name,
381 Elf_Word section_index,
382 Elf_Addr addr,
383 Elf_Word size,
384 uint8_t binding,
David Srbecky197160d2016-03-07 17:33:57 +0000385 uint8_t type) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000386 Elf_Sym sym = Elf_Sym();
387 sym.st_name = name;
Vladimir Marko944da602016-02-19 12:27:55 +0000388 sym.st_value = addr;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000389 sym.st_size = size;
David Srbecky197160d2016-03-07 17:33:57 +0000390 sym.st_other = 0;
Vladimir Marko944da602016-02-19 12:27:55 +0000391 sym.st_shndx = section_index;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000392 sym.st_info = (binding << 4) + (type & 0xf);
David Srbecky32210b92017-12-04 14:39:21 +0000393 syms_.push_back(sym);
David Srbeckyd2645a32018-02-16 16:16:39 +0000394
395 // The sh_info file must be set to index one-past the last local symbol.
396 if (binding == STB_LOCAL) {
397 this->header_.sh_info = syms_.size();
398 }
David Srbecky0c5bbc12015-04-28 17:54:52 +0100399 }
David Srbecky32210b92017-12-04 14:39:21 +0000400
401 Elf_Word GetCacheSize() { return syms_.size() * sizeof(Elf_Sym); }
402
403 void WriteCachedSection() {
404 this->Start();
405 this->WriteFully(syms_.data(), syms_.size() * sizeof(Elf_Sym));
406 this->End();
407 }
408
409 private:
410 std::vector<Elf_Sym> syms_; // Buffered/cached content of the whole section.
David Srbeckybc90fd02015-04-22 19:40:27 +0100411 };
412
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100413 class AbiflagsSection final : public Section {
Douglas Leung316a2182015-09-17 15:26:25 -0700414 public:
415 // Section with Mips abiflag info.
416 static constexpr uint8_t MIPS_AFL_REG_NONE = 0; // no registers
417 static constexpr uint8_t MIPS_AFL_REG_32 = 1; // 32-bit registers
418 static constexpr uint8_t MIPS_AFL_REG_64 = 2; // 64-bit registers
419 static constexpr uint32_t MIPS_AFL_FLAGS1_ODDSPREG = 1; // Uses odd single-prec fp regs
420 static constexpr uint8_t MIPS_ABI_FP_DOUBLE = 1; // -mdouble-float
421 static constexpr uint8_t MIPS_ABI_FP_XX = 5; // -mfpxx
422 static constexpr uint8_t MIPS_ABI_FP_64A = 7; // -mips32r* -mfp64 -mno-odd-spreg
423
424 AbiflagsSection(ElfBuilder<ElfTypes>* owner,
425 const std::string& name,
426 Elf_Word type,
427 Elf_Word flags,
428 const Section* link,
429 Elf_Word info,
430 Elf_Word align,
431 Elf_Word entsize,
432 InstructionSet isa,
433 const InstructionSetFeatures* features)
434 : Section(owner, name, type, flags, link, info, align, entsize) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000435 if (isa == InstructionSet::kMips || isa == InstructionSet::kMips64) {
Douglas Leung316a2182015-09-17 15:26:25 -0700436 bool fpu32 = false; // assume mips64 values
437 uint8_t isa_rev = 6; // assume mips64 values
Vladimir Marko33bff252017-11-01 14:35:42 +0000438 if (isa == InstructionSet::kMips) {
Douglas Leung316a2182015-09-17 15:26:25 -0700439 // adjust for mips32 values
440 fpu32 = features->AsMipsInstructionSetFeatures()->Is32BitFloatingPoint();
441 isa_rev = features->AsMipsInstructionSetFeatures()->IsR6()
442 ? 6
443 : features->AsMipsInstructionSetFeatures()->IsMipsIsaRevGreaterThanEqual2()
444 ? (fpu32 ? 2 : 5)
445 : 1;
446 }
447 abiflags_.version = 0; // version of flags structure
Vladimir Marko33bff252017-11-01 14:35:42 +0000448 abiflags_.isa_level = (isa == InstructionSet::kMips) ? 32 : 64;
Douglas Leung316a2182015-09-17 15:26:25 -0700449 abiflags_.isa_rev = isa_rev;
Vladimir Marko33bff252017-11-01 14:35:42 +0000450 abiflags_.gpr_size = (isa == InstructionSet::kMips) ? MIPS_AFL_REG_32 : MIPS_AFL_REG_64;
Douglas Leung316a2182015-09-17 15:26:25 -0700451 abiflags_.cpr1_size = fpu32 ? MIPS_AFL_REG_32 : MIPS_AFL_REG_64;
452 abiflags_.cpr2_size = MIPS_AFL_REG_NONE;
453 // Set the fp_abi to MIPS_ABI_FP_64A for mips32 with 64-bit FPUs (ie: mips32 R5 and R6).
454 // Otherwise set to MIPS_ABI_FP_DOUBLE.
Vladimir Marko33bff252017-11-01 14:35:42 +0000455 abiflags_.fp_abi =
456 (isa == InstructionSet::kMips && !fpu32) ? MIPS_ABI_FP_64A : MIPS_ABI_FP_DOUBLE;
Douglas Leung316a2182015-09-17 15:26:25 -0700457 abiflags_.isa_ext = 0;
458 abiflags_.ases = 0;
459 // To keep the code simple, we are not using odd FP reg for single floats for both
460 // mips32 and mips64 ART. Therefore we are not setting the MIPS_AFL_FLAGS1_ODDSPREG bit.
461 abiflags_.flags1 = 0;
462 abiflags_.flags2 = 0;
463 }
464 }
465
466 Elf_Word GetSize() const {
467 return sizeof(abiflags_);
468 }
469
470 void Write() {
471 this->WriteFully(&abiflags_, sizeof(abiflags_));
472 }
473
474 private:
475 struct {
476 uint16_t version; // version of this structure
477 uint8_t isa_level, isa_rev, gpr_size, cpr1_size, cpr2_size;
478 uint8_t fp_abi;
479 uint32_t isa_ext, ases, flags1, flags2;
480 } abiflags_;
481 };
482
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100483 class BuildIdSection final : public Section {
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700484 public:
485 BuildIdSection(ElfBuilder<ElfTypes>* owner,
486 const std::string& name,
487 Elf_Word type,
488 Elf_Word flags,
489 const Section* link,
490 Elf_Word info,
491 Elf_Word align,
492 Elf_Word entsize)
493 : Section(owner, name, type, flags, link, info, align, entsize),
494 digest_start_(-1) {
495 }
496
David Srbeckye155f4b2017-12-06 15:18:38 +0000497 Elf_Word GetSize() {
498 return 16 + kBuildIdLen;
499 }
500
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700501 void Write() {
502 // The size fields are 32-bit on both 32-bit and 64-bit systems, confirmed
503 // with the 64-bit linker and libbfd code. The size of name and desc must
504 // be a multiple of 4 and it currently is.
505 this->WriteUint32(4); // namesz.
506 this->WriteUint32(kBuildIdLen); // descsz.
507 this->WriteUint32(3); // type = NT_GNU_BUILD_ID.
508 this->WriteFully("GNU", 4); // name.
509 digest_start_ = this->Seek(0, kSeekCurrent);
510 static_assert(kBuildIdLen % 4 == 0, "expecting a mutliple of 4 for build ID length");
511 this->WriteFully(std::string(kBuildIdLen, '\0').c_str(), kBuildIdLen); // desc.
David Srbeckye155f4b2017-12-06 15:18:38 +0000512 DCHECK_EQ(this->GetPosition(), GetSize());
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700513 }
514
515 off_t GetDigestStart() {
516 CHECK_GT(digest_start_, 0);
517 return digest_start_;
518 }
519
520 private:
521 bool WriteUint32(uint32_t v) {
522 return this->WriteFully(&v, sizeof(v));
523 }
524
525 // File offset where the build ID digest starts.
526 // Populated with zeros first, then updated with the actual value as the
527 // very last thing in the output file creation.
528 off_t digest_start_;
529 };
530
David Srbecky5d811202016-03-08 13:21:22 +0000531 ElfBuilder(InstructionSet isa, const InstructionSetFeatures* features, OutputStream* output)
Vladimir Marko131980f2015-12-03 18:29:23 +0000532 : isa_(isa),
David Srbecky5d811202016-03-08 13:21:22 +0000533 features_(features),
Vladimir Marko131980f2015-12-03 18:29:23 +0000534 stream_(output),
535 rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
536 text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
Vladimir Markob066d432018-01-03 13:14:37 +0000537 data_bimg_rel_ro_(
538 this, ".data.bimg.rel.ro", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
Vladimir Marko131980f2015-12-03 18:29:23 +0000539 bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000540 dex_(this, ".dex", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
Vladimir Marko131980f2015-12-03 18:29:23 +0000541 dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
542 dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
543 hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
544 dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
545 eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
546 eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
David Srbecky579942f2016-01-28 20:01:28 +0000547 strtab_(this, ".strtab", 0, 1),
Vladimir Marko131980f2015-12-03 18:29:23 +0000548 symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
549 debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
550 debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
551 debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
552 shstrtab_(this, ".shstrtab", 0, 1),
Douglas Leung316a2182015-09-17 15:26:25 -0700553 abiflags_(this, ".MIPS.abiflags", SHT_MIPS_ABIFLAGS, SHF_ALLOC, nullptr, 0, kPageSize, 0,
554 isa, features),
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700555 build_id_(this, ".note.gnu.build-id", SHT_NOTE, SHF_ALLOC, nullptr, 0, 4, 0),
David Srbeckye155f4b2017-12-06 15:18:38 +0000556 current_section_(nullptr),
David Srbecky579942f2016-01-28 20:01:28 +0000557 started_(false),
David Srbeckyde91fd42018-07-05 22:27:08 +0100558 finished_(false),
Vladimir Marko944da602016-02-19 12:27:55 +0000559 write_program_headers_(false),
560 loaded_size_(0u),
Vladimir Marko131980f2015-12-03 18:29:23 +0000561 virtual_address_(0) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000562 text_.phdr_flags_ = PF_R | PF_X;
Vladimir Markob066d432018-01-03 13:14:37 +0000563 data_bimg_rel_ro_.phdr_flags_ = PF_R | PF_W; // Shall be made read-only at run time.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000564 bss_.phdr_flags_ = PF_R | PF_W;
David Srbeckyec2cdf42017-12-08 16:21:25 +0000565 dex_.phdr_flags_ = PF_R;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000566 dynamic_.phdr_flags_ = PF_R | PF_W;
567 dynamic_.phdr_type_ = PT_DYNAMIC;
568 eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
Douglas Leung316a2182015-09-17 15:26:25 -0700569 abiflags_.phdr_type_ = PT_MIPS_ABIFLAGS;
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700570 build_id_.phdr_type_ = PT_NOTE;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700571 }
572 ~ElfBuilder() {}
573
David Srbecky6d8c8f02015-10-26 10:57:09 +0000574 InstructionSet GetIsa() { return isa_; }
David Srbeckye155f4b2017-12-06 15:18:38 +0000575 BuildIdSection* GetBuildId() { return &build_id_; }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000576 Section* GetRoData() { return &rodata_; }
577 Section* GetText() { return &text_; }
Vladimir Markob066d432018-01-03 13:14:37 +0000578 Section* GetDataBimgRelRo() { return &data_bimg_rel_ro_; }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000579 Section* GetBss() { return &bss_; }
David Srbeckyec2cdf42017-12-08 16:21:25 +0000580 Section* GetDex() { return &dex_; }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000581 StringSection* GetStrTab() { return &strtab_; }
582 SymbolSection* GetSymTab() { return &symtab_; }
583 Section* GetEhFrame() { return &eh_frame_; }
584 Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
585 Section* GetDebugFrame() { return &debug_frame_; }
David Srbeckyb851b492015-11-11 20:19:38 +0000586 Section* GetDebugInfo() { return &debug_info_; }
587 Section* GetDebugLine() { return &debug_line_; }
Ian Rogers0279ebb2014-10-08 17:27:48 -0700588
David Srbecky6d8c8f02015-10-26 10:57:09 +0000589 // Encode patch locations as LEB128 list of deltas between consecutive addresses.
590 // (exposed publicly for tests)
Vladimir Marko10c13562015-11-25 14:33:36 +0000591 static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
David Srbecky6d8c8f02015-10-26 10:57:09 +0000592 std::vector<uint8_t>* buffer) {
593 buffer->reserve(buffer->size() + locations.size() * 2); // guess 2 bytes per ULEB128.
594 uintptr_t address = 0; // relative to start of section.
595 for (uintptr_t location : locations) {
596 DCHECK_GE(location, address) << "Patch locations are not in sorted order";
597 EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
598 address = location;
599 }
600 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700601
Vladimir Marko10c13562015-11-25 14:33:36 +0000602 void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000603 std::vector<uint8_t> buffer;
Vladimir Marko10c13562015-11-25 14:33:36 +0000604 EncodeOatPatches(patch_locations, &buffer);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000605 std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
606 s->Start();
607 s->WriteFully(buffer.data(), buffer.size());
608 s->End();
609 other_sections_.push_back(std::move(s));
610 }
David Srbecky527c9c72015-04-17 21:14:10 +0100611
David Srbecky6d8c8f02015-10-26 10:57:09 +0000612 void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
613 std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
614 s->Start();
615 s->WriteFully(buffer->data(), buffer->size());
616 s->End();
617 other_sections_.push_back(std::move(s));
618 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700619
David Srbecky579942f2016-01-28 20:01:28 +0000620 // Reserve space for ELF header and program headers.
621 // We do not know the number of headers until later, so
622 // it is easiest to just reserve a fixed amount of space.
623 // Program headers are required for loading by the linker.
624 // It is possible to omit them for ELF files used for debugging.
625 void Start(bool write_program_headers = true) {
626 int size = sizeof(Elf_Ehdr);
627 if (write_program_headers) {
628 size += sizeof(Elf_Phdr) * kMaxProgramHeaders;
629 }
Vladimir Marko131980f2015-12-03 18:29:23 +0000630 stream_.Seek(size, kSeekSet);
David Srbecky579942f2016-01-28 20:01:28 +0000631 started_ = true;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000632 virtual_address_ += size;
David Srbecky579942f2016-01-28 20:01:28 +0000633 write_program_headers_ = write_program_headers;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000634 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700635
David Srbeckyde91fd42018-07-05 22:27:08 +0100636 off_t End() {
David Srbecky579942f2016-01-28 20:01:28 +0000637 DCHECK(started_);
David Srbeckyde91fd42018-07-05 22:27:08 +0100638 DCHECK(!finished_);
639 finished_ = true;
David Srbecky579942f2016-01-28 20:01:28 +0000640
Vladimir Marko944da602016-02-19 12:27:55 +0000641 // Note: loaded_size_ == 0 for tests that don't write .rodata, .text, .bss,
642 // .dynstr, dynsym, .hash and .dynamic. These tests should not read loaded_size_.
643 // TODO: Either refactor the .eh_frame creation so that it counts towards loaded_size_,
644 // or remove all support for .eh_frame. (The currently unused .eh_frame counts towards
645 // the virtual_address_ but we don't consider it for loaded_size_.)
646 CHECK(loaded_size_ == 0 || loaded_size_ == RoundUp(virtual_address_, kPageSize))
647 << loaded_size_ << " " << virtual_address_;
648
David Srbecky6d8c8f02015-10-26 10:57:09 +0000649 // Write section names and finish the section headers.
650 shstrtab_.Start();
651 shstrtab_.Write("");
652 for (auto* section : sections_) {
653 section->header_.sh_name = shstrtab_.Write(section->name_);
654 if (section->link_ != nullptr) {
655 section->header_.sh_link = section->link_->GetSectionIndex();
David Srbeckyb0a962c2015-04-28 19:43:56 +0100656 }
David Srbeckye155f4b2017-12-06 15:18:38 +0000657 if (section->header_.sh_offset == 0) {
658 section->header_.sh_type = SHT_NOBITS;
659 }
David Srbecky527c9c72015-04-17 21:14:10 +0100660 }
David Srbecky6d8c8f02015-10-26 10:57:09 +0000661 shstrtab_.End();
David Srbecky527c9c72015-04-17 21:14:10 +0100662
David Srbecky6d8c8f02015-10-26 10:57:09 +0000663 // Write section headers at the end of the ELF file.
664 std::vector<Elf_Shdr> shdrs;
665 shdrs.reserve(1u + sections_.size());
666 shdrs.push_back(Elf_Shdr()); // NULL at index 0.
667 for (auto* section : sections_) {
668 shdrs.push_back(section->header_);
669 }
670 Elf_Off section_headers_offset;
David Srbecky579942f2016-01-28 20:01:28 +0000671 section_headers_offset = AlignFileOffset(sizeof(Elf_Off));
Vladimir Marko131980f2015-12-03 18:29:23 +0000672 stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
David Srbeckyde91fd42018-07-05 22:27:08 +0100673 off_t file_size = stream_.Seek(0, kSeekCurrent);
Vladimir Marko131980f2015-12-03 18:29:23 +0000674
675 // Flush everything else before writing the program headers. This should prevent
676 // the OS from reordering writes, so that we don't end up with valid headers
677 // and partially written data if we suddenly lose power, for example.
678 stream_.Flush();
David Srbecky6d8c8f02015-10-26 10:57:09 +0000679
David Srbecky579942f2016-01-28 20:01:28 +0000680 // The main ELF header.
Douglas Leung316a2182015-09-17 15:26:25 -0700681 Elf_Ehdr elf_header = MakeElfHeader(isa_, features_);
David Srbeckybc90fd02015-04-22 19:40:27 +0100682 elf_header.e_shoff = section_headers_offset;
David Srbecky6d8c8f02015-10-26 10:57:09 +0000683 elf_header.e_shnum = shdrs.size();
David Srbeckybc90fd02015-04-22 19:40:27 +0100684 elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
David Srbecky579942f2016-01-28 20:01:28 +0000685
686 // Program headers (i.e. mmap instructions).
687 std::vector<Elf_Phdr> phdrs;
688 if (write_program_headers_) {
689 phdrs = MakeProgramHeaders();
690 CHECK_LE(phdrs.size(), kMaxProgramHeaders);
691 elf_header.e_phoff = sizeof(Elf_Ehdr);
692 elf_header.e_phnum = phdrs.size();
693 }
694
Vladimir Marko131980f2015-12-03 18:29:23 +0000695 stream_.Seek(0, kSeekSet);
696 stream_.WriteFully(&elf_header, sizeof(elf_header));
697 stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
698 stream_.Flush();
David Srbeckyde91fd42018-07-05 22:27:08 +0100699
700 return file_size;
701 }
702
703 // This has the same effect as running the "strip" command line tool.
704 // It removes all debugging sections (but it keeps mini-debug-info).
705 // It returns the ELF file size (as the caller needs to truncate it).
706 off_t Strip() {
707 DCHECK(finished_);
708 finished_ = false;
709 Elf_Off end = 0;
710 std::vector<Section*> non_debug_sections;
711 for (Section* section : sections_) {
712 if (section == &shstrtab_ || // Section names will be recreated.
713 section == &symtab_ ||
714 section == &strtab_ ||
715 section->name_.find(".debug_") == 0) {
716 section->header_.sh_offset = 0;
717 section->header_.sh_size = 0;
718 section->section_index_ = 0;
719 } else {
720 if (section->header_.sh_type != SHT_NOBITS) {
721 DCHECK_LE(section->header_.sh_offset, end + kPageSize) << "Large gap between sections";
722 end = std::max<off_t>(end, section->header_.sh_offset + section->header_.sh_size);
723 }
724 non_debug_sections.push_back(section);
725 }
726 }
727 shstrtab_.Reset();
728 // Write the non-debug section headers, program headers, and ELF header again.
729 sections_ = std::move(non_debug_sections);
730 stream_.Seek(end, kSeekSet);
731 return End();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700732 }
733
David Srbecky6d8c8f02015-10-26 10:57:09 +0000734 // The running program does not have access to section headers
735 // and the loader is not supposed to use them either.
736 // The dynamic sections therefore replicates some of the layout
737 // information like the address and size of .rodata and .text.
738 // It also contains other metadata like the SONAME.
739 // The .dynamic section is found using the PT_DYNAMIC program header.
Vladimir Marko944da602016-02-19 12:27:55 +0000740 void PrepareDynamicSection(const std::string& elf_file_path,
741 Elf_Word rodata_size,
742 Elf_Word text_size,
Vladimir Markob066d432018-01-03 13:14:37 +0000743 Elf_Word data_bimg_rel_ro_size,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000744 Elf_Word bss_size,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100745 Elf_Word bss_methods_offset,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000746 Elf_Word bss_roots_offset,
747 Elf_Word dex_size) {
David Srbecky6d8c8f02015-10-26 10:57:09 +0000748 std::string soname(elf_file_path);
749 size_t directory_separator_pos = soname.rfind('/');
750 if (directory_separator_pos != std::string::npos) {
751 soname = soname.substr(directory_separator_pos + 1);
752 }
753
David Srbeckye155f4b2017-12-06 15:18:38 +0000754 // Allocate all pre-dynamic sections.
755 rodata_.AllocateVirtualMemory(rodata_size);
756 text_.AllocateVirtualMemory(text_size);
Vladimir Markob066d432018-01-03 13:14:37 +0000757 if (data_bimg_rel_ro_size != 0) {
758 data_bimg_rel_ro_.AllocateVirtualMemory(data_bimg_rel_ro_size);
759 }
David Srbeckye155f4b2017-12-06 15:18:38 +0000760 if (bss_size != 0) {
761 bss_.AllocateVirtualMemory(bss_size);
Douglas Leung316a2182015-09-17 15:26:25 -0700762 }
David Srbeckyec2cdf42017-12-08 16:21:25 +0000763 if (dex_size != 0) {
764 dex_.AllocateVirtualMemory(dex_size);
765 }
David Srbeckye155f4b2017-12-06 15:18:38 +0000766 if (isa_ == InstructionSet::kMips || isa_ == InstructionSet::kMips64) {
767 abiflags_.AllocateVirtualMemory(abiflags_.GetSize());
768 }
Vladimir Marko45724f92016-02-17 17:46:10 +0000769
Vladimir Marko944da602016-02-19 12:27:55 +0000770 // Cache .dynstr, .dynsym and .hash data.
771 dynstr_.Add(""); // dynstr should start with empty string.
Vladimir Marko944da602016-02-19 12:27:55 +0000772 Elf_Word oatdata = dynstr_.Add("oatdata");
David Srbeckye155f4b2017-12-06 15:18:38 +0000773 dynsym_.Add(oatdata, &rodata_, rodata_.GetAddress(), rodata_size, STB_GLOBAL, STT_OBJECT);
Vladimir Marko944da602016-02-19 12:27:55 +0000774 if (text_size != 0u) {
David Srbeckya310f442018-02-19 12:33:36 +0000775 // The runtime does not care about the size of this symbol (it uses the "lastword" symbol).
776 // We use size 0 (meaning "unknown size" in ELF) to prevent overlap with the debug symbols.
Vladimir Marko944da602016-02-19 12:27:55 +0000777 Elf_Word oatexec = dynstr_.Add("oatexec");
David Srbeckya310f442018-02-19 12:33:36 +0000778 dynsym_.Add(oatexec, &text_, text_.GetAddress(), /* size */ 0, STB_GLOBAL, STT_OBJECT);
Vladimir Marko944da602016-02-19 12:27:55 +0000779 Elf_Word oatlastword = dynstr_.Add("oatlastword");
David Srbeckye155f4b2017-12-06 15:18:38 +0000780 Elf_Word oatlastword_address = text_.GetAddress() + text_size - 4;
781 dynsym_.Add(oatlastword, &text_, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
Vladimir Marko944da602016-02-19 12:27:55 +0000782 } else if (rodata_size != 0) {
783 // rodata_ can be size 0 for dwarf_test.
784 Elf_Word oatlastword = dynstr_.Add("oatlastword");
David Srbeckye155f4b2017-12-06 15:18:38 +0000785 Elf_Word oatlastword_address = rodata_.GetAddress() + rodata_size - 4;
786 dynsym_.Add(oatlastword, &rodata_, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
Vladimir Marko944da602016-02-19 12:27:55 +0000787 }
Vladimir Markob066d432018-01-03 13:14:37 +0000788 if (data_bimg_rel_ro_size != 0u) {
789 Elf_Word oatdatabimgrelro = dynstr_.Add("oatdatabimgrelro");
790 dynsym_.Add(oatdatabimgrelro,
791 &data_bimg_rel_ro_,
792 data_bimg_rel_ro_.GetAddress(),
793 data_bimg_rel_ro_size,
794 STB_GLOBAL,
795 STT_OBJECT);
796 Elf_Word oatdatabimgrelrolastword = dynstr_.Add("oatdatabimgrelrolastword");
797 Elf_Word oatdatabimgrelrolastword_address =
798 data_bimg_rel_ro_.GetAddress() + data_bimg_rel_ro_size - 4;
799 dynsym_.Add(oatdatabimgrelrolastword,
800 &data_bimg_rel_ro_,
801 oatdatabimgrelrolastword_address,
802 4,
803 STB_GLOBAL,
804 STT_OBJECT);
805 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000806 DCHECK_LE(bss_roots_offset, bss_size);
Vladimir Marko944da602016-02-19 12:27:55 +0000807 if (bss_size != 0u) {
Vladimir Marko944da602016-02-19 12:27:55 +0000808 Elf_Word oatbss = dynstr_.Add("oatbss");
David Srbeckye155f4b2017-12-06 15:18:38 +0000809 dynsym_.Add(oatbss, &bss_, bss_.GetAddress(), bss_roots_offset, STB_GLOBAL, STT_OBJECT);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100810 DCHECK_LE(bss_methods_offset, bss_roots_offset);
811 DCHECK_LE(bss_roots_offset, bss_size);
812 // Add a symbol marking the start of the methods part of the .bss, if not empty.
813 if (bss_methods_offset != bss_roots_offset) {
David Srbeckye155f4b2017-12-06 15:18:38 +0000814 Elf_Word bss_methods_address = bss_.GetAddress() + bss_methods_offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100815 Elf_Word bss_methods_size = bss_roots_offset - bss_methods_offset;
816 Elf_Word oatbssroots = dynstr_.Add("oatbssmethods");
817 dynsym_.Add(
David Srbeckye155f4b2017-12-06 15:18:38 +0000818 oatbssroots, &bss_, bss_methods_address, bss_methods_size, STB_GLOBAL, STT_OBJECT);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100819 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000820 // Add a symbol marking the start of the GC roots part of the .bss, if not empty.
821 if (bss_roots_offset != bss_size) {
David Srbeckye155f4b2017-12-06 15:18:38 +0000822 Elf_Word bss_roots_address = bss_.GetAddress() + bss_roots_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +0000823 Elf_Word bss_roots_size = bss_size - bss_roots_offset;
824 Elf_Word oatbssroots = dynstr_.Add("oatbssroots");
825 dynsym_.Add(
David Srbeckye155f4b2017-12-06 15:18:38 +0000826 oatbssroots, &bss_, bss_roots_address, bss_roots_size, STB_GLOBAL, STT_OBJECT);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000827 }
Vladimir Marko944da602016-02-19 12:27:55 +0000828 Elf_Word oatbsslastword = dynstr_.Add("oatbsslastword");
David Srbeckye155f4b2017-12-06 15:18:38 +0000829 Elf_Word bsslastword_address = bss_.GetAddress() + bss_size - 4;
830 dynsym_.Add(oatbsslastword, &bss_, bsslastword_address, 4, STB_GLOBAL, STT_OBJECT);
Vladimir Marko944da602016-02-19 12:27:55 +0000831 }
David Srbeckyec2cdf42017-12-08 16:21:25 +0000832 if (dex_size != 0u) {
833 Elf_Word oatdex = dynstr_.Add("oatdex");
David Srbeckya310f442018-02-19 12:33:36 +0000834 dynsym_.Add(oatdex, &dex_, dex_.GetAddress(), /* size */ 0, STB_GLOBAL, STT_OBJECT);
David Srbeckyec2cdf42017-12-08 16:21:25 +0000835 Elf_Word oatdexlastword = dynstr_.Add("oatdexlastword");
836 Elf_Word oatdexlastword_address = dex_.GetAddress() + dex_size - 4;
837 dynsym_.Add(oatdexlastword, &dex_, oatdexlastword_address, 4, STB_GLOBAL, STT_OBJECT);
838 }
839
Vladimir Marko944da602016-02-19 12:27:55 +0000840 Elf_Word soname_offset = dynstr_.Add(soname);
David Srbecky6d8c8f02015-10-26 10:57:09 +0000841
842 // We do not really need a hash-table since there is so few entries.
843 // However, the hash-table is the only way the linker can actually
844 // determine the number of symbols in .dynsym so it is required.
Vladimir Marko944da602016-02-19 12:27:55 +0000845 int count = dynsym_.GetCacheSize() / sizeof(Elf_Sym); // Includes NULL.
David Srbecky6d8c8f02015-10-26 10:57:09 +0000846 std::vector<Elf_Word> hash;
847 hash.push_back(1); // Number of buckets.
848 hash.push_back(count); // Number of chains.
849 // Buckets. Having just one makes it linear search.
850 hash.push_back(1); // Point to first non-NULL symbol.
851 // Chains. This creates linked list of symbols.
852 hash.push_back(0); // Dummy entry for the NULL symbol.
853 for (int i = 1; i < count - 1; i++) {
854 hash.push_back(i + 1); // Each symbol points to the next one.
855 }
856 hash.push_back(0); // Last symbol terminates the chain.
Vladimir Marko944da602016-02-19 12:27:55 +0000857 hash_.Add(hash.data(), hash.size() * sizeof(hash[0]));
David Srbecky6d8c8f02015-10-26 10:57:09 +0000858
David Srbeckye155f4b2017-12-06 15:18:38 +0000859 // Allocate all remaining sections.
860 dynstr_.AllocateVirtualMemory(dynstr_.GetCacheSize());
861 dynsym_.AllocateVirtualMemory(dynsym_.GetCacheSize());
862 hash_.AllocateVirtualMemory(hash_.GetCacheSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000863
David Srbecky6d8c8f02015-10-26 10:57:09 +0000864 Elf_Dyn dyns[] = {
David Srbeckye155f4b2017-12-06 15:18:38 +0000865 { DT_HASH, { hash_.GetAddress() } },
866 { DT_STRTAB, { dynstr_.GetAddress() } },
867 { DT_SYMTAB, { dynsym_.GetAddress() } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000868 { DT_SYMENT, { sizeof(Elf_Sym) } },
Vladimir Marko944da602016-02-19 12:27:55 +0000869 { DT_STRSZ, { dynstr_.GetCacheSize() } },
David Srbecky6d8c8f02015-10-26 10:57:09 +0000870 { DT_SONAME, { soname_offset } },
871 { DT_NULL, { 0 } },
872 };
Vladimir Marko944da602016-02-19 12:27:55 +0000873 dynamic_.Add(&dyns, sizeof(dyns));
David Srbeckye155f4b2017-12-06 15:18:38 +0000874 dynamic_.AllocateVirtualMemory(dynamic_.GetCacheSize());
Vladimir Marko944da602016-02-19 12:27:55 +0000875
David Srbeckye155f4b2017-12-06 15:18:38 +0000876 loaded_size_ = RoundUp(virtual_address_, kPageSize);
Vladimir Marko944da602016-02-19 12:27:55 +0000877 }
878
879 void WriteDynamicSection() {
880 dynstr_.WriteCachedSection();
881 dynsym_.WriteCachedSection();
882 hash_.WriteCachedSection();
883 dynamic_.WriteCachedSection();
Vladimir Marko944da602016-02-19 12:27:55 +0000884 }
885
886 Elf_Word GetLoadedSize() {
887 CHECK_NE(loaded_size_, 0u);
888 return loaded_size_;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700889 }
890
Douglas Leung316a2182015-09-17 15:26:25 -0700891 void WriteMIPSabiflagsSection() {
892 abiflags_.Start();
893 abiflags_.Write();
894 abiflags_.End();
895 }
896
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700897 void WriteBuildIdSection() {
898 build_id_.Start();
899 build_id_.Write();
900 build_id_.End();
901 }
902
903 void WriteBuildId(uint8_t build_id[kBuildIdLen]) {
904 stream_.Seek(build_id_.GetDigestStart(), kSeekSet);
905 stream_.WriteFully(build_id, kBuildIdLen);
David Srbeckyde91fd42018-07-05 22:27:08 +0100906 stream_.Flush();
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700907 }
908
David Srbecky6d8c8f02015-10-26 10:57:09 +0000909 // Returns true if all writes and seeks on the output stream succeeded.
910 bool Good() {
Vladimir Marko131980f2015-12-03 18:29:23 +0000911 return stream_.Good();
912 }
913
914 // Returns the builder's internal stream.
915 OutputStream* GetStream() {
916 return &stream_;
David Srbecky527c9c72015-04-17 21:14:10 +0100917 }
918
David Srbecky579942f2016-01-28 20:01:28 +0000919 off_t AlignFileOffset(size_t alignment) {
920 return stream_.Seek(RoundUp(stream_.Seek(0, kSeekCurrent), alignment), kSeekSet);
921 }
922
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700923 private:
Douglas Leung316a2182015-09-17 15:26:25 -0700924 static Elf_Ehdr MakeElfHeader(InstructionSet isa, const InstructionSetFeatures* features) {
David Srbeckybc90fd02015-04-22 19:40:27 +0100925 Elf_Ehdr elf_header = Elf_Ehdr();
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700926 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000927 case InstructionSet::kArm:
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700928 // Fall through.
Vladimir Marko33bff252017-11-01 14:35:42 +0000929 case InstructionSet::kThumb2: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100930 elf_header.e_machine = EM_ARM;
931 elf_header.e_flags = EF_ARM_EABI_VER5;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700932 break;
933 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000934 case InstructionSet::kArm64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100935 elf_header.e_machine = EM_AARCH64;
936 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700937 break;
938 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000939 case InstructionSet::kX86: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100940 elf_header.e_machine = EM_386;
941 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700942 break;
943 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000944 case InstructionSet::kX86_64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100945 elf_header.e_machine = EM_X86_64;
946 elf_header.e_flags = 0;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700947 break;
948 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000949 case InstructionSet::kMips: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100950 elf_header.e_machine = EM_MIPS;
951 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700952 EF_MIPS_PIC |
953 EF_MIPS_CPIC |
954 EF_MIPS_ABI_O32 |
Greg Kaiser81a18992016-06-16 15:55:15 -0700955 (features->AsMipsInstructionSetFeatures()->IsR6()
956 ? EF_MIPS_ARCH_32R6
957 : EF_MIPS_ARCH_32R2));
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700958 break;
959 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000960 case InstructionSet::kMips64: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100961 elf_header.e_machine = EM_MIPS;
962 elf_header.e_flags = (EF_MIPS_NOREORDER |
Douglas Leung316a2182015-09-17 15:26:25 -0700963 EF_MIPS_PIC |
964 EF_MIPS_CPIC |
965 EF_MIPS_ARCH_64R6);
Andreas Gampe57b34292015-01-14 15:45:59 -0800966 break;
967 }
Vladimir Marko33bff252017-11-01 14:35:42 +0000968 case InstructionSet::kNone: {
David Srbeckybc90fd02015-04-22 19:40:27 +0100969 LOG(FATAL) << "No instruction set";
David Srbecky6d8c8f02015-10-26 10:57:09 +0000970 break;
971 }
972 default: {
973 LOG(FATAL) << "Unknown instruction set " << isa;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700974 }
975 }
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700976
David Srbeckybc90fd02015-04-22 19:40:27 +0100977 elf_header.e_ident[EI_MAG0] = ELFMAG0;
978 elf_header.e_ident[EI_MAG1] = ELFMAG1;
979 elf_header.e_ident[EI_MAG2] = ELFMAG2;
980 elf_header.e_ident[EI_MAG3] = ELFMAG3;
981 elf_header.e_ident[EI_CLASS] = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
Mathieu Chartier6beced42016-11-15 15:51:31 -0800982 ? ELFCLASS32 : ELFCLASS64;
David Srbeckybc90fd02015-04-22 19:40:27 +0100983 elf_header.e_ident[EI_DATA] = ELFDATA2LSB;
984 elf_header.e_ident[EI_VERSION] = EV_CURRENT;
985 elf_header.e_ident[EI_OSABI] = ELFOSABI_LINUX;
986 elf_header.e_ident[EI_ABIVERSION] = 0;
987 elf_header.e_type = ET_DYN;
988 elf_header.e_version = 1;
989 elf_header.e_entry = 0;
990 elf_header.e_ehsize = sizeof(Elf_Ehdr);
991 elf_header.e_phentsize = sizeof(Elf_Phdr);
992 elf_header.e_shentsize = sizeof(Elf_Shdr);
David Srbeckybc90fd02015-04-22 19:40:27 +0100993 return elf_header;
Andreas Gampe54fc26c2014-09-04 21:47:42 -0700994 }
995
David Srbecky6d8c8f02015-10-26 10:57:09 +0000996 // Create program headers based on written sections.
997 std::vector<Elf_Phdr> MakeProgramHeaders() {
998 CHECK(!sections_.empty());
999 std::vector<Elf_Phdr> phdrs;
1000 {
1001 // The program headers must start with PT_PHDR which is used in
1002 // loaded process to determine the number of program headers.
1003 Elf_Phdr phdr = Elf_Phdr();
1004 phdr.p_type = PT_PHDR;
1005 phdr.p_flags = PF_R;
1006 phdr.p_offset = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
1007 phdr.p_filesz = phdr.p_memsz = 0; // We need to fill this later.
1008 phdr.p_align = sizeof(Elf_Off);
1009 phdrs.push_back(phdr);
1010 // Tell the linker to mmap the start of file to memory.
1011 Elf_Phdr load = Elf_Phdr();
1012 load.p_type = PT_LOAD;
1013 load.p_flags = PF_R;
1014 load.p_offset = load.p_vaddr = load.p_paddr = 0;
David Srbecky2fdd03c2016-03-10 15:32:37 +00001015 load.p_filesz = load.p_memsz = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001016 load.p_align = kPageSize;
1017 phdrs.push_back(load);
David Srbeckybc90fd02015-04-22 19:40:27 +01001018 }
David Srbecky6d8c8f02015-10-26 10:57:09 +00001019 // Create program headers for sections.
1020 for (auto* section : sections_) {
1021 const Elf_Shdr& shdr = section->header_;
1022 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
David Srbeckye155f4b2017-12-06 15:18:38 +00001023 DCHECK(shdr.sh_addr != 0u) << "Allocate virtual memory for the section";
David Srbecky6d8c8f02015-10-26 10:57:09 +00001024 // PT_LOAD tells the linker to mmap part of the file.
1025 // The linker can only mmap page-aligned sections.
1026 // Single PT_LOAD may contain several ELF sections.
1027 Elf_Phdr& prev = phdrs.back();
1028 Elf_Phdr load = Elf_Phdr();
1029 load.p_type = PT_LOAD;
1030 load.p_flags = section->phdr_flags_;
1031 load.p_offset = shdr.sh_offset;
1032 load.p_vaddr = load.p_paddr = shdr.sh_addr;
1033 load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
1034 load.p_memsz = shdr.sh_size;
1035 load.p_align = shdr.sh_addralign;
1036 if (prev.p_type == load.p_type &&
1037 prev.p_flags == load.p_flags &&
1038 prev.p_filesz == prev.p_memsz && // Do not merge .bss
1039 load.p_filesz == load.p_memsz) { // Do not merge .bss
1040 // Merge this PT_LOAD with the previous one.
1041 Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
1042 prev.p_filesz = size;
1043 prev.p_memsz = size;
1044 } else {
1045 // If we are adding new load, it must be aligned.
1046 CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
1047 phdrs.push_back(load);
1048 }
1049 }
1050 }
1051 for (auto* section : sections_) {
1052 const Elf_Shdr& shdr = section->header_;
1053 if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
1054 // Other PT_* types allow the program to locate interesting
1055 // parts of memory at runtime. They must overlap with PT_LOAD.
1056 if (section->phdr_type_ != 0) {
1057 Elf_Phdr phdr = Elf_Phdr();
1058 phdr.p_type = section->phdr_type_;
1059 phdr.p_flags = section->phdr_flags_;
1060 phdr.p_offset = shdr.sh_offset;
1061 phdr.p_vaddr = phdr.p_paddr = shdr.sh_addr;
1062 phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
1063 phdr.p_align = shdr.sh_addralign;
1064 phdrs.push_back(phdr);
1065 }
1066 }
1067 }
1068 // Set the size of the initial PT_PHDR.
1069 CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
1070 phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
David Srbeckybc90fd02015-04-22 19:40:27 +01001071
David Srbecky6d8c8f02015-10-26 10:57:09 +00001072 return phdrs;
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001073 }
1074
David Srbeckybc90fd02015-04-22 19:40:27 +01001075 InstructionSet isa_;
David Srbecky5d811202016-03-08 13:21:22 +00001076 const InstructionSetFeatures* features_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001077
Vladimir Marko131980f2015-12-03 18:29:23 +00001078 ErrorDelayingOutputStream stream_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001079
1080 Section rodata_;
1081 Section text_;
Vladimir Markob066d432018-01-03 13:14:37 +00001082 Section data_bimg_rel_ro_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001083 Section bss_;
David Srbeckyec2cdf42017-12-08 16:21:25 +00001084 Section dex_;
Vladimir Marko944da602016-02-19 12:27:55 +00001085 CachedStringSection dynstr_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001086 SymbolSection dynsym_;
Vladimir Marko944da602016-02-19 12:27:55 +00001087 CachedSection hash_;
1088 CachedSection dynamic_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001089 Section eh_frame_;
1090 Section eh_frame_hdr_;
1091 StringSection strtab_;
1092 SymbolSection symtab_;
1093 Section debug_frame_;
David Srbeckyb851b492015-11-11 20:19:38 +00001094 Section debug_info_;
1095 Section debug_line_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001096 StringSection shstrtab_;
Douglas Leung316a2182015-09-17 15:26:25 -07001097 AbiflagsSection abiflags_;
Alexey Alexandrovab40c112016-09-19 09:33:49 -07001098 BuildIdSection build_id_;
David Srbecky6d8c8f02015-10-26 10:57:09 +00001099 std::vector<std::unique_ptr<Section>> other_sections_;
1100
1101 // List of used section in the order in which they were written.
1102 std::vector<Section*> sections_;
David Srbeckye155f4b2017-12-06 15:18:38 +00001103 Section* current_section_; // The section which is currently being written.
David Srbecky6d8c8f02015-10-26 10:57:09 +00001104
David Srbecky579942f2016-01-28 20:01:28 +00001105 bool started_;
David Srbeckyde91fd42018-07-05 22:27:08 +01001106 bool finished_;
Vladimir Marko944da602016-02-19 12:27:55 +00001107 bool write_program_headers_;
1108
1109 // The size of the memory taken by the ELF file when loaded.
1110 size_t loaded_size_;
David Srbecky579942f2016-01-28 20:01:28 +00001111
David Srbecky6d8c8f02015-10-26 10:57:09 +00001112 // Used for allocation of virtual address space.
1113 Elf_Addr virtual_address_;
Ian Rogers0279ebb2014-10-08 17:27:48 -07001114
1115 DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001116};
1117
Vladimir Marko74527972016-11-29 15:57:32 +00001118} // namespace linker
Andreas Gampe54fc26c2014-09-04 21:47:42 -07001119} // namespace art
1120
Vladimir Marko74527972016-11-29 15:57:32 +00001121#endif // ART_COMPILER_LINKER_ELF_BUILDER_H_