elf_builder.h revision 6d8c8f0344a706df651567387ede683ab3ec1b5f
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 "base/bit_utils.h"
24#include "base/casts.h"
25#include "base/unix_file/fd_file.h"
26#include "buffered_output_stream.h"
27#include "elf_utils.h"
28#include "file_output_stream.h"
29#include "leb128.h"
30
31namespace art {
32
33// Writes ELF file.
34//
35// The basic layout of the elf file:
36//   Elf_Ehdr                    - The ELF header.
37//   Elf_Phdr[]                  - Program headers for the linker.
38//   .rodata                     - DEX files and oat metadata.
39//   .text                       - Compiled code.
40//   .bss                        - Zero-initialized writeable section.
41//   .dynstr                     - Names for .dynsym.
42//   .dynsym                     - A few oat-specific dynamic symbols.
43//   .hash                       - Hash-table for .dynsym.
44//   .dynamic                    - Tags which let the linker locate .dynsym.
45//   .strtab                     - Names for .symtab.
46//   .symtab                     - Debug symbols.
47//   .eh_frame                   - Unwind information (CFI).
48//   .eh_frame_hdr               - Index of .eh_frame.
49//   .debug_frame                - Unwind information (CFI).
50//   .debug_frame.oat_patches    - Addresses for relocation.
51//   .debug_info                 - Debug information.
52//   .debug_info.oat_patches     - Addresses for relocation.
53//   .debug_abbrev               - Decoding information for .debug_info.
54//   .debug_str                  - Strings for .debug_info.
55//   .debug_line                 - Line number tables.
56//   .debug_line.oat_patches     - Addresses for relocation.
57//   .text.oat_patches           - Addresses for relocation.
58//   .shstrtab                   - Names of ELF sections.
59//   Elf_Shdr[]                  - Section headers.
60//
61// Some section are optional (the debug sections in particular).
62//
63// We try write the section data directly into the file without much
64// in-memory buffering.  This means we generally write sections based on the
65// dependency order (e.g. .dynamic points to .dynsym which points to .text).
66//
67// In the cases where we need to buffer, we write the larger section first
68// and buffer the smaller one (e.g. .strtab is bigger than .symtab).
69//
70// The debug sections are written last for easier stripping.
71//
72template <typename ElfTypes>
73class ElfBuilder FINAL {
74 public:
75  static constexpr size_t kMaxProgramHeaders = 16;
76  using Elf_Addr = typename ElfTypes::Addr;
77  using Elf_Off = typename ElfTypes::Off;
78  using Elf_Word = typename ElfTypes::Word;
79  using Elf_Sword = typename ElfTypes::Sword;
80  using Elf_Ehdr = typename ElfTypes::Ehdr;
81  using Elf_Shdr = typename ElfTypes::Shdr;
82  using Elf_Sym = typename ElfTypes::Sym;
83  using Elf_Phdr = typename ElfTypes::Phdr;
84  using Elf_Dyn = typename ElfTypes::Dyn;
85
86  // Base class of all sections.
87  class Section : public OutputStream {
88   public:
89    Section(ElfBuilder<ElfTypes>* owner, const std::string& name,
90            Elf_Word type, Elf_Word flags, const Section* link,
91            Elf_Word info, Elf_Word align, Elf_Word entsize)
92        : OutputStream(name), owner_(owner), header_(),
93          section_index_(0), name_(name), link_(link),
94          started_(false), finished_(false), phdr_flags_(PF_R), phdr_type_(0) {
95      DCHECK_GE(align, 1u);
96      header_.sh_type = type;
97      header_.sh_flags = flags;
98      header_.sh_info = info;
99      header_.sh_addralign = align;
100      header_.sh_entsize = entsize;
101    }
102
103    virtual ~Section() {
104      if (started_) {
105        CHECK(finished_);
106      }
107    }
108
109    // Start writing of this section.
110    void Start() {
111      CHECK(!started_);
112      CHECK(!finished_);
113      started_ = true;
114      auto& sections = owner_->sections_;
115      // Check that the previous section is complete.
116      CHECK(sections.empty() || sections.back()->finished_);
117      // The first ELF section index is 1. Index 0 is reserved for NULL.
118      section_index_ = sections.size() + 1;
119      // Push this section on the list of written sections.
120      sections.push_back(this);
121      // Align file position.
122      if (header_.sh_type != SHT_NOBITS) {
123        header_.sh_offset = RoundUp(owner_->Seek(0, kSeekCurrent), header_.sh_addralign);
124        owner_->Seek(header_.sh_offset, kSeekSet);
125      }
126      // Align virtual memory address.
127      if ((header_.sh_flags & SHF_ALLOC) != 0) {
128        header_.sh_addr = RoundUp(owner_->virtual_address_, header_.sh_addralign);
129        owner_->virtual_address_ = header_.sh_addr;
130      }
131    }
132
133    // Finish writing of this section.
134    void End() {
135      CHECK(started_);
136      CHECK(!finished_);
137      finished_ = true;
138      if (header_.sh_type == SHT_NOBITS) {
139        CHECK_GT(header_.sh_size, 0u);
140      } else {
141        // Use the current file position to determine section size.
142        off_t file_offset = owner_->Seek(0, kSeekCurrent);
143        CHECK_GE(file_offset, (off_t)header_.sh_offset);
144        header_.sh_size = file_offset - header_.sh_offset;
145      }
146      if ((header_.sh_flags & SHF_ALLOC) != 0) {
147        owner_->virtual_address_ += header_.sh_size;
148      }
149    }
150
151    // Get the location of this section in virtual memory.
152    Elf_Addr GetAddress() const {
153      CHECK(started_);
154      return header_.sh_addr;
155    }
156
157    // Returns the size of the content of this section.
158    Elf_Word GetSize() const {
159      CHECK(finished_);
160      return header_.sh_size;
161    }
162
163    // Set desired allocation size for .bss section.
164    void SetSize(Elf_Word size) {
165      CHECK_EQ(header_.sh_type, (Elf_Word)SHT_NOBITS);
166      header_.sh_size = size;
167    }
168
169    // This function always succeeds to simplify code.
170    // Use builder's Good() to check the actual status.
171    bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
172      CHECK(started_);
173      CHECK(!finished_);
174      owner_->WriteFully(buffer, byte_count);
175      return true;
176    }
177
178    // This function always succeeds to simplify code.
179    // Use builder's Good() to check the actual status.
180    off_t Seek(off_t offset, Whence whence) OVERRIDE {
181      // Forward the seek as-is and trust the caller to use it reasonably.
182      return owner_->Seek(offset, whence);
183    }
184
185    Elf_Word GetSectionIndex() const {
186      DCHECK(started_);
187      DCHECK_NE(section_index_, 0u);
188      return section_index_;
189    }
190
191   private:
192    ElfBuilder<ElfTypes>* owner_;
193    Elf_Shdr header_;
194    Elf_Word section_index_;
195    const std::string name_;
196    const Section* const link_;
197    bool started_;
198    bool finished_;
199    Elf_Word phdr_flags_;
200    Elf_Word phdr_type_;
201
202    DISALLOW_COPY_AND_ASSIGN(Section);
203
204    friend class ElfBuilder;
205  };
206
207  // Writer of .dynstr .strtab and .shstrtab sections.
208  class StringSection FINAL : public Section {
209   public:
210    StringSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
211                  Elf_Word flags, Elf_Word align)
212        : Section(owner, name, SHT_STRTAB, flags, nullptr, 0, align, 0),
213          current_offset_(0) {
214    }
215
216    Elf_Word Write(const std::string& name) {
217      if (current_offset_ == 0) {
218        DCHECK(name.empty());
219      }
220      Elf_Word offset = current_offset_;
221      this->WriteFully(name.c_str(), name.length() + 1);
222      current_offset_ += name.length() + 1;
223      return offset;
224    }
225
226   private:
227    Elf_Word current_offset_;
228  };
229
230  // Writer of .dynsym and .symtab sections.
231  class SymbolSection FINAL : public Section {
232   public:
233    SymbolSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
234                  Elf_Word type, Elf_Word flags, StringSection* strtab)
235        : Section(owner, name, type, flags, strtab, 0,
236                  sizeof(Elf_Off), sizeof(Elf_Sym)) {
237    }
238
239    // Buffer symbol for this section.  It will be written later.
240    void Add(Elf_Word name, const Section* section,
241             Elf_Addr addr, bool is_relative, Elf_Word size,
242             uint8_t binding, uint8_t type, uint8_t other = 0) {
243      CHECK(section != nullptr);
244      Elf_Sym sym = Elf_Sym();
245      sym.st_name = name;
246      sym.st_value = addr + (is_relative ? section->GetAddress() : 0);
247      sym.st_size = size;
248      sym.st_other = other;
249      sym.st_shndx = section->GetSectionIndex();
250      sym.st_info = (binding << 4) + (type & 0xf);
251      symbols_.push_back(sym);
252    }
253
254    void Write() {
255      // The symbol table always has to start with NULL symbol.
256      Elf_Sym null_symbol = Elf_Sym();
257      this->WriteFully(&null_symbol, sizeof(null_symbol));
258      this->WriteFully(symbols_.data(), symbols_.size() * sizeof(symbols_[0]));
259      symbols_.clear();
260      symbols_.shrink_to_fit();
261    }
262
263   private:
264    std::vector<Elf_Sym> symbols_;
265  };
266
267  ElfBuilder(InstructionSet isa, OutputStream* output)
268    : isa_(isa),
269      output_(output),
270      output_good_(true),
271      output_offset_(0),
272      rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
273      text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
274      bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
275      dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
276      dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
277      hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
278      dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
279      eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
280      eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
281      strtab_(this, ".strtab", 0, kPageSize),
282      symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
283      debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
284      shstrtab_(this, ".shstrtab", 0, 1),
285      virtual_address_(0) {
286    text_.phdr_flags_ = PF_R | PF_X;
287    bss_.phdr_flags_ = PF_R | PF_W;
288    dynamic_.phdr_flags_ = PF_R | PF_W;
289    dynamic_.phdr_type_ = PT_DYNAMIC;
290    eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
291  }
292  ~ElfBuilder() {}
293
294  InstructionSet GetIsa() { return isa_; }
295  Section* GetRoData() { return &rodata_; }
296  Section* GetText() { return &text_; }
297  Section* GetBss() { return &bss_; }
298  StringSection* GetStrTab() { return &strtab_; }
299  SymbolSection* GetSymTab() { return &symtab_; }
300  Section* GetEhFrame() { return &eh_frame_; }
301  Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
302  Section* GetDebugFrame() { return &debug_frame_; }
303
304  // Encode patch locations as LEB128 list of deltas between consecutive addresses.
305  // (exposed publicly for tests)
306  static void EncodeOatPatches(const std::vector<uintptr_t>& locations,
307                               std::vector<uint8_t>* buffer) {
308    buffer->reserve(buffer->size() + locations.size() * 2);  // guess 2 bytes per ULEB128.
309    uintptr_t address = 0;  // relative to start of section.
310    for (uintptr_t location : locations) {
311      DCHECK_GE(location, address) << "Patch locations are not in sorted order";
312      EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
313      address = location;
314    }
315  }
316
317  void WritePatches(const char* name, const std::vector<uintptr_t>* patch_locations) {
318    std::vector<uint8_t> buffer;
319    EncodeOatPatches(*patch_locations, &buffer);
320    std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
321    s->Start();
322    s->WriteFully(buffer.data(), buffer.size());
323    s->End();
324    other_sections_.push_back(std::move(s));
325  }
326
327  void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
328    std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
329    s->Start();
330    s->WriteFully(buffer->data(), buffer->size());
331    s->End();
332    other_sections_.push_back(std::move(s));
333  }
334
335  void Start() {
336    // Reserve space for ELF header and program headers.
337    // We do not know the number of headers until later, so
338    // it is easiest to just reserve a fixed amount of space.
339    int size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
340    Seek(size, kSeekSet);
341    virtual_address_ += size;
342  }
343
344  void End() {
345    // Write section names and finish the section headers.
346    shstrtab_.Start();
347    shstrtab_.Write("");
348    for (auto* section : sections_) {
349      section->header_.sh_name = shstrtab_.Write(section->name_);
350      if (section->link_ != nullptr) {
351        section->header_.sh_link = section->link_->GetSectionIndex();
352      }
353    }
354    shstrtab_.End();
355
356    // Write section headers at the end of the ELF file.
357    std::vector<Elf_Shdr> shdrs;
358    shdrs.reserve(1u + sections_.size());
359    shdrs.push_back(Elf_Shdr());  // NULL at index 0.
360    for (auto* section : sections_) {
361      shdrs.push_back(section->header_);
362    }
363    Elf_Off section_headers_offset;
364    section_headers_offset = RoundUp(Seek(0, kSeekCurrent), sizeof(Elf_Off));
365    Seek(section_headers_offset, kSeekSet);
366    WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
367
368    // Write the initial file headers.
369    std::vector<Elf_Phdr> phdrs = MakeProgramHeaders();
370    Elf_Ehdr elf_header = MakeElfHeader(isa_);
371    elf_header.e_phoff = sizeof(Elf_Ehdr);
372    elf_header.e_shoff = section_headers_offset;
373    elf_header.e_phnum = phdrs.size();
374    elf_header.e_shnum = shdrs.size();
375    elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
376    Seek(0, kSeekSet);
377    WriteFully(&elf_header, sizeof(elf_header));
378    WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
379  }
380
381  // The running program does not have access to section headers
382  // and the loader is not supposed to use them either.
383  // The dynamic sections therefore replicates some of the layout
384  // information like the address and size of .rodata and .text.
385  // It also contains other metadata like the SONAME.
386  // The .dynamic section is found using the PT_DYNAMIC program header.
387  void WriteDynamicSection(const std::string& elf_file_path) {
388    std::string soname(elf_file_path);
389    size_t directory_separator_pos = soname.rfind('/');
390    if (directory_separator_pos != std::string::npos) {
391      soname = soname.substr(directory_separator_pos + 1);
392    }
393
394    dynstr_.Start();
395    dynstr_.Write("");  // dynstr should start with empty string.
396    dynsym_.Add(dynstr_.Write("oatdata"), &rodata_, 0, true,
397                rodata_.GetSize(), STB_GLOBAL, STT_OBJECT);
398    if (text_.GetSize() != 0u) {
399      dynsym_.Add(dynstr_.Write("oatexec"), &text_, 0, true,
400                  text_.GetSize(), STB_GLOBAL, STT_OBJECT);
401      dynsym_.Add(dynstr_.Write("oatlastword"), &text_, text_.GetSize() - 4,
402                  true, 4, STB_GLOBAL, STT_OBJECT);
403    } else if (rodata_.GetSize() != 0) {
404      // rodata_ can be size 0 for dwarf_test.
405      dynsym_.Add(dynstr_.Write("oatlastword"), &rodata_, rodata_.GetSize() - 4,
406                  true, 4, STB_GLOBAL, STT_OBJECT);
407    }
408    if (bss_.finished_) {
409      dynsym_.Add(dynstr_.Write("oatbss"), &bss_,
410                  0, true, bss_.GetSize(), STB_GLOBAL, STT_OBJECT);
411      dynsym_.Add(dynstr_.Write("oatbsslastword"), &bss_,
412                  bss_.GetSize() - 4, true, 4, STB_GLOBAL, STT_OBJECT);
413    }
414    Elf_Word soname_offset = dynstr_.Write(soname);
415    dynstr_.End();
416
417    dynsym_.Start();
418    dynsym_.Write();
419    dynsym_.End();
420
421    // We do not really need a hash-table since there is so few entries.
422    // However, the hash-table is the only way the linker can actually
423    // determine the number of symbols in .dynsym so it is required.
424    hash_.Start();
425    int count = dynsym_.GetSize() / sizeof(Elf_Sym);  // Includes NULL.
426    std::vector<Elf_Word> hash;
427    hash.push_back(1);  // Number of buckets.
428    hash.push_back(count);  // Number of chains.
429    // Buckets.  Having just one makes it linear search.
430    hash.push_back(1);  // Point to first non-NULL symbol.
431    // Chains.  This creates linked list of symbols.
432    hash.push_back(0);  // Dummy entry for the NULL symbol.
433    for (int i = 1; i < count - 1; i++) {
434      hash.push_back(i + 1);  // Each symbol points to the next one.
435    }
436    hash.push_back(0);  // Last symbol terminates the chain.
437    hash_.WriteFully(hash.data(), hash.size() * sizeof(hash[0]));
438    hash_.End();
439
440    dynamic_.Start();
441    Elf_Dyn dyns[] = {
442      { DT_HASH, { hash_.GetAddress() } },
443      { DT_STRTAB, { dynstr_.GetAddress() } },
444      { DT_SYMTAB, { dynsym_.GetAddress() } },
445      { DT_SYMENT, { sizeof(Elf_Sym) } },
446      { DT_STRSZ, { dynstr_.GetSize() } },
447      { DT_SONAME, { soname_offset } },
448      { DT_NULL, { 0 } },
449    };
450    dynamic_.WriteFully(&dyns, sizeof(dyns));
451    dynamic_.End();
452  }
453
454  // Returns true if all writes and seeks on the output stream succeeded.
455  bool Good() {
456    return output_good_;
457  }
458
459 private:
460  // This function always succeeds to simplify code.
461  // Use Good() to check the actual status of the output stream.
462  void WriteFully(const void* buffer, size_t byte_count) {
463    if (output_good_) {
464      if (!output_->WriteFully(buffer, byte_count)) {
465        PLOG(ERROR) << "Failed to write " << byte_count
466                    << " bytes to ELF file at offset " << output_offset_;
467        output_good_ = false;
468      }
469    }
470    output_offset_ += byte_count;
471  }
472
473  // This function always succeeds to simplify code.
474  // Use Good() to check the actual status of the output stream.
475  off_t Seek(off_t offset, Whence whence) {
476    // We keep shadow copy of the offset so that we return
477    // the expected value even if the output stream failed.
478    off_t new_offset;
479    switch (whence) {
480      case kSeekSet:
481        new_offset = offset;
482        break;
483      case kSeekCurrent:
484        new_offset = output_offset_ + offset;
485        break;
486      default:
487        LOG(FATAL) << "Unsupported seek type: " << whence;
488        UNREACHABLE();
489    }
490    if (output_good_) {
491      off_t actual_offset = output_->Seek(offset, whence);
492      if (actual_offset == (off_t)-1) {
493        PLOG(ERROR) << "Failed to seek in ELF file. Offset=" << offset
494                    << " whence=" << whence << " new_offset=" << new_offset;
495        output_good_ = false;
496      }
497      DCHECK_EQ(actual_offset, new_offset);
498    }
499    output_offset_ = new_offset;
500    return new_offset;
501  }
502
503  static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
504    Elf_Ehdr elf_header = Elf_Ehdr();
505    switch (isa) {
506      case kArm:
507        // Fall through.
508      case kThumb2: {
509        elf_header.e_machine = EM_ARM;
510        elf_header.e_flags = EF_ARM_EABI_VER5;
511        break;
512      }
513      case kArm64: {
514        elf_header.e_machine = EM_AARCH64;
515        elf_header.e_flags = 0;
516        break;
517      }
518      case kX86: {
519        elf_header.e_machine = EM_386;
520        elf_header.e_flags = 0;
521        break;
522      }
523      case kX86_64: {
524        elf_header.e_machine = EM_X86_64;
525        elf_header.e_flags = 0;
526        break;
527      }
528      case kMips: {
529        elf_header.e_machine = EM_MIPS;
530        elf_header.e_flags = (EF_MIPS_NOREORDER |
531                               EF_MIPS_PIC       |
532                               EF_MIPS_CPIC      |
533                               EF_MIPS_ABI_O32   |
534                               EF_MIPS_ARCH_32R2);
535        break;
536      }
537      case kMips64: {
538        elf_header.e_machine = EM_MIPS;
539        elf_header.e_flags = (EF_MIPS_NOREORDER |
540                               EF_MIPS_PIC       |
541                               EF_MIPS_CPIC      |
542                               EF_MIPS_ARCH_64R6);
543        break;
544      }
545      case kNone: {
546        LOG(FATAL) << "No instruction set";
547        break;
548      }
549      default: {
550        LOG(FATAL) << "Unknown instruction set " << isa;
551      }
552    }
553
554    elf_header.e_ident[EI_MAG0]       = ELFMAG0;
555    elf_header.e_ident[EI_MAG1]       = ELFMAG1;
556    elf_header.e_ident[EI_MAG2]       = ELFMAG2;
557    elf_header.e_ident[EI_MAG3]       = ELFMAG3;
558    elf_header.e_ident[EI_CLASS]      = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
559                                         ? ELFCLASS32 : ELFCLASS64;;
560    elf_header.e_ident[EI_DATA]       = ELFDATA2LSB;
561    elf_header.e_ident[EI_VERSION]    = EV_CURRENT;
562    elf_header.e_ident[EI_OSABI]      = ELFOSABI_LINUX;
563    elf_header.e_ident[EI_ABIVERSION] = 0;
564    elf_header.e_type = ET_DYN;
565    elf_header.e_version = 1;
566    elf_header.e_entry = 0;
567    elf_header.e_ehsize = sizeof(Elf_Ehdr);
568    elf_header.e_phentsize = sizeof(Elf_Phdr);
569    elf_header.e_shentsize = sizeof(Elf_Shdr);
570    elf_header.e_phoff = sizeof(Elf_Ehdr);
571    return elf_header;
572  }
573
574  // Create program headers based on written sections.
575  std::vector<Elf_Phdr> MakeProgramHeaders() {
576    CHECK(!sections_.empty());
577    std::vector<Elf_Phdr> phdrs;
578    {
579      // The program headers must start with PT_PHDR which is used in
580      // loaded process to determine the number of program headers.
581      Elf_Phdr phdr = Elf_Phdr();
582      phdr.p_type    = PT_PHDR;
583      phdr.p_flags   = PF_R;
584      phdr.p_offset  = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
585      phdr.p_filesz  = phdr.p_memsz = 0;  // We need to fill this later.
586      phdr.p_align   = sizeof(Elf_Off);
587      phdrs.push_back(phdr);
588      // Tell the linker to mmap the start of file to memory.
589      Elf_Phdr load = Elf_Phdr();
590      load.p_type    = PT_LOAD;
591      load.p_flags   = PF_R;
592      load.p_offset  = load.p_vaddr = load.p_paddr = 0;
593      load.p_filesz  = load.p_memsz = sections_[0]->header_.sh_offset;
594      load.p_align   = kPageSize;
595      phdrs.push_back(load);
596    }
597    // Create program headers for sections.
598    for (auto* section : sections_) {
599      const Elf_Shdr& shdr = section->header_;
600      if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
601        // PT_LOAD tells the linker to mmap part of the file.
602        // The linker can only mmap page-aligned sections.
603        // Single PT_LOAD may contain several ELF sections.
604        Elf_Phdr& prev = phdrs.back();
605        Elf_Phdr load = Elf_Phdr();
606        load.p_type   = PT_LOAD;
607        load.p_flags  = section->phdr_flags_;
608        load.p_offset = shdr.sh_offset;
609        load.p_vaddr  = load.p_paddr = shdr.sh_addr;
610        load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
611        load.p_memsz  = shdr.sh_size;
612        load.p_align  = shdr.sh_addralign;
613        if (prev.p_type == load.p_type &&
614            prev.p_flags == load.p_flags &&
615            prev.p_filesz == prev.p_memsz &&  // Do not merge .bss
616            load.p_filesz == load.p_memsz) {  // Do not merge .bss
617          // Merge this PT_LOAD with the previous one.
618          Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
619          prev.p_filesz = size;
620          prev.p_memsz  = size;
621        } else {
622          // If we are adding new load, it must be aligned.
623          CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
624          phdrs.push_back(load);
625        }
626      }
627    }
628    for (auto* section : sections_) {
629      const Elf_Shdr& shdr = section->header_;
630      if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
631        // Other PT_* types allow the program to locate interesting
632        // parts of memory at runtime. They must overlap with PT_LOAD.
633        if (section->phdr_type_ != 0) {
634          Elf_Phdr phdr = Elf_Phdr();
635          phdr.p_type   = section->phdr_type_;
636          phdr.p_flags  = section->phdr_flags_;
637          phdr.p_offset = shdr.sh_offset;
638          phdr.p_vaddr  = phdr.p_paddr = shdr.sh_addr;
639          phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
640          phdr.p_align  = shdr.sh_addralign;
641          phdrs.push_back(phdr);
642        }
643      }
644    }
645    // Set the size of the initial PT_PHDR.
646    CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
647    phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
648
649    return phdrs;
650  }
651
652  InstructionSet isa_;
653
654  OutputStream* output_;
655  bool output_good_;  // True if all writes to output succeeded.
656  off_t output_offset_;  // Keep track of the current position in the stream.
657
658  Section rodata_;
659  Section text_;
660  Section bss_;
661  StringSection dynstr_;
662  SymbolSection dynsym_;
663  Section hash_;
664  Section dynamic_;
665  Section eh_frame_;
666  Section eh_frame_hdr_;
667  StringSection strtab_;
668  SymbolSection symtab_;
669  Section debug_frame_;
670  StringSection shstrtab_;
671  std::vector<std::unique_ptr<Section>> other_sections_;
672
673  // List of used section in the order in which they were written.
674  std::vector<Section*> sections_;
675
676  // Used for allocation of virtual address space.
677  Elf_Addr virtual_address_;
678
679  DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
680};
681
682}  // namespace art
683
684#endif  // ART_COMPILER_ELF_BUILDER_H_
685