elf_builder.h revision 5cc349f3dd578e974f78314c50b6a0267c23e591
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 "elf_utils.h"
27#include "leb128.h"
28#include "linker/error_delaying_output_stream.h"
29#include "utils/array_ref.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    ~Section() OVERRIDE {
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_->stream_.Seek(0, kSeekCurrent), header_.sh_addralign);
124        owner_->stream_.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_->stream_.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    // Returns true if the section was written to disk.
152    // (Used to check whether we have .text when writing JIT debug info)
153    bool Exists() const {
154      return finished_;
155    }
156
157    // Get the location of this section in virtual memory.
158    Elf_Addr GetAddress() const {
159      CHECK(started_);
160      return header_.sh_addr;
161    }
162
163    // Returns the size of the content of this section.
164    Elf_Word GetSize() const {
165      if (finished_) {
166        return header_.sh_size;
167      } else {
168        CHECK(started_);
169        CHECK_NE(header_.sh_type, (Elf_Word)SHT_NOBITS);
170        return owner_->stream_.Seek(0, kSeekCurrent) - header_.sh_offset;
171      }
172    }
173
174    // Set desired allocation size for .bss section.
175    void SetSize(Elf_Word size) {
176      CHECK_EQ(header_.sh_type, (Elf_Word)SHT_NOBITS);
177      header_.sh_size = size;
178    }
179
180    // This function always succeeds to simplify code.
181    // Use builder's Good() to check the actual status.
182    bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
183      CHECK(started_);
184      CHECK(!finished_);
185      return owner_->stream_.WriteFully(buffer, byte_count);
186    }
187
188    // This function always succeeds to simplify code.
189    // Use builder's Good() to check the actual status.
190    off_t Seek(off_t offset, Whence whence) OVERRIDE {
191      // Forward the seek as-is and trust the caller to use it reasonably.
192      return owner_->stream_.Seek(offset, whence);
193    }
194
195    // This function flushes the output and returns whether it succeeded.
196    // If there was a previous failure, this does nothing and returns false, i.e. failed.
197    bool Flush() OVERRIDE {
198      return owner_->stream_.Flush();
199    }
200
201    Elf_Word GetSectionIndex() const {
202      DCHECK(started_);
203      DCHECK_NE(section_index_, 0u);
204      return section_index_;
205    }
206
207   private:
208    ElfBuilder<ElfTypes>* owner_;
209    Elf_Shdr header_;
210    Elf_Word section_index_;
211    const std::string name_;
212    const Section* const link_;
213    bool started_;
214    bool finished_;
215    Elf_Word phdr_flags_;
216    Elf_Word phdr_type_;
217
218    friend class ElfBuilder;
219
220    DISALLOW_COPY_AND_ASSIGN(Section);
221  };
222
223  // Writer of .dynstr .strtab and .shstrtab sections.
224  class StringSection FINAL : public Section {
225   public:
226    StringSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
227                  Elf_Word flags, Elf_Word align)
228        : Section(owner, name, SHT_STRTAB, flags, nullptr, 0, align, 0),
229          current_offset_(0) {
230    }
231
232    Elf_Word Write(const std::string& name) {
233      if (current_offset_ == 0) {
234        DCHECK(name.empty());
235      }
236      Elf_Word offset = current_offset_;
237      this->WriteFully(name.c_str(), name.length() + 1);
238      current_offset_ += name.length() + 1;
239      return offset;
240    }
241
242   private:
243    Elf_Word current_offset_;
244  };
245
246  // Writer of .dynsym and .symtab sections.
247  class SymbolSection FINAL : public Section {
248   public:
249    SymbolSection(ElfBuilder<ElfTypes>* owner, const std::string& name,
250                  Elf_Word type, Elf_Word flags, StringSection* strtab)
251        : Section(owner, name, type, flags, strtab, 0,
252                  sizeof(Elf_Off), sizeof(Elf_Sym)) {
253    }
254
255    // Buffer symbol for this section.  It will be written later.
256    // If the symbol's section is null, it will be considered absolute (SHN_ABS).
257    // (we use this in JIT to reference code which is stored outside the debug ELF file)
258    void Add(Elf_Word name, const Section* section,
259             Elf_Addr addr, bool is_relative, Elf_Word size,
260             uint8_t binding, uint8_t type, uint8_t other = 0) {
261      Elf_Sym sym = Elf_Sym();
262      sym.st_name = name;
263      sym.st_value = addr + (is_relative ? section->GetAddress() : 0);
264      sym.st_size = size;
265      sym.st_other = other;
266      sym.st_shndx = (section != nullptr ? section->GetSectionIndex()
267                                         : static_cast<Elf_Word>(SHN_ABS));
268      sym.st_info = (binding << 4) + (type & 0xf);
269      symbols_.push_back(sym);
270    }
271
272    void Write() {
273      // The symbol table always has to start with NULL symbol.
274      Elf_Sym null_symbol = Elf_Sym();
275      this->WriteFully(&null_symbol, sizeof(null_symbol));
276      this->WriteFully(symbols_.data(), symbols_.size() * sizeof(symbols_[0]));
277      symbols_.clear();
278      symbols_.shrink_to_fit();
279    }
280
281   private:
282    std::vector<Elf_Sym> symbols_;
283  };
284
285  ElfBuilder(InstructionSet isa, OutputStream* output)
286      : isa_(isa),
287        stream_(output),
288        rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
289        text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0, kPageSize, 0),
290        bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
291        dynstr_(this, ".dynstr", SHF_ALLOC, kPageSize),
292        dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
293        hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
294        dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, kPageSize, sizeof(Elf_Dyn)),
295        eh_frame_(this, ".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, kPageSize, 0),
296        eh_frame_hdr_(this, ".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0),
297        strtab_(this, ".strtab", 0, kPageSize),
298        symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
299        debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
300        debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
301        debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
302        shstrtab_(this, ".shstrtab", 0, 1),
303        virtual_address_(0) {
304    text_.phdr_flags_ = PF_R | PF_X;
305    bss_.phdr_flags_ = PF_R | PF_W;
306    dynamic_.phdr_flags_ = PF_R | PF_W;
307    dynamic_.phdr_type_ = PT_DYNAMIC;
308    eh_frame_hdr_.phdr_type_ = PT_GNU_EH_FRAME;
309  }
310  ~ElfBuilder() {}
311
312  InstructionSet GetIsa() { return isa_; }
313  Section* GetRoData() { return &rodata_; }
314  Section* GetText() { return &text_; }
315  Section* GetBss() { return &bss_; }
316  StringSection* GetStrTab() { return &strtab_; }
317  SymbolSection* GetSymTab() { return &symtab_; }
318  Section* GetEhFrame() { return &eh_frame_; }
319  Section* GetEhFrameHdr() { return &eh_frame_hdr_; }
320  Section* GetDebugFrame() { return &debug_frame_; }
321  Section* GetDebugInfo() { return &debug_info_; }
322  Section* GetDebugLine() { return &debug_line_; }
323
324  // Encode patch locations as LEB128 list of deltas between consecutive addresses.
325  // (exposed publicly for tests)
326  static void EncodeOatPatches(const ArrayRef<const uintptr_t>& locations,
327                               std::vector<uint8_t>* buffer) {
328    buffer->reserve(buffer->size() + locations.size() * 2);  // guess 2 bytes per ULEB128.
329    uintptr_t address = 0;  // relative to start of section.
330    for (uintptr_t location : locations) {
331      DCHECK_GE(location, address) << "Patch locations are not in sorted order";
332      EncodeUnsignedLeb128(buffer, dchecked_integral_cast<uint32_t>(location - address));
333      address = location;
334    }
335  }
336
337  void WritePatches(const char* name, const ArrayRef<const uintptr_t>& patch_locations) {
338    std::vector<uint8_t> buffer;
339    EncodeOatPatches(patch_locations, &buffer);
340    std::unique_ptr<Section> s(new Section(this, name, SHT_OAT_PATCH, 0, nullptr, 0, 1, 0));
341    s->Start();
342    s->WriteFully(buffer.data(), buffer.size());
343    s->End();
344    other_sections_.push_back(std::move(s));
345  }
346
347  void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
348    std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
349    s->Start();
350    s->WriteFully(buffer->data(), buffer->size());
351    s->End();
352    other_sections_.push_back(std::move(s));
353  }
354
355  void Start() {
356    // Reserve space for ELF header and program headers.
357    // We do not know the number of headers until later, so
358    // it is easiest to just reserve a fixed amount of space.
359    int size = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
360    stream_.Seek(size, kSeekSet);
361    virtual_address_ += size;
362  }
363
364  void End() {
365    // Write section names and finish the section headers.
366    shstrtab_.Start();
367    shstrtab_.Write("");
368    for (auto* section : sections_) {
369      section->header_.sh_name = shstrtab_.Write(section->name_);
370      if (section->link_ != nullptr) {
371        section->header_.sh_link = section->link_->GetSectionIndex();
372      }
373    }
374    shstrtab_.End();
375
376    // Write section headers at the end of the ELF file.
377    std::vector<Elf_Shdr> shdrs;
378    shdrs.reserve(1u + sections_.size());
379    shdrs.push_back(Elf_Shdr());  // NULL at index 0.
380    for (auto* section : sections_) {
381      shdrs.push_back(section->header_);
382    }
383    Elf_Off section_headers_offset;
384    section_headers_offset = RoundUp(stream_.Seek(0, kSeekCurrent), sizeof(Elf_Off));
385    stream_.Seek(section_headers_offset, kSeekSet);
386    stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
387
388    // Flush everything else before writing the program headers. This should prevent
389    // the OS from reordering writes, so that we don't end up with valid headers
390    // and partially written data if we suddenly lose power, for example.
391    stream_.Flush();
392
393    // Write the initial file headers.
394    std::vector<Elf_Phdr> phdrs = MakeProgramHeaders();
395    Elf_Ehdr elf_header = MakeElfHeader(isa_);
396    elf_header.e_phoff = sizeof(Elf_Ehdr);
397    elf_header.e_shoff = section_headers_offset;
398    elf_header.e_phnum = phdrs.size();
399    elf_header.e_shnum = shdrs.size();
400    elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
401    stream_.Seek(0, kSeekSet);
402    stream_.WriteFully(&elf_header, sizeof(elf_header));
403    stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
404    stream_.Flush();
405  }
406
407  // The running program does not have access to section headers
408  // and the loader is not supposed to use them either.
409  // The dynamic sections therefore replicates some of the layout
410  // information like the address and size of .rodata and .text.
411  // It also contains other metadata like the SONAME.
412  // The .dynamic section is found using the PT_DYNAMIC program header.
413  void WriteDynamicSection(const std::string& elf_file_path) {
414    std::string soname(elf_file_path);
415    size_t directory_separator_pos = soname.rfind('/');
416    if (directory_separator_pos != std::string::npos) {
417      soname = soname.substr(directory_separator_pos + 1);
418    }
419
420    dynstr_.Start();
421    dynstr_.Write("");  // dynstr should start with empty string.
422    dynsym_.Add(dynstr_.Write("oatdata"), &rodata_, 0, true,
423                rodata_.GetSize(), STB_GLOBAL, STT_OBJECT);
424    if (text_.GetSize() != 0u) {
425      dynsym_.Add(dynstr_.Write("oatexec"), &text_, 0, true,
426                  text_.GetSize(), STB_GLOBAL, STT_OBJECT);
427      dynsym_.Add(dynstr_.Write("oatlastword"), &text_, text_.GetSize() - 4,
428                  true, 4, STB_GLOBAL, STT_OBJECT);
429    } else if (rodata_.GetSize() != 0) {
430      // rodata_ can be size 0 for dwarf_test.
431      dynsym_.Add(dynstr_.Write("oatlastword"), &rodata_, rodata_.GetSize() - 4,
432                  true, 4, STB_GLOBAL, STT_OBJECT);
433    }
434    if (bss_.finished_) {
435      dynsym_.Add(dynstr_.Write("oatbss"), &bss_,
436                  0, true, bss_.GetSize(), STB_GLOBAL, STT_OBJECT);
437      dynsym_.Add(dynstr_.Write("oatbsslastword"), &bss_,
438                  bss_.GetSize() - 4, true, 4, STB_GLOBAL, STT_OBJECT);
439    }
440    Elf_Word soname_offset = dynstr_.Write(soname);
441    dynstr_.End();
442
443    dynsym_.Start();
444    dynsym_.Write();
445    dynsym_.End();
446
447    // We do not really need a hash-table since there is so few entries.
448    // However, the hash-table is the only way the linker can actually
449    // determine the number of symbols in .dynsym so it is required.
450    hash_.Start();
451    int count = dynsym_.GetSize() / sizeof(Elf_Sym);  // Includes NULL.
452    std::vector<Elf_Word> hash;
453    hash.push_back(1);  // Number of buckets.
454    hash.push_back(count);  // Number of chains.
455    // Buckets.  Having just one makes it linear search.
456    hash.push_back(1);  // Point to first non-NULL symbol.
457    // Chains.  This creates linked list of symbols.
458    hash.push_back(0);  // Dummy entry for the NULL symbol.
459    for (int i = 1; i < count - 1; i++) {
460      hash.push_back(i + 1);  // Each symbol points to the next one.
461    }
462    hash.push_back(0);  // Last symbol terminates the chain.
463    hash_.WriteFully(hash.data(), hash.size() * sizeof(hash[0]));
464    hash_.End();
465
466    dynamic_.Start();
467    Elf_Dyn dyns[] = {
468      { DT_HASH, { hash_.GetAddress() } },
469      { DT_STRTAB, { dynstr_.GetAddress() } },
470      { DT_SYMTAB, { dynsym_.GetAddress() } },
471      { DT_SYMENT, { sizeof(Elf_Sym) } },
472      { DT_STRSZ, { dynstr_.GetSize() } },
473      { DT_SONAME, { soname_offset } },
474      { DT_NULL, { 0 } },
475    };
476    dynamic_.WriteFully(&dyns, sizeof(dyns));
477    dynamic_.End();
478  }
479
480  // Returns true if all writes and seeks on the output stream succeeded.
481  bool Good() {
482    return stream_.Good();
483  }
484
485  // Returns the builder's internal stream.
486  OutputStream* GetStream() {
487    return &stream_;
488  }
489
490 private:
491  static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
492    Elf_Ehdr elf_header = Elf_Ehdr();
493    switch (isa) {
494      case kArm:
495        // Fall through.
496      case kThumb2: {
497        elf_header.e_machine = EM_ARM;
498        elf_header.e_flags = EF_ARM_EABI_VER5;
499        break;
500      }
501      case kArm64: {
502        elf_header.e_machine = EM_AARCH64;
503        elf_header.e_flags = 0;
504        break;
505      }
506      case kX86: {
507        elf_header.e_machine = EM_386;
508        elf_header.e_flags = 0;
509        break;
510      }
511      case kX86_64: {
512        elf_header.e_machine = EM_X86_64;
513        elf_header.e_flags = 0;
514        break;
515      }
516      case kMips: {
517        elf_header.e_machine = EM_MIPS;
518        elf_header.e_flags = (EF_MIPS_NOREORDER |
519                               EF_MIPS_PIC       |
520                               EF_MIPS_CPIC      |
521                               EF_MIPS_ABI_O32   |
522                               EF_MIPS_ARCH_32R2);
523        break;
524      }
525      case kMips64: {
526        elf_header.e_machine = EM_MIPS;
527        elf_header.e_flags = (EF_MIPS_NOREORDER |
528                               EF_MIPS_PIC       |
529                               EF_MIPS_CPIC      |
530                               EF_MIPS_ARCH_64R6);
531        break;
532      }
533      case kNone: {
534        LOG(FATAL) << "No instruction set";
535        break;
536      }
537      default: {
538        LOG(FATAL) << "Unknown instruction set " << isa;
539      }
540    }
541
542    elf_header.e_ident[EI_MAG0]       = ELFMAG0;
543    elf_header.e_ident[EI_MAG1]       = ELFMAG1;
544    elf_header.e_ident[EI_MAG2]       = ELFMAG2;
545    elf_header.e_ident[EI_MAG3]       = ELFMAG3;
546    elf_header.e_ident[EI_CLASS]      = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
547                                         ? ELFCLASS32 : ELFCLASS64;;
548    elf_header.e_ident[EI_DATA]       = ELFDATA2LSB;
549    elf_header.e_ident[EI_VERSION]    = EV_CURRENT;
550    elf_header.e_ident[EI_OSABI]      = ELFOSABI_LINUX;
551    elf_header.e_ident[EI_ABIVERSION] = 0;
552    elf_header.e_type = ET_DYN;
553    elf_header.e_version = 1;
554    elf_header.e_entry = 0;
555    elf_header.e_ehsize = sizeof(Elf_Ehdr);
556    elf_header.e_phentsize = sizeof(Elf_Phdr);
557    elf_header.e_shentsize = sizeof(Elf_Shdr);
558    elf_header.e_phoff = sizeof(Elf_Ehdr);
559    return elf_header;
560  }
561
562  // Create program headers based on written sections.
563  std::vector<Elf_Phdr> MakeProgramHeaders() {
564    CHECK(!sections_.empty());
565    std::vector<Elf_Phdr> phdrs;
566    {
567      // The program headers must start with PT_PHDR which is used in
568      // loaded process to determine the number of program headers.
569      Elf_Phdr phdr = Elf_Phdr();
570      phdr.p_type    = PT_PHDR;
571      phdr.p_flags   = PF_R;
572      phdr.p_offset  = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
573      phdr.p_filesz  = phdr.p_memsz = 0;  // We need to fill this later.
574      phdr.p_align   = sizeof(Elf_Off);
575      phdrs.push_back(phdr);
576      // Tell the linker to mmap the start of file to memory.
577      Elf_Phdr load = Elf_Phdr();
578      load.p_type    = PT_LOAD;
579      load.p_flags   = PF_R;
580      load.p_offset  = load.p_vaddr = load.p_paddr = 0;
581      load.p_filesz  = load.p_memsz = sections_[0]->header_.sh_offset;
582      load.p_align   = kPageSize;
583      phdrs.push_back(load);
584    }
585    // Create program headers for sections.
586    for (auto* section : sections_) {
587      const Elf_Shdr& shdr = section->header_;
588      if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
589        // PT_LOAD tells the linker to mmap part of the file.
590        // The linker can only mmap page-aligned sections.
591        // Single PT_LOAD may contain several ELF sections.
592        Elf_Phdr& prev = phdrs.back();
593        Elf_Phdr load = Elf_Phdr();
594        load.p_type   = PT_LOAD;
595        load.p_flags  = section->phdr_flags_;
596        load.p_offset = shdr.sh_offset;
597        load.p_vaddr  = load.p_paddr = shdr.sh_addr;
598        load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
599        load.p_memsz  = shdr.sh_size;
600        load.p_align  = shdr.sh_addralign;
601        if (prev.p_type == load.p_type &&
602            prev.p_flags == load.p_flags &&
603            prev.p_filesz == prev.p_memsz &&  // Do not merge .bss
604            load.p_filesz == load.p_memsz) {  // Do not merge .bss
605          // Merge this PT_LOAD with the previous one.
606          Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
607          prev.p_filesz = size;
608          prev.p_memsz  = size;
609        } else {
610          // If we are adding new load, it must be aligned.
611          CHECK_EQ(shdr.sh_addralign, (Elf_Word)kPageSize);
612          phdrs.push_back(load);
613        }
614      }
615    }
616    for (auto* section : sections_) {
617      const Elf_Shdr& shdr = section->header_;
618      if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
619        // Other PT_* types allow the program to locate interesting
620        // parts of memory at runtime. They must overlap with PT_LOAD.
621        if (section->phdr_type_ != 0) {
622          Elf_Phdr phdr = Elf_Phdr();
623          phdr.p_type   = section->phdr_type_;
624          phdr.p_flags  = section->phdr_flags_;
625          phdr.p_offset = shdr.sh_offset;
626          phdr.p_vaddr  = phdr.p_paddr = shdr.sh_addr;
627          phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
628          phdr.p_align  = shdr.sh_addralign;
629          phdrs.push_back(phdr);
630        }
631      }
632    }
633    // Set the size of the initial PT_PHDR.
634    CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
635    phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
636
637    return phdrs;
638  }
639
640  InstructionSet isa_;
641
642  ErrorDelayingOutputStream stream_;
643
644  Section rodata_;
645  Section text_;
646  Section bss_;
647  StringSection dynstr_;
648  SymbolSection dynsym_;
649  Section hash_;
650  Section dynamic_;
651  Section eh_frame_;
652  Section eh_frame_hdr_;
653  StringSection strtab_;
654  SymbolSection symtab_;
655  Section debug_frame_;
656  Section debug_info_;
657  Section debug_line_;
658  StringSection shstrtab_;
659  std::vector<std::unique_ptr<Section>> other_sections_;
660
661  // List of used section in the order in which they were written.
662  std::vector<Section*> sections_;
663
664  // Used for allocation of virtual address space.
665  Elf_Addr virtual_address_;
666
667  DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
668};
669
670}  // namespace art
671
672#endif  // ART_COMPILER_ELF_BUILDER_H_
673