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