• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_LIBELFFILE_ELF_ELF_BUILDER_H_
18 #define ART_LIBELFFILE_ELF_ELF_BUILDER_H_
19 
20 #include <vector>
21 #include <deque>
22 
23 #include "arch/instruction_set.h"
24 #include "base/array_ref.h"
25 #include "base/bit_utils.h"
26 #include "base/casts.h"
27 #include "base/leb128.h"
28 #include "base/unix_file/fd_file.h"
29 #include "elf/elf_utils.h"
30 #include "stream/error_delaying_output_stream.h"
31 
32 namespace 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 //   .note.gnu.build-id          - Optional build ID section (SHA-1 digest).
40 //   .dynstr                     - Names for .dynsym.
41 //   .dynsym                     - A few oat-specific dynamic symbols.
42 //   .hash                       - Hash-table for .dynsym.
43 //   .dynamic                    - Tags which let the linker locate .dynsym.
44 //   .rodata                     - Oat metadata.
45 //   .text                       - Compiled code.
46 //   .bss                        - Zero-initialized writeable section.
47 //   .dex                        - Reserved NOBITS space for dex-related data.
48 //   .strtab                     - Names for .symtab.
49 //   .symtab                     - Debug symbols.
50 //   .debug_frame                - Unwind information (CFI).
51 //   .debug_info                 - Debug information.
52 //   .debug_abbrev               - Decoding information for .debug_info.
53 //   .debug_str                  - Strings for .debug_info.
54 //   .debug_line                 - Line number tables.
55 //   .shstrtab                   - Names of ELF sections.
56 //   Elf_Shdr[]                  - Section headers.
57 //
58 // Some section are optional (the debug sections in particular).
59 //
60 // To reduce the amount of padding necessary to page-align sections with
61 // different permissions (and thus reduce disk usage), we group most read-only
62 // data sections together at the start of the file. This includes .dynstr,
63 // .dynsym, .hash, and .dynamic, whose contents are dependent on other sections.
64 // Therefore, when building the ELF we initially just reserve space for them,
65 // and write their contents later.
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 //
72 template <typename ElfTypes>
73 class ElfBuilder final {
74  public:
75   static constexpr size_t kMaxProgramHeaders = 16;
76   // SHA-1 digest.  Not using SHA_DIGEST_LENGTH from openssl/sha.h to avoid
77   // spreading this header dependency for just this single constant.
78   static constexpr size_t kBuildIdLen = 20;
79 
80   using Elf_Addr = typename ElfTypes::Addr;
81   using Elf_Off = typename ElfTypes::Off;
82   using Elf_Word = typename ElfTypes::Word;
83   using Elf_Sword = typename ElfTypes::Sword;
84   using Elf_Ehdr = typename ElfTypes::Ehdr;
85   using Elf_Shdr = typename ElfTypes::Shdr;
86   using Elf_Sym = typename ElfTypes::Sym;
87   using Elf_Phdr = typename ElfTypes::Phdr;
88   using Elf_Dyn = typename ElfTypes::Dyn;
89 
90   // Base class of all sections.
91   class Section : public OutputStream {
92    public:
Section(ElfBuilder<ElfTypes> * owner,const std::string & name,Elf_Word type,Elf_Word flags,const Section * link,Elf_Word info,Elf_Word align,Elf_Word entsize)93     Section(ElfBuilder<ElfTypes>* owner,
94             const std::string& name,
95             Elf_Word type,
96             Elf_Word flags,
97             const Section* link,
98             Elf_Word info,
99             Elf_Word align,
100             Elf_Word entsize)
101         : OutputStream(name),
102           owner_(owner),
103           header_(),
104           section_index_(0),
105           name_(name),
106           link_(link),
107           phdr_flags_(PF_R),
108           phdr_type_(0) {
109       DCHECK_GE(align, 1u);
110       header_.sh_type = type;
111       header_.sh_flags = flags;
112       header_.sh_info = info;
113       header_.sh_addralign = align;
114       header_.sh_entsize = entsize;
115     }
116 
117     // Allocate chunk of virtual memory for this section from the owning ElfBuilder.
118     // This must be done at the start for all SHF_ALLOC sections (i.e. mmaped by linker).
119     // It is fine to allocate section but never call Start/End() (e.g. the .bss section).
AllocateVirtualMemory(Elf_Word size)120     void AllocateVirtualMemory(Elf_Word size) {
121       AllocateVirtualMemory(owner_->virtual_address_, size);
122     }
123 
AllocateVirtualMemory(Elf_Addr addr,Elf_Word size)124     void AllocateVirtualMemory(Elf_Addr addr, Elf_Word size) {
125       CHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
126       Elf_Word align = AddSection();
127       CHECK_EQ(header_.sh_addr, 0u);
128       header_.sh_addr = RoundUp(addr, align);
129       CHECK(header_.sh_size == 0u || header_.sh_size == size);
130       header_.sh_size = size;
131       CHECK_LE(owner_->virtual_address_, header_.sh_addr);
132       owner_->virtual_address_ = header_.sh_addr + header_.sh_size;
133     }
134 
135     // Start writing file data of this section.
Start()136     virtual void Start() {
137       CHECK(owner_->current_section_ == nullptr);
138       Elf_Word align = AddSection();
139       CHECK_EQ(header_.sh_offset, 0u);
140       header_.sh_offset = owner_->AlignFileOffset(align);
141       owner_->current_section_ = this;
142     }
143 
144     // Finish writing file data of this section.
End()145     virtual void End() {
146       CHECK(owner_->current_section_ == this);
147       Elf_Word position = GetPosition();
148       CHECK(header_.sh_size == 0u || header_.sh_size == position);
149       header_.sh_size = position;
150       owner_->current_section_ = nullptr;
151     }
152 
153     // Get the number of bytes written so far.
154     // Only valid while writing the section.
GetPosition()155     Elf_Word GetPosition() const {
156       CHECK(owner_->current_section_ == this);
157       off_t file_offset = owner_->stream_.Seek(0, kSeekCurrent);
158       DCHECK_GE(file_offset, (off_t)header_.sh_offset);
159       return file_offset - header_.sh_offset;
160     }
161 
162     // Get the location of this section in virtual memory.
GetAddress()163     Elf_Addr GetAddress() const {
164       DCHECK_NE(header_.sh_flags & SHF_ALLOC, 0u);
165       DCHECK_NE(header_.sh_addr, 0u);
166       return header_.sh_addr;
167     }
168 
169     // This function always succeeds to simplify code.
170     // Use builder's Good() to check the actual status.
WriteFully(const void * buffer,size_t byte_count)171     bool WriteFully(const void* buffer, size_t byte_count) override {
172       CHECK(owner_->current_section_ == this);
173       return owner_->stream_.WriteFully(buffer, byte_count);
174     }
175 
176     // This function always succeeds to simplify code.
177     // Use builder's Good() to check the actual status.
Seek(off_t offset,Whence whence)178     off_t Seek(off_t offset, Whence whence) override {
179       // Forward the seek as-is and trust the caller to use it reasonably.
180       return owner_->stream_.Seek(offset, whence);
181     }
182 
183     // This function flushes the output and returns whether it succeeded.
184     // If there was a previous failure, this does nothing and returns false, i.e. failed.
Flush()185     bool Flush() override {
186       return owner_->stream_.Flush();
187     }
188 
GetSectionIndex()189     Elf_Word GetSectionIndex() const {
190       DCHECK_NE(section_index_, 0u);
191       return section_index_;
192     }
193 
194     // Returns true if this section has been added.
Exists()195     bool Exists() const {
196       return section_index_ != 0;
197     }
198 
199    protected:
200     // Add this section to the list of generated ELF sections (if not there already).
201     // It also ensures the alignment is sufficient to generate valid program headers,
202     // since that depends on the previous section. It returns the required alignment.
AddSection()203     Elf_Word AddSection() {
204       if (section_index_ == 0) {
205         std::vector<Section*>& sections = owner_->sections_;
206         Elf_Word last = sections.empty() ? PF_R : sections.back()->phdr_flags_;
207         if (phdr_flags_ != last) {
208           header_.sh_addralign = kElfSegmentAlignment;  // Page-align if R/W/X flags changed.
209         }
210         sections.push_back(this);
211         section_index_ = sections.size();  // First ELF section has index 1.
212       }
213       return owner_->write_program_headers_ ? header_.sh_addralign : 1;
214     }
215 
216     ElfBuilder<ElfTypes>* owner_;
217     Elf_Shdr header_;
218     Elf_Word section_index_;
219     const std::string name_;
220     const Section* const link_;
221     Elf_Word phdr_flags_;
222     Elf_Word phdr_type_;
223 
224     friend class ElfBuilder;
225 
226     DISALLOW_COPY_AND_ASSIGN(Section);
227   };
228 
229   class CachedSection : public Section {
230    public:
CachedSection(ElfBuilder<ElfTypes> * owner,const std::string & name,Elf_Word type,Elf_Word flags,const Section * link,Elf_Word info,Elf_Word align,Elf_Word entsize)231     CachedSection(ElfBuilder<ElfTypes>* owner,
232                   const std::string& name,
233                   Elf_Word type,
234                   Elf_Word flags,
235                   const Section* link,
236                   Elf_Word info,
237                   Elf_Word align,
238                   Elf_Word entsize)
239         : Section(owner, name, type, flags, link, info, align, entsize), cache_() { }
240 
Add(const void * data,size_t length)241     Elf_Word Add(const void* data, size_t length) {
242       Elf_Word offset = cache_.size();
243       const uint8_t* d = reinterpret_cast<const uint8_t*>(data);
244       cache_.insert(cache_.end(), d, d + length);
245       return offset;
246     }
247 
GetCacheSize()248     Elf_Word GetCacheSize() {
249       return cache_.size();
250     }
251 
Write()252     void Write() {
253       this->WriteFully(cache_.data(), cache_.size());
254       cache_.clear();
255       cache_.shrink_to_fit();
256     }
257 
WriteCachedSection()258     void WriteCachedSection() {
259       this->Start();
260       Write();
261       this->End();
262     }
263 
264    private:
265     std::vector<uint8_t> cache_;
266   };
267 
268   // Writer of .dynstr section.
269   class CachedStringSection final : public CachedSection {
270    public:
CachedStringSection(ElfBuilder<ElfTypes> * owner,const std::string & name,Elf_Word flags,Elf_Word align)271     CachedStringSection(ElfBuilder<ElfTypes>* owner,
272                         const std::string& name,
273                         Elf_Word flags,
274                         Elf_Word align)
275         : CachedSection(owner,
276                         name,
277                         SHT_STRTAB,
278                         flags,
279                         /* link= */ nullptr,
280                         /* info= */ 0,
281                         align,
282                         /* entsize= */ 0) { }
283 
Add(const std::string & name)284     Elf_Word Add(const std::string& name) {
285       if (CachedSection::GetCacheSize() == 0u) {
286         DCHECK(name.empty());
287       }
288       return CachedSection::Add(name.c_str(), name.length() + 1);
289     }
290   };
291 
292   // Writer of .strtab and .shstrtab sections.
293   class StringSection final : public Section {
294    public:
StringSection(ElfBuilder<ElfTypes> * owner,const std::string & name,Elf_Word flags,Elf_Word align)295     StringSection(ElfBuilder<ElfTypes>* owner,
296                   const std::string& name,
297                   Elf_Word flags,
298                   Elf_Word align)
299         : Section(owner,
300                   name,
301                   SHT_STRTAB,
302                   flags,
303                   /* link= */ nullptr,
304                   /* info= */ 0,
305                   align,
306                   /* entsize= */ 0) {
307       Reset();
308     }
309 
Reset()310     void Reset() {
311       current_offset_ = 0;
312       last_name_ = "";
313       last_offset_ = 0;
314     }
315 
Start()316     void Start() {
317       Section::Start();
318       Write("");  // ELF specification requires that the section starts with empty string.
319     }
320 
Write(std::string_view name)321     Elf_Word Write(std::string_view name) {
322       if (current_offset_ == 0) {
323         DCHECK(name.empty());
324       } else if (name == last_name_) {
325         return last_offset_;  // Very simple string de-duplication.
326       }
327       last_name_ = name;
328       last_offset_ = current_offset_;
329       this->WriteFully(name.data(), name.length());
330       char null_terminator = '\0';
331       this->WriteFully(&null_terminator, sizeof(null_terminator));
332       current_offset_ += name.length() + 1;
333       return last_offset_;
334     }
335 
336    private:
337     Elf_Word current_offset_;
338     std::string last_name_;
339     Elf_Word last_offset_;
340   };
341 
342   // Writer of .dynsym and .symtab sections.
343   class SymbolSection final : public Section {
344    public:
SymbolSection(ElfBuilder<ElfTypes> * owner,const std::string & name,Elf_Word type,Elf_Word flags,Section * strtab)345     SymbolSection(ElfBuilder<ElfTypes>* owner,
346                   const std::string& name,
347                   Elf_Word type,
348                   Elf_Word flags,
349                   Section* strtab)
350         : Section(owner,
351                   name,
352                   type,
353                   flags,
354                   strtab,
355                   /* info= */ 1,
356                   sizeof(Elf_Off),
357                   sizeof(Elf_Sym)) {
358       syms_.push_back(Elf_Sym());  // The symbol table always has to start with NULL symbol.
359     }
360 
361     // Buffer symbol for this section.  It will be written later.
Add(Elf_Word name,const Section * section,Elf_Addr addr,Elf_Word size,uint8_t binding,uint8_t type)362     void Add(Elf_Word name,
363              const Section* section,
364              Elf_Addr addr,
365              Elf_Word size,
366              uint8_t binding,
367              uint8_t type) {
368       Elf_Sym sym = Elf_Sym();
369       sym.st_name = name;
370       sym.st_value = addr;
371       sym.st_size = size;
372       sym.st_other = 0;
373       sym.st_info = (binding << 4) + (type & 0xf);
374       Add(sym, section);
375     }
376 
377     // Buffer symbol for this section.  It will be written later.
Add(Elf_Sym sym,const Section * section)378     void Add(Elf_Sym sym, const Section* section) {
379       if (section != nullptr) {
380         DCHECK_LE(section->GetAddress(), sym.st_value);
381         DCHECK_LE(sym.st_value, section->GetAddress() + section->header_.sh_size);
382         sym.st_shndx = section->GetSectionIndex();
383       } else {
384         sym.st_shndx = SHN_UNDEF;
385       }
386       syms_.push_back(sym);
387     }
388 
GetCacheSize()389     Elf_Word GetCacheSize() { return syms_.size() * sizeof(Elf_Sym); }
390 
WriteCachedSection()391     void WriteCachedSection() {
392       auto is_local = [](const Elf_Sym& sym) { return ELF_ST_BIND(sym.st_info) == STB_LOCAL; };
393       auto less_then = [is_local](const Elf_Sym& a, const Elf_Sym b) {
394         auto tuple_a = std::make_tuple(!is_local(a), a.st_value, a.st_name);
395         auto tuple_b = std::make_tuple(!is_local(b), b.st_value, b.st_name);
396         return tuple_a < tuple_b;  // Locals first, then sort by address and name offset.
397       };
398       if (!std::is_sorted(syms_.begin(), syms_.end(), less_then)) {
399         std::sort(syms_.begin(), syms_.end(), less_then);
400       }
401       auto locals_end = std::partition_point(syms_.begin(), syms_.end(), is_local);
402       this->header_.sh_info = locals_end - syms_.begin();  // Required by the spec.
403 
404       this->Start();
405       for (; !syms_.empty(); syms_.pop_front()) {
406         this->WriteFully(&syms_.front(), sizeof(Elf_Sym));
407       }
408       this->End();
409     }
410 
411    private:
412     std::deque<Elf_Sym> syms_;  // Buffered/cached content of the whole section.
413   };
414 
415   class BuildIdSection final : public Section {
416    public:
BuildIdSection(ElfBuilder<ElfTypes> * owner,const std::string & name,Elf_Word type,Elf_Word flags,const Section * link,Elf_Word info,Elf_Word align,Elf_Word entsize)417     BuildIdSection(ElfBuilder<ElfTypes>* owner,
418                    const std::string& name,
419                    Elf_Word type,
420                    Elf_Word flags,
421                    const Section* link,
422                    Elf_Word info,
423                    Elf_Word align,
424                    Elf_Word entsize)
425         : Section(owner, name, type, flags, link, info, align, entsize),
426           digest_start_(-1) {
427     }
428 
GetSize()429     Elf_Word GetSize() {
430       return 16 + kBuildIdLen;
431     }
432 
Write()433     void Write() {
434       // The size fields are 32-bit on both 32-bit and 64-bit systems, confirmed
435       // with the 64-bit linker and libbfd code. The size of name and desc must
436       // be a multiple of 4 and it currently is.
437       this->WriteUint32(4);  // namesz.
438       this->WriteUint32(kBuildIdLen);  // descsz.
439       this->WriteUint32(3);  // type = NT_GNU_BUILD_ID.
440       this->WriteFully("GNU", 4);  // name.
441       digest_start_ = this->Seek(0, kSeekCurrent);
442       static_assert(kBuildIdLen % 4 == 0, "expecting a mutliple of 4 for build ID length");
443       this->WriteFully(std::string(kBuildIdLen, '\0').c_str(), kBuildIdLen);  // desc.
444       DCHECK_EQ(this->GetPosition(), GetSize());
445     }
446 
GetDigestStart()447     off_t GetDigestStart() {
448       CHECK_GT(digest_start_, 0);
449       return digest_start_;
450     }
451 
452    private:
WriteUint32(uint32_t v)453     bool WriteUint32(uint32_t v) {
454       return this->WriteFully(&v, sizeof(v));
455     }
456 
457     // File offset where the build ID digest starts.
458     // Populated with zeros first, then updated with the actual value as the
459     // very last thing in the output file creation.
460     off_t digest_start_;
461   };
462 
ElfBuilder(InstructionSet isa,OutputStream * output)463   ElfBuilder(InstructionSet isa, OutputStream* output)
464       : isa_(isa),
465         stream_(output),
466         rodata_(this, ".rodata", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4u, 0),
467         text_(this, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR, nullptr, 0,
468             kElfSegmentAlignment, 0),
469         data_img_rel_ro_(this, ".data.img.rel.ro", SHT_PROGBITS, SHF_ALLOC, nullptr, 0,
470             kElfSegmentAlignment, 0),
471         bss_(this, ".bss", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kElfSegmentAlignment, 0),
472         dex_(this, ".dex", SHT_NOBITS, SHF_ALLOC, nullptr, 0, kElfSegmentAlignment, 0),
473         dynstr_(this, ".dynstr", SHF_ALLOC, 1),
474         dynsym_(this, ".dynsym", SHT_DYNSYM, SHF_ALLOC, &dynstr_),
475         hash_(this, ".hash", SHT_HASH, SHF_ALLOC, &dynsym_, 0, sizeof(Elf_Word), sizeof(Elf_Word)),
476         dynamic_(this, ".dynamic", SHT_DYNAMIC, SHF_ALLOC, &dynstr_, 0, sizeof(Elf_Addr),
477             sizeof(Elf_Dyn)),
478         strtab_(this, ".strtab", 0, 1),
479         symtab_(this, ".symtab", SHT_SYMTAB, 0, &strtab_),
480         debug_frame_(this, ".debug_frame", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
481         debug_frame_hdr_(
482             this, ".debug_frame_hdr.android", SHT_PROGBITS, 0, nullptr, 0, sizeof(Elf_Addr), 0),
483         debug_info_(this, ".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
484         debug_line_(this, ".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0),
485         shstrtab_(this, ".shstrtab", 0, 1),
486         build_id_(this, ".note.gnu.build-id", SHT_NOTE, SHF_ALLOC, nullptr, 0, 4, 0),
487         current_section_(nullptr),
488         started_(false),
489         finished_(false),
490         write_program_headers_(false),
491         loaded_size_(0u),
492         virtual_address_(0),
493         dynamic_sections_start_(0),
494         dynamic_sections_reserved_size_(0u) {
495     text_.phdr_flags_ = PF_R | PF_X;
496     data_img_rel_ro_.phdr_flags_ = PF_R | PF_W;  // Shall be made read-only at run time.
497     bss_.phdr_flags_ = PF_R | PF_W;
498     dex_.phdr_flags_ = PF_R;
499     dynamic_.phdr_flags_ = PF_R;
500     dynamic_.phdr_type_ = PT_DYNAMIC;
501     build_id_.phdr_type_ = PT_NOTE;
502   }
~ElfBuilder()503   ~ElfBuilder() {}
504 
GetIsa()505   InstructionSet GetIsa() { return isa_; }
GetBuildId()506   BuildIdSection* GetBuildId() { return &build_id_; }
GetRoData()507   Section* GetRoData() { return &rodata_; }
GetText()508   Section* GetText() { return &text_; }
GetDataImgRelRo()509   Section* GetDataImgRelRo() { return &data_img_rel_ro_; }
GetBss()510   Section* GetBss() { return &bss_; }
GetDex()511   Section* GetDex() { return &dex_; }
GetStrTab()512   StringSection* GetStrTab() { return &strtab_; }
GetSymTab()513   SymbolSection* GetSymTab() { return &symtab_; }
GetDebugFrame()514   Section* GetDebugFrame() { return &debug_frame_; }
GetDebugFrameHdr()515   Section* GetDebugFrameHdr() { return &debug_frame_hdr_; }
GetDebugInfo()516   Section* GetDebugInfo() { return &debug_info_; }
GetDebugLine()517   Section* GetDebugLine() { return &debug_line_; }
518 
WriteSection(const char * name,const std::vector<uint8_t> * buffer)519   void WriteSection(const char* name, const std::vector<uint8_t>* buffer) {
520     std::unique_ptr<Section> s(new Section(this, name, SHT_PROGBITS, 0, nullptr, 0, 1, 0));
521     s->Start();
522     s->WriteFully(buffer->data(), buffer->size());
523     s->End();
524     other_sections_.push_back(std::move(s));
525   }
526 
527   // Reserve space for ELF header and program headers.
528   // We do not know the number of headers until later, so
529   // it is easiest to just reserve a fixed amount of space.
530   // Program headers are required for loading by the linker.
531   // It is possible to omit them for ELF files used for debugging.
532   void Start(bool write_program_headers = true) {
533     int size = sizeof(Elf_Ehdr);
534     if (write_program_headers) {
535       size += sizeof(Elf_Phdr) * kMaxProgramHeaders;
536     }
537     stream_.Seek(size, kSeekSet);
538     started_ = true;
539     virtual_address_ += size;
540     write_program_headers_ = write_program_headers;
541   }
542 
End()543   off_t End() {
544     DCHECK(started_);
545     DCHECK(!finished_);
546     finished_ = true;
547 
548     // Note: loaded_size_ == 0 for tests that don't write .rodata, .text, .bss,
549     // .dynstr, dynsym, .hash and .dynamic. These tests should not read loaded_size_.
550     CHECK(loaded_size_ == 0 || loaded_size_ == RoundUp(virtual_address_, kElfSegmentAlignment))
551         << loaded_size_ << " " << virtual_address_;
552 
553     // Write section names and finish the section headers.
554     shstrtab_.Start();
555     shstrtab_.Write("");
556     for (auto* section : sections_) {
557       section->header_.sh_name = shstrtab_.Write(section->name_);
558       if (section->link_ != nullptr) {
559         section->header_.sh_link = section->link_->GetSectionIndex();
560       }
561       if (section->header_.sh_offset == 0) {
562         section->header_.sh_type = SHT_NOBITS;
563       }
564     }
565     shstrtab_.End();
566 
567     // Write section headers at the end of the ELF file.
568     std::vector<Elf_Shdr> shdrs;
569     shdrs.reserve(1u + sections_.size());
570     shdrs.push_back(Elf_Shdr());  // NULL at index 0.
571     for (auto* section : sections_) {
572       shdrs.push_back(section->header_);
573     }
574     Elf_Off section_headers_offset;
575     section_headers_offset = AlignFileOffset(sizeof(Elf_Off));
576     stream_.WriteFully(shdrs.data(), shdrs.size() * sizeof(shdrs[0]));
577     off_t file_size = stream_.Seek(0, kSeekCurrent);
578 
579     // Flush everything else before writing the program headers. This should prevent
580     // the OS from reordering writes, so that we don't end up with valid headers
581     // and partially written data if we suddenly lose power, for example.
582     stream_.Flush();
583 
584     // The main ELF header.
585     Elf_Ehdr elf_header = MakeElfHeader(isa_);
586     elf_header.e_shoff = section_headers_offset;
587     elf_header.e_shnum = shdrs.size();
588     elf_header.e_shstrndx = shstrtab_.GetSectionIndex();
589 
590     // Program headers (i.e. mmap instructions).
591     std::vector<Elf_Phdr> phdrs;
592     if (write_program_headers_) {
593       phdrs = MakeProgramHeaders();
594       CHECK_LE(phdrs.size(), kMaxProgramHeaders);
595       elf_header.e_phoff = sizeof(Elf_Ehdr);
596       elf_header.e_phnum = phdrs.size();
597     }
598 
599     stream_.Seek(0, kSeekSet);
600     stream_.WriteFully(&elf_header, sizeof(elf_header));
601     stream_.WriteFully(phdrs.data(), phdrs.size() * sizeof(phdrs[0]));
602     stream_.Flush();
603 
604     return file_size;
605   }
606 
607   // This has the same effect as running the "strip" command line tool.
608   // It removes all debugging sections (but it keeps mini-debug-info).
609   // It returns the ELF file size (as the caller needs to truncate it).
Strip()610   off_t Strip() {
611     DCHECK(finished_);
612     finished_ = false;
613     Elf_Off end = 0;
614     std::vector<Section*> non_debug_sections;
615     for (Section* section : sections_) {
616       if (section == &shstrtab_ ||  // Section names will be recreated.
617           section == &symtab_ ||
618           section == &strtab_ ||
619           section->name_.find(".debug_") == 0) {
620         section->header_.sh_offset = 0;
621         section->header_.sh_size = 0;
622         section->section_index_ = 0;
623       } else {
624         if (section->header_.sh_type != SHT_NOBITS) {
625           DCHECK_LE(section->header_.sh_offset, end + kElfSegmentAlignment)
626               << "Large gap between sections";
627           end = std::max<off_t>(end, section->header_.sh_offset + section->header_.sh_size);
628         }
629         non_debug_sections.push_back(section);
630       }
631     }
632     shstrtab_.Reset();
633     // Write the non-debug section headers, program headers, and ELF header again.
634     sections_ = std::move(non_debug_sections);
635     stream_.Seek(end, kSeekSet);
636     return End();
637   }
638 
639   // Reserve space for: .dynstr, .dynsym, .hash and .dynamic.
640   //
641   // Dynamic section content is dependent on subsequent sections. Here, reserve enough
642   // space for it. We will write the content later (in PrepareDynamicSection).
ReserveSpaceForDynamicSection(const std::string & elf_file_path)643   void ReserveSpaceForDynamicSection(const std::string& elf_file_path) {
644     CHECK_EQ(dynamic_sections_start_, 0);
645     CHECK_EQ(dynamic_sections_reserved_size_, 0u);
646     CHECK(!rodata_.Exists());
647 
648     off_t offset = stream_.Seek(0, kSeekCurrent);
649     dynamic_sections_start_ = offset;
650 
651     dynstr_.AddSection();
652     // We don't expect that .dynstr section can have any alignment requirements.
653     DCHECK_EQ(dynstr_.header_.sh_addralign, 1u);
654     offset += []() consteval {
655       size_t size = 0;
656       for (size_t i = 0; i < kDynamicSymbolCount; i++) {
657         DynamicSymbol sym = static_cast<DynamicSymbol>(i);
658         size += GetDynamicSymbolName(sym).length() + 1;
659       }
660       return size;
661     }();
662     offset += GetSoname(elf_file_path).length() + 1;
663 
664     dynsym_.AddSection();
665     offset = RoundUp(offset, dynsym_.header_.sh_addralign);
666     offset += kDynamicSymbolCount * sizeof(Elf_Sym);
667 
668     hash_.AddSection();
669     offset = RoundUp(offset, hash_.header_.sh_addralign);
670     offset += PrepareDynamicSymbolHashtable(kDynamicSymbolCount, /*hashtable=*/ nullptr);
671 
672     dynamic_.AddSection();
673     offset = RoundUp(offset, dynamic_.header_.sh_addralign);
674     offset += kDynamicEntriesCount * sizeof(Elf_Dyn);
675 
676     dynamic_sections_reserved_size_ = offset - dynamic_sections_start_;
677 
678     stream_.Seek(offset, kSeekSet);
679   }
680 
681   // The running program does not have access to section headers
682   // and the loader is not supposed to use them either.
683   // The dynamic sections therefore replicates some of the layout
684   // information like the address and size of .rodata and .text.
685   // It also contains other metadata like the SONAME.
686   // The .dynamic section is found using the PT_DYNAMIC program header.
PrepareDynamicSection(const std::string & elf_file_path,Elf_Word rodata_size,Elf_Word text_size,Elf_Word data_img_rel_ro_size,Elf_Word data_img_rel_ro_app_image_offset,Elf_Word bss_size,Elf_Word bss_methods_offset,Elf_Word bss_roots_offset,Elf_Word dex_size)687   void PrepareDynamicSection(const std::string& elf_file_path,
688                              Elf_Word rodata_size,
689                              Elf_Word text_size,
690                              Elf_Word data_img_rel_ro_size,
691                              Elf_Word data_img_rel_ro_app_image_offset,
692                              Elf_Word bss_size,
693                              Elf_Word bss_methods_offset,
694                              Elf_Word bss_roots_offset,
695                              Elf_Word dex_size) {
696     CHECK_NE(dynamic_sections_reserved_size_, 0u);
697 
698     // Skip over the reserved memory for dynamic sections - we prepare them later
699     // due to dependencies.
700     Elf_Addr dynamic_sections_address = virtual_address_;
701     virtual_address_ += dynamic_sections_reserved_size_;
702 
703     rodata_.AllocateVirtualMemory(rodata_size);
704     text_.AllocateVirtualMemory(text_size);
705     if (data_img_rel_ro_size != 0) {
706       data_img_rel_ro_.AllocateVirtualMemory(data_img_rel_ro_size);
707     }
708     if (bss_size != 0) {
709       bss_.AllocateVirtualMemory(bss_size);
710     }
711     if (dex_size != 0) {
712       dex_.AllocateVirtualMemory(dex_size);
713     }
714 
715     // Cache .dynstr, .dynsym and .hash data.
716     dynstr_.Add("");  // dynstr should start with empty string.
717     Elf_Word oatdata = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatData));
718     dynsym_.Add(oatdata, &rodata_, rodata_.GetAddress(), rodata_size, STB_GLOBAL, STT_OBJECT);
719     if (text_size != 0u) {
720       // The runtime does not care about the size of this symbol (it uses the "lastword" symbol).
721       // We use size 0 (meaning "unknown size" in ELF) to prevent overlap with the debug symbols.
722       Elf_Word oatexec = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatExec));
723       dynsym_.Add(oatexec, &text_, text_.GetAddress(), /* size= */ 0, STB_GLOBAL, STT_OBJECT);
724       Elf_Word oatlastword = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatLastWord));
725       Elf_Word oatlastword_address = text_.GetAddress() + text_size - 4;
726       dynsym_.Add(oatlastword, &text_, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
727     } else if (rodata_size != 0) {
728       // rodata_ can be size 0 for dwarf_test.
729       Elf_Word oatlastword = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatLastWord));
730       Elf_Word oatlastword_address = rodata_.GetAddress() + rodata_size - 4;
731       dynsym_.Add(oatlastword, &rodata_, oatlastword_address, 4, STB_GLOBAL, STT_OBJECT);
732     }
733     DCHECK_LE(data_img_rel_ro_app_image_offset, data_img_rel_ro_size);
734     if (data_img_rel_ro_size != 0u) {
735       Elf_Word oatdataimgrelro = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatDataImgRelRo));
736       dynsym_.Add(oatdataimgrelro,
737                   &data_img_rel_ro_,
738                   data_img_rel_ro_.GetAddress(),
739                   data_img_rel_ro_size,
740                   STB_GLOBAL,
741                   STT_OBJECT);
742       Elf_Word oatdataimgrelrolastword =
743           dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatDataImgRelRoLastWord));
744       dynsym_.Add(oatdataimgrelrolastword,
745                   &data_img_rel_ro_,
746                   data_img_rel_ro_.GetAddress() + data_img_rel_ro_size - 4,
747                   4,
748                   STB_GLOBAL,
749                   STT_OBJECT);
750       if (data_img_rel_ro_app_image_offset != data_img_rel_ro_size) {
751         Elf_Word oatdataimgrelroappimage =
752             dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatDataImgRelRoAppImage));
753         dynsym_.Add(oatdataimgrelroappimage,
754                     &data_img_rel_ro_,
755                     data_img_rel_ro_.GetAddress() + data_img_rel_ro_app_image_offset,
756                     data_img_rel_ro_app_image_offset,
757                     STB_GLOBAL,
758                     STT_OBJECT);
759       }
760     }
761     DCHECK_LE(bss_roots_offset, bss_size);
762     if (bss_size != 0u) {
763       Elf_Word oatbss = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatBss));
764       dynsym_.Add(oatbss, &bss_, bss_.GetAddress(), bss_roots_offset, STB_GLOBAL, STT_OBJECT);
765       DCHECK_LE(bss_methods_offset, bss_roots_offset);
766       DCHECK_LE(bss_roots_offset, bss_size);
767       // Add a symbol marking the start of the methods part of the .bss, if not empty.
768       if (bss_methods_offset != bss_roots_offset) {
769         Elf_Word bss_methods_address = bss_.GetAddress() + bss_methods_offset;
770         Elf_Word bss_methods_size = bss_roots_offset - bss_methods_offset;
771         Elf_Word oatbssroots = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatBssMethods));
772         dynsym_.Add(
773             oatbssroots, &bss_, bss_methods_address, bss_methods_size, STB_GLOBAL, STT_OBJECT);
774       }
775       // Add a symbol marking the start of the GC roots part of the .bss, if not empty.
776       if (bss_roots_offset != bss_size) {
777         Elf_Word bss_roots_address = bss_.GetAddress() + bss_roots_offset;
778         Elf_Word bss_roots_size = bss_size - bss_roots_offset;
779         Elf_Word oatbssroots = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatBssRoots));
780         dynsym_.Add(
781             oatbssroots, &bss_, bss_roots_address, bss_roots_size, STB_GLOBAL, STT_OBJECT);
782       }
783       Elf_Word oatbsslastword = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatBssLastWord));
784       Elf_Word bsslastword_address = bss_.GetAddress() + bss_size - 4;
785       dynsym_.Add(oatbsslastword, &bss_, bsslastword_address, 4, STB_GLOBAL, STT_OBJECT);
786     }
787     if (dex_size != 0u) {
788       Elf_Word oatdex = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatDex));
789       dynsym_.Add(oatdex, &dex_, dex_.GetAddress(), /* size= */ 0, STB_GLOBAL, STT_OBJECT);
790       Elf_Word oatdexlastword = dynstr_.Add(GetDynamicSymbolName(DynamicSymbol::kOatDexLastWord));
791       Elf_Word oatdexlastword_address = dex_.GetAddress() + dex_size - 4;
792       dynsym_.Add(oatdexlastword, &dex_, oatdexlastword_address, 4, STB_GLOBAL, STT_OBJECT);
793     }
794 
795     Elf_Word soname_offset = dynstr_.Add(GetSoname(elf_file_path));
796 
797     // We do not really need a hash-table since there is so few entries.
798     // However, the hash-table is the only way the linker can actually
799     // determine the number of symbols in .dynsym so it is required.
800     int count = dynsym_.GetCacheSize() / sizeof(Elf_Sym);  // Includes NULL.
801     std::vector<Elf_Word> hash;
802     PrepareDynamicSymbolHashtable(count, &hash);
803     hash_.Add(hash.data(), hash.size() * sizeof(hash[0]));
804 
805     Elf_Addr current_virtual_address = virtual_address_;
806     virtual_address_ = dynamic_sections_address;
807 
808     // Allocate all remaining sections.
809     dynstr_.AllocateVirtualMemory(dynstr_.GetCacheSize());
810     dynsym_.AllocateVirtualMemory(dynsym_.GetCacheSize());
811     hash_.AllocateVirtualMemory(hash_.GetCacheSize());
812 
813     Elf_Dyn dyns[] = {
814       { .d_tag = DT_HASH,   .d_un = { .d_ptr = hash_.GetAddress() }, },
815       { .d_tag = DT_STRTAB, .d_un = { .d_ptr = dynstr_.GetAddress() }, },
816       { .d_tag = DT_SYMTAB, .d_un = { .d_ptr = dynsym_.GetAddress() }, },
817       { .d_tag = DT_SYMENT, .d_un = { .d_ptr = sizeof(Elf_Sym) }, },
818       { .d_tag = DT_STRSZ,  .d_un = { .d_ptr = dynstr_.GetCacheSize() }, },
819       { .d_tag = DT_SONAME, .d_un = { .d_ptr = soname_offset }, },
820       { .d_tag = DT_NULL,   .d_un = { .d_ptr = 0 }, },
821     };
822     static_assert(sizeof(dyns) == kDynamicEntriesCount * sizeof(dyns[0]));
823 
824     dynamic_.Add(&dyns, sizeof(dyns));
825     dynamic_.AllocateVirtualMemory(dynamic_.GetCacheSize());
826 
827     CHECK_LE(virtual_address_, rodata_.GetAddress());
828     virtual_address_ = current_virtual_address;
829 
830     loaded_size_ = RoundUp(virtual_address_, kElfSegmentAlignment);
831   }
832 
WriteDynamicSection()833   void WriteDynamicSection() {
834     CHECK_NE(dynamic_sections_start_, 0);
835     CHECK_NE(dynamic_sections_reserved_size_, 0u);
836 
837     off_t current_offset = stream_.Seek(0, kSeekCurrent);
838     stream_.Seek(dynamic_sections_start_, kSeekSet);
839 
840     dynstr_.WriteCachedSection();
841     dynsym_.WriteCachedSection();
842     hash_.WriteCachedSection();
843     dynamic_.WriteCachedSection();
844 
845     DCHECK_LE(stream_.Seek(0, kSeekCurrent),
846         static_cast<off_t>(dynamic_sections_start_ + dynamic_sections_reserved_size_));
847     stream_.Seek(current_offset, kSeekSet);
848   }
849 
GetLoadedSize()850   Elf_Word GetLoadedSize() {
851     CHECK_NE(loaded_size_, 0u);
852     return loaded_size_;
853   }
854 
WriteBuildIdSection()855   void WriteBuildIdSection() {
856     build_id_.Start();
857     build_id_.Write();
858     build_id_.End();
859   }
860 
WriteBuildId(uint8_t build_id[kBuildIdLen])861   void WriteBuildId(uint8_t build_id[kBuildIdLen]) {
862     stream_.Seek(build_id_.GetDigestStart(), kSeekSet);
863     stream_.WriteFully(build_id, kBuildIdLen);
864     stream_.Flush();
865   }
866 
867   // Returns true if all writes and seeks on the output stream succeeded.
Good()868   bool Good() {
869     return stream_.Good();
870   }
871 
872   // Returns the builder's internal stream.
GetStream()873   OutputStream* GetStream() {
874     return &stream_;
875   }
876 
AlignFileOffset(size_t alignment)877   off_t AlignFileOffset(size_t alignment) {
878      return stream_.Seek(RoundUp(stream_.Seek(0, kSeekCurrent), alignment), kSeekSet);
879   }
880 
GetIsaFromHeader(const Elf_Ehdr & header)881   static InstructionSet GetIsaFromHeader(const Elf_Ehdr& header) {
882     switch (header.e_machine) {
883       case EM_ARM:
884         return InstructionSet::kThumb2;
885       case EM_AARCH64:
886         return InstructionSet::kArm64;
887       case EM_RISCV:
888         return InstructionSet::kRiscv64;
889       case EM_386:
890         return InstructionSet::kX86;
891       case EM_X86_64:
892         return InstructionSet::kX86_64;
893     }
894     LOG(FATAL) << "Unknown architecture: " << header.e_machine;
895     UNREACHABLE();
896   }
897 
898  private:
MakeElfHeader(InstructionSet isa)899   static Elf_Ehdr MakeElfHeader(InstructionSet isa) {
900     Elf_Ehdr elf_header = Elf_Ehdr();
901     switch (isa) {
902       case InstructionSet::kArm:
903         // Fall through.
904       case InstructionSet::kThumb2: {
905         elf_header.e_machine = EM_ARM;
906         elf_header.e_flags = EF_ARM_EABI_VER5;
907         break;
908       }
909       case InstructionSet::kArm64: {
910         elf_header.e_machine = EM_AARCH64;
911         elf_header.e_flags = 0;
912         break;
913       }
914       case InstructionSet::kRiscv64: {
915         elf_header.e_machine = EM_RISCV;
916         elf_header.e_flags = EF_RISCV_RVC | EF_RISCV_FLOAT_ABI_DOUBLE;
917         break;
918       }
919       case InstructionSet::kX86: {
920         elf_header.e_machine = EM_386;
921         elf_header.e_flags = 0;
922         break;
923       }
924       case InstructionSet::kX86_64: {
925         elf_header.e_machine = EM_X86_64;
926         elf_header.e_flags = 0;
927         break;
928       }
929       case InstructionSet::kNone: {
930         LOG(FATAL) << "No instruction set";
931         break;
932       }
933       default: {
934         LOG(FATAL) << "Unknown instruction set " << isa;
935       }
936     }
937     DCHECK_EQ(GetIsaFromHeader(elf_header),
938               (isa == InstructionSet::kArm) ? InstructionSet::kThumb2 : isa);
939 
940     elf_header.e_ident[EI_MAG0]       = ELFMAG0;
941     elf_header.e_ident[EI_MAG1]       = ELFMAG1;
942     elf_header.e_ident[EI_MAG2]       = ELFMAG2;
943     elf_header.e_ident[EI_MAG3]       = ELFMAG3;
944     elf_header.e_ident[EI_CLASS]      = (sizeof(Elf_Addr) == sizeof(Elf32_Addr))
945                                          ? ELFCLASS32 : ELFCLASS64;
946     elf_header.e_ident[EI_DATA]       = ELFDATA2LSB;
947     elf_header.e_ident[EI_VERSION]    = EV_CURRENT;
948     elf_header.e_ident[EI_OSABI]      = ELFOSABI_LINUX;
949     elf_header.e_ident[EI_ABIVERSION] = 0;
950     elf_header.e_type = ET_DYN;
951     elf_header.e_version = 1;
952     elf_header.e_entry = 0;
953     elf_header.e_ehsize = sizeof(Elf_Ehdr);
954     elf_header.e_phentsize = sizeof(Elf_Phdr);
955     elf_header.e_shentsize = sizeof(Elf_Shdr);
956     return elf_header;
957   }
958 
959   // Create program headers based on written sections.
MakeProgramHeaders()960   std::vector<Elf_Phdr> MakeProgramHeaders() {
961     CHECK(!sections_.empty());
962     std::vector<Elf_Phdr> phdrs;
963     {
964       // The program headers must start with PT_PHDR which is used in
965       // loaded process to determine the number of program headers.
966       Elf_Phdr phdr = Elf_Phdr();
967       phdr.p_type    = PT_PHDR;
968       phdr.p_flags   = PF_R;
969       phdr.p_offset  = phdr.p_vaddr = phdr.p_paddr = sizeof(Elf_Ehdr);
970       phdr.p_filesz  = phdr.p_memsz = 0;  // We need to fill this later.
971       phdr.p_align   = sizeof(Elf_Off);
972       phdrs.push_back(phdr);
973       // Tell the linker to mmap the start of file to memory.
974       Elf_Phdr load = Elf_Phdr();
975       load.p_type    = PT_LOAD;
976       load.p_flags   = PF_R;
977       load.p_offset  = load.p_vaddr = load.p_paddr = 0;
978       load.p_filesz  = load.p_memsz = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * kMaxProgramHeaders;
979       load.p_align   = kElfSegmentAlignment;
980       phdrs.push_back(load);
981     }
982     // Create program headers for sections.
983     for (auto* section : sections_) {
984       const Elf_Shdr& shdr = section->header_;
985       if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
986         DCHECK(shdr.sh_addr != 0u) << "Allocate virtual memory for the section";
987         // PT_LOAD tells the linker to mmap part of the file.
988         // The linker can only mmap page-aligned sections.
989         // Single PT_LOAD may contain several ELF sections.
990         Elf_Phdr& prev = phdrs.back();
991         Elf_Phdr load = Elf_Phdr();
992         load.p_type   = PT_LOAD;
993         load.p_flags  = section->phdr_flags_;
994         load.p_offset = shdr.sh_offset;
995         load.p_vaddr  = load.p_paddr = shdr.sh_addr;
996         load.p_filesz = (shdr.sh_type != SHT_NOBITS ? shdr.sh_size : 0u);
997         load.p_memsz  = shdr.sh_size;
998         load.p_align  = shdr.sh_addralign;
999         if (prev.p_type == load.p_type &&
1000             prev.p_flags == load.p_flags &&
1001             prev.p_filesz == prev.p_memsz &&  // Do not merge .bss
1002             load.p_filesz == load.p_memsz) {  // Do not merge .bss
1003           // Merge this PT_LOAD with the previous one.
1004           Elf_Word size = shdr.sh_offset + shdr.sh_size - prev.p_offset;
1005           prev.p_filesz = size;
1006           prev.p_memsz  = size;
1007         } else {
1008           // If we are adding new load, it must be aligned.
1009           CHECK_EQ(shdr.sh_addralign, (Elf_Word)kElfSegmentAlignment);
1010           phdrs.push_back(load);
1011         }
1012       }
1013     }
1014     for (auto* section : sections_) {
1015       const Elf_Shdr& shdr = section->header_;
1016       if ((shdr.sh_flags & SHF_ALLOC) != 0 && shdr.sh_size != 0) {
1017         // Other PT_* types allow the program to locate interesting
1018         // parts of memory at runtime. They must overlap with PT_LOAD.
1019         if (section->phdr_type_ != 0) {
1020           Elf_Phdr phdr = Elf_Phdr();
1021           phdr.p_type   = section->phdr_type_;
1022           phdr.p_flags  = section->phdr_flags_;
1023           phdr.p_offset = shdr.sh_offset;
1024           phdr.p_vaddr  = phdr.p_paddr = shdr.sh_addr;
1025           phdr.p_filesz = phdr.p_memsz = shdr.sh_size;
1026           phdr.p_align  = shdr.sh_addralign;
1027           phdrs.push_back(phdr);
1028         }
1029       }
1030     }
1031     // Set the size of the initial PT_PHDR.
1032     CHECK_EQ(phdrs[0].p_type, (Elf_Word)PT_PHDR);
1033     phdrs[0].p_filesz = phdrs[0].p_memsz = phdrs.size() * sizeof(Elf_Phdr);
1034 
1035     return phdrs;
1036   }
1037 
1038   enum class DynamicSymbol {
1039     kNull,
1040     kOatData,
1041     kOatExec,
1042     kOatLastWord,
1043     kOatDataImgRelRo,
1044     kOatDataImgRelRoLastWord,
1045     kOatDataImgRelRoAppImage,
1046     kOatBss,
1047     kOatBssMethods,
1048     kOatBssRoots,
1049     kOatBssLastWord,
1050     kOatDex,
1051     kOatDexLastWord,
1052     kLast = kOatDexLastWord
1053   };
1054 
1055   static constexpr size_t kDynamicSymbolCount = static_cast<size_t>(DynamicSymbol::kLast) + 1;
1056   static constexpr size_t kDynamicEntriesCount = 7;
1057 
GetDynamicSymbolName(DynamicSymbol sym)1058   static constexpr std::string GetDynamicSymbolName(DynamicSymbol sym) {
1059     switch (sym) {
1060       case DynamicSymbol::kNull:
1061         return "";
1062       case DynamicSymbol::kOatData:
1063         return "oatdata";
1064       case DynamicSymbol::kOatExec:
1065         return "oatexec";
1066       case DynamicSymbol::kOatLastWord:
1067         return "oatlastword";
1068       case DynamicSymbol::kOatDataImgRelRo:
1069         return "oatdataimgrelro";
1070       case DynamicSymbol::kOatDataImgRelRoLastWord:
1071         return "oatdataimgrelrolastword";
1072       case DynamicSymbol::kOatDataImgRelRoAppImage:
1073         return "oatdataimgrelroappimage";
1074       case DynamicSymbol::kOatBss:
1075         return "oatbss";
1076       case DynamicSymbol::kOatBssMethods:
1077         return "oatbssmethods";
1078       case DynamicSymbol::kOatBssRoots:
1079         return "oatbssroots";
1080       case DynamicSymbol::kOatBssLastWord:
1081         return "oatbsslastword";
1082       case DynamicSymbol::kOatDex:
1083         return "oatdex";
1084       case DynamicSymbol::kOatDexLastWord:
1085         return "oatdexlastword";
1086     }
1087   }
1088 
1089   // This method builds a hashtable for dynamic symbols using `hashtable` as a storage.
1090   // If `hashtable` is nullptr, it just calculate its size in bytes and returns it.
PrepareDynamicSymbolHashtable(size_t count,std::vector<Elf_Word> * hashtable)1091   static size_t PrepareDynamicSymbolHashtable(size_t count, std::vector<Elf_Word> *hashtable) {
1092     size_t size = 0;
1093     auto write = [&size, hashtable](Elf_Word value) {
1094       if (hashtable) {
1095         hashtable->push_back(value);
1096       }
1097       size += sizeof(value);
1098     };
1099 
1100     write(1);  // Number of buckets.
1101     write(count);  // Number of chains.
1102     // Buckets.  Having just one makes it linear search.
1103     write(1);  // Point to first non-NULL symbol.
1104     // Chains.  This creates linked list of symbols.
1105     write(0);  // Placeholder entry for the NULL symbol.
1106     for (size_t i = 1; i < count - 1; i++) {
1107       write(i + 1);  // Each symbol points to the next one.
1108     }
1109     write(0);  // Last symbol terminates the chain.
1110 
1111     return size;
1112   }
1113 
GetSoname(const std::string & elf_file_path)1114   static std::string GetSoname(const std::string& elf_file_path) {
1115     std::string soname(elf_file_path);
1116     size_t directory_separator_pos = soname.rfind('/');
1117     if (directory_separator_pos != std::string::npos) {
1118       soname = soname.substr(directory_separator_pos + 1);
1119     }
1120     return soname;
1121   }
1122 
1123   InstructionSet isa_;
1124 
1125   ErrorDelayingOutputStream stream_;
1126 
1127   Section rodata_;
1128   Section text_;
1129   Section data_img_rel_ro_;
1130   Section bss_;
1131   Section dex_;
1132   CachedStringSection dynstr_;
1133   SymbolSection dynsym_;
1134   CachedSection hash_;
1135   CachedSection dynamic_;
1136   StringSection strtab_;
1137   SymbolSection symtab_;
1138   Section debug_frame_;
1139   Section debug_frame_hdr_;
1140   Section debug_info_;
1141   Section debug_line_;
1142   StringSection shstrtab_;
1143   BuildIdSection build_id_;
1144   std::vector<std::unique_ptr<Section>> other_sections_;
1145 
1146   // List of used section in the order in which they were written.
1147   std::vector<Section*> sections_;
1148   Section* current_section_;  // The section which is currently being written.
1149 
1150   bool started_;
1151   bool finished_;
1152   bool write_program_headers_;
1153 
1154   // The size of the memory taken by the ELF file when loaded.
1155   size_t loaded_size_;
1156 
1157   // Used for allocation of virtual address space.
1158   Elf_Addr virtual_address_;
1159 
1160   // Offset in the ELF where the first dynamic section is written (.dynstr).
1161   off_t dynamic_sections_start_;
1162 
1163   // Size reserved for dynamic sections: .dynstr, .dynsym, .hash and .dynamic.
1164   size_t dynamic_sections_reserved_size_;
1165 
1166   DISALLOW_COPY_AND_ASSIGN(ElfBuilder);
1167 };
1168 
1169 }  // namespace art
1170 
1171 #endif  // ART_LIBELFFILE_ELF_ELF_BUILDER_H_
1172