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