elf_builder.h revision 197160d47f34238cb5e7444fa4c2de300db8e2c6
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
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
20#include <vector>
21
22#include "arch/instruction_set.h"
23#include "arch/mips/instruction_set_features_mips.h"
24#include "base/bit_utils.h"
25#include "base/casts.h"
26#include "base/unix_file/fd_file.h"
27#include "elf_utils.h"
28#include "leb128.h"
29#include "linker/error_delaying_output_stream.h"
30#include "utils/array_ref.h"
31
32namespace art {
33
34// Writes ELF file.
35//
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//
73template <typename ElfTypes>
74class ElfBuilder FINAL {
75 public:
76  static constexpr size_t kMaxProgramHeaders = 16;
77  using Elf_Addr = typename ElfTypes::Addr;
78  using Elf_Off = typename ElfTypes::Off;
79  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
87  // Base class of all sections.
88  class Section : public OutputStream {
89   public:
90    Section(ElfBuilder<ElfTypes>* owner,
91            const std::string& name,
92            Elf_Word type,
93            Elf_Word flags,
94            const Section* link,
95            Elf_Word info,
96            Elf_Word align,
97            Elf_Word entsize)
98        : OutputStream(name),
99          owner_(owner),
100          header_(),
101          section_index_(0),
102          name_(name),
103          link_(link),
104          started_(false),
105          finished_(false),
106          phdr_flags_(PF_R),
107          phdr_type_(0) {
108      DCHECK_GE(align, 1u);
109      header_.sh_type = type;
110      header_.sh_flags = flags;
111      header_.sh_info = info;
112      header_.sh_addralign = align;
113      header_.sh_entsize = entsize;
114    }
115
116    // Start writing of this section.
117    void Start() {
118      CHECK(!started_);
119      CHECK(!finished_);
120      started_ = true;
121      auto& sections = owner_->sections_;
122      // Check that the previous section is complete.
123      CHECK(sections.empty() || sections.back()->finished_);
124      // The first ELF section index is 1. Index 0 is reserved for NULL.
125      section_index_ = sections.size() + 1;
126      // Page-align if we switch between allocated and non-allocated sections,
127      // or if we change the type of allocation (e.g. executable vs non-executable).
128      if (!sections.empty()) {
129        if (header_.sh_flags != sections.back()->header_.sh_flags) {
130          header_.sh_addralign = kPageSize;
131        }
132      }
133      // Align file position.
134      if (header_.sh_type != SHT_NOBITS) {
135        header_.sh_offset = owner_->AlignFileOffset(header_.sh_addralign);
136      } else {
137        header_.sh_offset = 0;
138      }
139      // Align virtual memory address.
140      if ((header_.sh_flags & SHF_ALLOC) != 0) {
141        header_.sh_addr = owner_->AlignVirtualAddress(header_.sh_addralign);
142      } else {
143        header_.sh_addr = 0;
144      }
145      // Push this section on the list of written sections.
146      sections.push_back(this);
147    }
148
149    // Finish writing of this section.
150    void End() {
151      CHECK(started_);
152      CHECK(!finished_);
153      finished_ = true;
154      if (header_.sh_type == SHT_NOBITS) {
155        CHECK_GT(header_.sh_size, 0u);
156      } else {
157        // Use the current file position to determine section size.
158        off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
159        CHECK_GE(file_offset, (off_t)header_.sh_offset);
160        header_.sh_size = file_offset - header_.sh_offset;
161      }
162      if ((header_.sh_flags & SHF_ALLOC) != 0) {
163        owner_->virtual_address_ += header_.sh_size;
164      }
165    }
166
167    // Get the location of this section in virtual memory.
168    Elf_Addr GetAddress() const {
169      CHECK(started_);
170      return header_.sh_addr;
171    }
172
173    // Returns the size of the content of this section.
174    Elf_Word GetSize() const {
175      if (finished_) {
176        return header_.sh_size;
177      } else {
178        CHECK(started_);
179        CHECK_NE(header_.sh_type, (Elf_Word)SHT_NOBITS);
180        return owner_->stream_.Seek(0, kSeekCurrent) - header_.sh_offset;
181      }
182    }
183
184    // Write this section as "NOBITS" section. (used for the .bss section)
185    // This means that the ELF file does not contain the initial data for this section
186    // and it will be zero-initialized when the ELF file is loaded in the running program.
187    void WriteNoBitsSection(Elf_Word size) {
188      DCHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
189      header_.sh_type = SHT_NOBITS;
190      Start();
191      header_.sh_size = size;
192      End();
193    }
194
195    // This function always succeeds to simplify code.
196    // Use builder's Good() to check the actual status.
197    bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
198      CHECK(started_);
199      CHECK(!finished_);
200      return owner_->stream_.WriteFully(buffer, byte_count);
201    }
202
203    // This function always succeeds to simplify code.
204    // Use builder's Good() to check the actual status.
205    off_t Seek(off_t offset, Whence whence) OVERRIDE {
206      // Forward the seek as-is and trust the caller to use it reasonably.
207      return owner_->stream_.Seek(offset, whence);
208    }
209
210    // This function flushes the output and returns whether it succeeded.
211    // If there was a previous failure, this does nothing and returns false, i.e. failed.
212    bool Flush() OVERRIDE {
213      return owner_->stream_.Flush();
214    }
215
216    Elf_Word GetSectionIndex() const {
217      DCHECK(started_);
218      DCHECK_NE(section_index_, 0u);
219      return section_index_;
220    }
221
222   private:
223    ElfBuilder<ElfTypes>* owner_;
224    Elf_Shdr header_;
225    Elf_Word section_index_;
226    const std::string name_;
227    const Section* const link_;
228    bool started_;
229    bool finished_;
230    Elf_Word phdr_flags_;
231    Elf_Word phdr_type_;
232
233    friend class ElfBuilder;
234
235    DISALLOW_COPY_AND_ASSIGN(Section);
236  };
237
238  class CachedSection : public Section {
239   public:
240    CachedSection(ElfBuilder<ElfTypes>* owner,
241                  const std::string& name,
242                  Elf_Word type,
243                  Elf_Word flags,
244                  const Section* link,
245                  Elf_Word info,
246                  Elf_Word align,
247                  Elf_Word entsize)
248        : Section(owner, name, type, flags, link, info, align, entsize), cache_() { }
249
250    Elf_Word Add(const void* data, size_t length) {
251      Elf_Word offset = cache_.size();
252      const uint8_t* d = reinterpret_cast<const uint8_t*>(data);
253      cache_.insert(cache_.end(), d, d + length);
254      return offset;
255    }
256
257    Elf_Word GetCacheSize() {
258      return cache_.size();
259    }
260
261    void Write() {
262      this->WriteFully(cache_.data(), cache_.size());
263      cache_.clear();
264      cache_.shrink_to_fit();
265    }
266
267    void WriteCachedSection() {
268      this->Start();
269      Write();
270      this->End();
271    }
272
273   private:
274    std::vector<uint8_t> cache_;
275  };
276
277  // Writer of .dynstr section.
278  class CachedStringSection FINAL : public CachedSection {
279   public:
280    CachedStringSection(ElfBuilder<ElfTypes>* owner,
281                        const std::string& name,
282                        Elf_Word flags,
283                        Elf_Word align)
284        : CachedSection(owner,
285                        name,
286                        SHT_STRTAB,
287                        flags,
288                        /* link */ nullptr,
289                        /* info */ 0,
290                        align,
291                        /* entsize */ 0) { }
292
293    Elf_Word Add(const std::string& name) {
294      if (CachedSection::GetCacheSize() == 0u) {
295        DCHECK(name.empty());
296      }
297      return CachedSection::Add(name.c_str(), name.length() + 1);
298    }
299  };
300
301  // Writer of .strtab and .shstrtab sections.
302  class StringSection FINAL : public Section {
303   public:
304    StringSection(ElfBuilder<ElfTypes>* owner,
305                  const std::string& name,
306                  Elf_Word flags,
307                  Elf_Word align)
308        : Section(owner,
309                  name,
310                  SHT_STRTAB,
311                  flags,
312                  /* link */ nullptr,
313                  /* info */ 0,
314                  align,
315                  /* entsize */ 0),
316          current_offset_(0) {
317    }
318
319    Elf_Word Write(const std::string& name) {
320      if (current_offset_ == 0) {
321        DCHECK(name.empty());
322      }
323      Elf_Word offset = current_offset_;
324      this->WriteFully(name.c_str(), name.length() + 1);
325      current_offset_ += name.length() + 1;
326      return offset;
327    }
328
329   private:
330    Elf_Word current_offset_;
331  };
332
333  // Writer of .dynsym and .symtab sections.
334  class SymbolSection FINAL : public CachedSection {
335   public:
336    SymbolSection(ElfBuilder<ElfTypes>* owner,
337                  const std::string& name,
338                  Elf_Word type,
339                  Elf_Word flags,
340                  Section* strtab)
341        : CachedSection(owner,
342                        name,
343                        type,
344                        flags,
345                        strtab,
346                        /* info */ 0,
347                        sizeof(Elf_Off),
348                        sizeof(Elf_Sym)) {
349      // The symbol table always has to start with NULL symbol.
350      Elf_Sym null_symbol = Elf_Sym();
351      CachedSection::Add(&null_symbol, sizeof(null_symbol));
352    }
353
354    // Buffer symbol for this section.  It will be written later.
355    // If the symbol's section is null, it will be considered absolute (SHN_ABS).
356    // (we use this in JIT to reference code which is stored outside the debug ELF file)
357    void Add(Elf_Word name,
358             const Section* section,
359             Elf_Addr addr,
360             Elf_Word size,
361             uint8_t binding,
362             uint8_t type) {
363      Elf_Word section_index;
364      if (section != nullptr) {
365        DCHECK_LE(section->GetAddress(), addr);
366        DCHECK_LE(addr, section->GetAddress() + section->GetSize());
367        section_index = section->GetSectionIndex();
368      } else {
369        section_index = static_cast<Elf_Word>(SHN_ABS);
370      }
371      Add(name, section_index, addr, size, binding, type);
372    }
373
374    void Add(Elf_Word name,
375             Elf_Word section_index,
376             Elf_Addr addr,
377             Elf_Word size,
378             uint8_t binding,
379             uint8_t type) {
380      Elf_Sym sym = Elf_Sym();
381      sym.st_name = name;
382      sym.st_value = addr;
383      sym.st_size = size;
384      sym.st_other = 0;
385      sym.st_shndx = section_index;
386      sym.st_info = (binding << 4) + (type & 0xf);
387      CachedSection::Add(&sym, sizeof(sym));
388    }
389  };
390
391  ElfBuilder(InstructionSet isa, const InstructionSetFeatures* features, OutputStream* output)
392      : isa_(isa),
393        features_(features),
394        stream_(output),
395        rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
396        text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
397        bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
398        dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
399        dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
400        hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
401        dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
402        eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
403        eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
404        strtab_(this, ".strtab", 0, 1),
405        symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
406        debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
407        debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
408        debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
409        shstrtab_(this, ".shstrtab", 0, 1),
410        started_(false),
411        write_program_headers_(false),
412        loaded_size_(0u),
413        virtual_address_(0) {
414    text_.phdr_flags_ = PF_R | PF_X;
415    bss_.phdr_flags_ = PF_R | PF_W;
416    dynamic_.phdr_flags_ = PF_R | PF_W;
417    dynamic_.phdr_type_ = PT_DYNAMIC;
418    eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
419  }
420  ~ElfBuilder() {}
421
422  InstructionSet GetIsa() { return isa_; }
423  Section* GetRoData() { return &rodata_; }
424  Section* GetText() { return &text_; }
425  Section* GetBss() { return &bss_; }
426  StringSection* GetStrTab() { return &strtab_; }
427  SymbolSection* GetSymTab() { return &symtab_; }
428  Section* GetEhFrame() { return &eh_frame_; }
429  Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
430  Section* GetDebugFrame() { return &debug_frame_; }
431  Section* GetDebugInfo() { return &debug_info_; }
432  Section* GetDebugLine() { return &debug_line_; }
433
434  // Encode patch locations as LEB128 list of deltas between consecutive addresses.
435  // (exposed publicly for tests)
436  static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
437                               std::vector<uint8_t>* buffer) {
438    buffer->reserve(buffer->size() + locations.size() * 2);  // guess 2 bytes per ULEB128.
439    uintptr_t address = 0;  // relative to start of section.
440    for (uintptr_t location : locations) {
441      DCHECK_GE(location, address) << "Patch locations are not in sorted order";
442      EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
443      address = location;
444    }
445  }
446
447  void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
448    std::vector<uint8_t> buffer;
449    EncodeOatPatches(patch_locations, &buffer);
450    std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
451    s->Start();
452    s->WriteFully(buffer.data(), buffer.size());
453    s->End();
454    other_sections_.push_back(std::move(s));
455  }
456
457  void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
458    std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
459    s->Start();
460    s->WriteFully(buffer->data(), buffer->size());
461    s->End();
462    other_sections_.push_back(std::move(s));
463  }
464
465  // Reserve space for ELF header and program headers.
466  // We do not know the number of headers until later, so
467  // it is easiest to just reserve a fixed amount of space.
468  // Program headers are required for loading by the linker.
469  // It is possible to omit them for ELF files used for debugging.
470  void Start(bool write_program_headers = true) {
471    int size = sizeof(Elf_Ehdr);
472    if (write_program_headers) {
473      size += sizeof(Elf_Phdr) * kMaxProgramHeaders;
474    }
475    stream_.Seek(size, kSeekSet);
476    started_ = true;
477    virtual_address_ += size;
478    write_program_headers_ = write_program_headers;
479  }
480
481  void End() {
482    DCHECK(started_);
483
484    // Note: loaded_size_ == 0 for tests that don't write .rodata, .text, .bss,
485    // .dynstr, dynsym, .hash and .dynamic. These tests should not read loaded_size_.
486    // TODO: Either refactor the .eh_frame creation so that it counts towards loaded_size_,
487    // or remove all support for .eh_frame. (The currently unused .eh_frame counts towards
488    // the virtual_address_ but we don't consider it for loaded_size_.)
489    CHECK(loaded_size_ == 0 || loaded_size_ == RoundUp(virtual_address_, kPageSize))
490        << loaded_size_ << " " << virtual_address_;
491
492    // Write section names and finish the section headers.
493    shstrtab_.Start();
494    shstrtab_.Write("");
495    for (auto* section : sections_) {
496      section->header_.sh_name = shstrtab_.Write(section->name_);
497      if (section->link_ != nullptr) {
498        section->header_.sh_link = section->link_->GetSectionIndex();
499      }
500    }
501    shstrtab_.End();
502
503    // Write section headers at the end of the ELF file.
504    std::vector<Elf_Shdr> shdrs;
505    shdrs.reserve(1u + sections_.size());
506    shdrs.push_back(Elf_Shdr());  // NULL at index 0.
507    for (auto* section : sections_) {
508      shdrs.push_back(section->header_);
509    }
510    Elf_Off section_headers_offset;
511    section_headers_offset = AlignFileOffset(sizeof(Elf_Off));
512    stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
513
514    // Flush everything else before writing the program headers. This should prevent
515    // the OS from reordering writes, so that we don't end up with valid headers
516    // and partially written data if we suddenly lose power, for example.
517    stream_.Flush();
518
519    // The main ELF header.
520    Elf_Ehdr elf_header = MakeElfHeader(isa_);
521    elf_header.e_shoff = section_headers_offset;
522    elf_header.e_shnum = shdrs.size();
523    elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
524
525    // Program headers (i.e. mmap instructions).
526    std::vector<Elf_Phdr> phdrs;
527    if (write_program_headers_) {
528      phdrs = MakeProgramHeaders();
529      CHECK_LE(phdrs.size(), kMaxProgramHeaders);
530      elf_header.e_phoff = sizeof(Elf_Ehdr);
531      elf_header.e_phnum = phdrs.size();
532    }
533
534    stream_.Seek(0, kSeekSet);
535    stream_.WriteFully(&elf_header, sizeof(elf_header));
536    stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
537    stream_.Flush();
538  }
539
540  // The running program does not have access to section headers
541  // and the loader is not supposed to use them either.
542  // The dynamic sections therefore replicates some of the layout
543  // information like the address and size of .rodata and .text.
544  // It also contains other metadata like the SONAME.
545  // The .dynamic section is found using the PT_DYNAMIC program header.
546  void PrepareDynamicSection(const std::string& elf_file_path,
547                             Elf_Word rodata_size,
548                             Elf_Word text_size,
549                             Elf_Word bss_size) {
550    std::string soname(elf_file_path);
551    size_t directory_separator_pos = soname.rfind('/');
552    if (directory_separator_pos != std::string::npos) {
553      soname = soname.substr(directory_separator_pos + 1);
554    }
555
556    // Calculate addresses of .text, .bss and .dynstr.
557    DCHECK_EQ(rodata_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
558    DCHECK_EQ(text_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
559    DCHECK_EQ(bss_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
560    DCHECK_EQ(dynstr_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
561    Elf_Word rodata_address = rodata_.GetAddress();
562    Elf_Word text_address = RoundUp(rodata_address + rodata_size, kPageSize);
563    Elf_Word bss_address = RoundUp(text_address + text_size, kPageSize);
564    Elf_Word dynstr_address = RoundUp(bss_address + bss_size, kPageSize);
565
566    // Cache .dynstr, .dynsym and .hash data.
567    dynstr_.Add("");  // dynstr should start with empty string.
568    Elf_Word rodata_index = rodata_.GetSectionIndex();
569    Elf_Word oatdata = dynstr_.Add("oatdata");
570    dynsym_.Add(oatdata, rodata_index, rodata_address, rodata_size, STB_GLOBAL, STT_OBJECT);
571    if (text_size != 0u) {
572      Elf_Word text_index = rodata_index + 1u;
573      Elf_Word oatexec = dynstr_.Add("oatexec");
574      dynsym_.Add(oatexec, text_index, text_address, text_size, STB_GLOBAL, STT_OBJECT);
575      Elf_Word oatlastword = dynstr_.Add("oatlastword");
576      Elf_Word oatlastword_address = text_address + text_size - 4;
577      dynsym_.Add(oatlastword, text_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
578    } else if (rodata_size != 0) {
579      // rodata_ can be size 0 for dwarf_test.
580      Elf_Word oatlastword = dynstr_.Add("oatlastword");
581      Elf_Word oatlastword_address = rodata_address + rodata_size - 4;
582      dynsym_.Add(oatlastword, rodata_index, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
583    }
584    if (bss_size != 0u) {
585      Elf_Word bss_index = rodata_index + 1u + (text_size != 0 ? 1u : 0u);
586      Elf_Word oatbss = dynstr_.Add("oatbss");
587      dynsym_.Add(oatbss, bss_index, bss_address, bss_size, STB_GLOBAL, STT_OBJECT);
588      Elf_Word oatbsslastword = dynstr_.Add("oatbsslastword");
589      Elf_Word bsslastword_address = bss_address + bss_size - 4;
590      dynsym_.Add(oatbsslastword, bss_index, bsslastword_address, 4, STB_GLOBAL, STT_OBJECT);
591    }
592    Elf_Word soname_offset = dynstr_.Add(soname);
593
594    // We do not really need a hash-table since there is so few entries.
595    // However, the hash-table is the only way the linker can actually
596    // determine the number of symbols in .dynsym so it is required.
597    int count = dynsym_.GetCacheSize() / sizeof(Elf_Sym);  // Includes NULL.
598    std::vector<Elf_Word> hash;
599    hash.push_back(1);  // Number of buckets.
600    hash.push_back(count);  // Number of chains.
601    // Buckets.  Having just one makes it linear search.
602    hash.push_back(1);  // Point to first non-NULL symbol.
603    // Chains.  This creates linked list of symbols.
604    hash.push_back(0);  // Dummy entry for the NULL symbol.
605    for (int i = 1; i < count - 1; i++) {
606      hash.push_back(i + 1);  // Each symbol points to the next one.
607    }
608    hash.push_back(0);  // Last symbol terminates the chain.
609    hash_.Add(hash.data(), hash.size() * sizeof(hash[0]));
610
611    // Calculate addresses of .dynsym, .hash and .dynamic.
612    DCHECK_EQ(dynstr_.header_.sh_flags, dynsym_.header_.sh_flags);
613    DCHECK_EQ(dynsym_.header_.sh_flags, hash_.header_.sh_flags);
614    Elf_Word dynsym_address =
615        RoundUp(dynstr_address + dynstr_.GetCacheSize(), dynsym_.header_.sh_addralign);
616    Elf_Word hash_address =
617        RoundUp(dynsym_address + dynsym_.GetCacheSize(), hash_.header_.sh_addralign);
618    DCHECK_EQ(dynamic_.header_.sh_addralign, static_cast<Elf_Word>(kPageSize));
619    Elf_Word dynamic_address = RoundUp(hash_address + dynsym_.GetCacheSize(), kPageSize);
620
621    Elf_Dyn dyns[] = {
622      { DT_HASH, { hash_address } },
623      { DT_STRTAB, { dynstr_address } },
624      { DT_SYMTAB, { dynsym_address } },
625      { DT_SYMENT, { sizeof(Elf_Sym) } },
626      { DT_STRSZ, { dynstr_.GetCacheSize() } },
627      { DT_SONAME, { soname_offset } },
628      { DT_NULL, { 0 } },
629    };
630    dynamic_.Add(&dyns, sizeof(dyns));
631
632    loaded_size_ = RoundUp(dynamic_address + dynamic_.GetCacheSize(), kPageSize);
633  }
634
635  void WriteDynamicSection() {
636    dynstr_.WriteCachedSection();
637    dynsym_.WriteCachedSection();
638    hash_.WriteCachedSection();
639    dynamic_.WriteCachedSection();
640
641    CHECK_EQ(loaded_size_, RoundUp(dynamic_.GetAddress() + dynamic_.GetSize(), kPageSize));
642  }
643
644  Elf_Word GetLoadedSize() {
645    CHECK_NE(loaded_size_, 0u);
646    return loaded_size_;
647  }
648
649  // Returns true if all writes and seeks on the output stream succeeded.
650  bool Good() {
651    return stream_.Good();
652  }
653
654  // Returns the builder's internal stream.
655  OutputStream* GetStream() {
656    return &stream_;
657  }
658
659  off_t AlignFileOffset(size_t alignment) {
660     return stream_.Seek(RoundUp(stream_.Seek(0, kSeekCurrent), alignment), kSeekSet);
661  }
662
663  Elf_Addr AlignVirtualAddress(size_t alignment) {
664     return virtual_address_ = RoundUp(virtual_address_, alignment);
665  }
666
667 private:
668  static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
669    Elf_Ehdr elf_header = Elf_Ehdr();
670    switch (isa) {
671      case kArm:
672        // Fall through.
673      case kThumb2: {
674        elf_header.e_machine = EM_ARM;
675        elf_header.e_flags = EF_ARM_EABI_VER5;
676        break;
677      }
678      case kArm64: {
679        elf_header.e_machine = EM_AARCH64;
680        elf_header.e_flags = 0;
681        break;
682      }
683      case kX86: {
684        elf_header.e_machine = EM_386;
685        elf_header.e_flags = 0;
686        break;
687      }
688      case kX86_64: {
689        elf_header.e_machine = EM_X86_64;
690        elf_header.e_flags = 0;
691        break;
692      }
693      case kMips: {
694        elf_header.e_machine = EM_MIPS;
695        elf_header.e_flags = (EF_MIPS_NOREORDER |
696                               EF_MIPS_PIC       |
697                               EF_MIPS_CPIC      |
698                               EF_MIPS_ABI_O32   |
699                               EF_MIPS_ARCH_32R2);
700        break;
701      }
702      case kMips64: {
703        elf_header.e_machine = EM_MIPS;
704        elf_header.e_flags = (EF_MIPS_NOREORDER |
705                               EF_MIPS_PIC       |
706                               EF_MIPS_CPIC      |
707                               EF_MIPS_ARCH_64R6);
708        break;
709      }
710      case kNone: {
711        LOG(FATAL) << "No instruction set";
712        break;
713      }
714      default: {
715        LOG(FATAL) << "Unknown instruction set " << isa;
716      }
717    }
718
719    elf_header.e_ident[EI_MAG0]       = ELFMAG0;
720    elf_header.e_ident[EI_MAG1]       = ELFMAG1;
721    elf_header.e_ident[EI_MAG2]       = ELFMAG2;
722    elf_header.e_ident[EI_MAG3]       = ELFMAG3;
723    elf_header.e_ident[EI_CLASS]      = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
724                                         ? ELFCLASS32 : ELFCLASS64;;
725    elf_header.e_ident[EI_DATA]       = ELFDATA2LSB;
726    elf_header.e_ident[EI_VERSION]    = EV_CURRENT;
727    elf_header.e_ident[EI_OSABI]      = ELFOSABI_LINUX;
728    elf_header.e_ident[EI_ABIVERSION] = 0;
729    elf_header.e_type = ET_DYN;
730    elf_header.e_version = 1;
731    elf_header.e_entry = 0;
732    elf_header.e_ehsize = sizeof(Elf_Ehdr);
733    elf_header.e_phentsize = sizeof(Elf_Phdr);
734    elf_header.e_shentsize = sizeof(Elf_Shdr);
735    elf_header.e_phoff = sizeof(Elf_Ehdr);
736    return elf_header;
737  }
738
739  // Create program headers based on written sections.
740  std::vector<Elf_Phdr> MakeProgramHeaders() {
741    CHECK(!sections_.empty());
742    std::vector<Elf_Phdr> phdrs;
743    {
744      // The program headers must start with PT_PHDR which is used in
745      // loaded process to determine the number of program headers.
746      Elf_Phdr phdr = Elf_Phdr();
747      phdr.p_type    = PT_PHDR;
748      phdr.p_flags   = PF_R;
749      phdr.p_offset  = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
750      phdr.p_filesz  = phdr.p_memsz = 0;  // We need to fill this later.
751      phdr.p_align   = sizeof(Elf_Off);
752      phdrs.push_back(phdr);
753      // Tell the linker to mmap the start of file to memory.
754      Elf_Phdr load = Elf_Phdr();
755      load.p_type    = PT_LOAD;
756      load.p_flags   = PF_R;
757      load.p_offset  = load.p_vaddr = load.p_paddr = 0;
758      load.p_filesz  = load.p_memsz = sections_[0]->header_.sh_offset;
759      load.p_align   = kPageSize;
760      phdrs.push_back(load);
761    }
762    // Create program headers for sections.
763    for (auto* section : sections_) {
764      const Elf_Shdr& shdr = section->header_;
765      if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
766        // PT_LOAD tells the linker to mmap part of the file.
767        // The linker can only mmap page-aligned sections.
768        // Single PT_LOAD may contain several ELF sections.
769        Elf_Phdr& prev = phdrs.back();
770        Elf_Phdr load = Elf_Phdr();
771        load.p_type   = PT_LOAD;
772        load.p_flags  = section->phdr_flags_;
773        load.p_offset = shdr.sh_offset;
774        load.p_vaddr  = load.p_paddr = shdr.sh_addr;
775        load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
776        load.p_memsz  = shdr.sh_size;
777        load.p_align  = shdr.sh_addralign;
778        if (prev.p_type == load.p_type &&
779            prev.p_flags == load.p_flags &&
780            prev.p_filesz == prev.p_memsz &&  // Do not merge .bss
781            load.p_filesz == load.p_memsz) {  // Do not merge .bss
782          // Merge this PT_LOAD with the previous one.
783          Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
784          prev.p_filesz = size;
785          prev.p_memsz  = size;
786        } else {
787          // If we are adding new load, it must be aligned.
788          CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
789          phdrs.push_back(load);
790        }
791      }
792    }
793    for (auto* section : sections_) {
794      const Elf_Shdr& shdr = section->header_;
795      if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
796        // Other PT_* types allow the program to locate interesting
797        // parts of memory at runtime. They must overlap with PT_LOAD.
798        if (section->phdr_type_ != 0) {
799          Elf_Phdr phdr = Elf_Phdr();
800          phdr.p_type   = section->phdr_type_;
801          phdr.p_flags  = section->phdr_flags_;
802          phdr.p_offset = shdr.sh_offset;
803          phdr.p_vaddr  = phdr.p_paddr = shdr.sh_addr;
804          phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
805          phdr.p_align  = shdr.sh_addralign;
806          phdrs.push_back(phdr);
807        }
808      }
809    }
810    // Set the size of the initial PT_PHDR.
811    CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
812    phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
813
814    return phdrs;
815  }
816
817  InstructionSet isa_;
818  const InstructionSetFeatures* features_;
819
820  ErrorDelayingOutputStream stream_;
821
822  Section rodata_;
823  Section text_;
824  Section bss_;
825  CachedStringSection dynstr_;
826  SymbolSection dynsym_;
827  CachedSection hash_;
828  CachedSection dynamic_;
829  Section eh_frame_;
830  Section eh_frame_hdr_;
831  StringSection strtab_;
832  SymbolSection symtab_;
833  Section debug_frame_;
834  Section debug_info_;
835  Section debug_line_;
836  StringSection shstrtab_;
837  std::vector<std::unique_ptr<Section>> other_sections_;
838
839  // List of used section in the order in which they were written.
840  std::vector<Section*> sections_;
841
842  bool started_;
843  bool write_program_headers_;
844
845  // The size of the memory taken by the ELF file when loaded.
846  size_t loaded_size_;
847
848  // Used for allocation of virtual address space.
849  Elf_Addr virtual_address_;
850
851  DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
852};
853
854}  // namespace art
855
856#endif  // ART_COMPILER_ELF_BUILDER_H_
857