1 //===- OutputSections.cpp -------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "OutputSections.h" 10 #include "Config.h" 11 #include "LinkerScript.h" 12 #include "SymbolTable.h" 13 #include "SyntheticSections.h" 14 #include "Target.h" 15 #include "lld/Common/Memory.h" 16 #include "lld/Common/Strings.h" 17 #include "llvm/BinaryFormat/Dwarf.h" 18 #include "llvm/Support/Compression.h" 19 #include "llvm/Support/MD5.h" 20 #include "llvm/Support/MathExtras.h" 21 #include "llvm/Support/Parallel.h" 22 #include "llvm/Support/SHA1.h" 23 #include <regex> 24 #include <unordered_set> 25 26 using namespace llvm; 27 using namespace llvm::dwarf; 28 using namespace llvm::object; 29 using namespace llvm::support::endian; 30 using namespace llvm::ELF; 31 using namespace lld; 32 using namespace lld::elf; 33 34 uint8_t *Out::bufferStart; 35 uint8_t Out::first; 36 PhdrEntry *Out::tlsPhdr; 37 OutputSection *Out::elfHeader; 38 OutputSection *Out::programHeaders; 39 OutputSection *Out::preinitArray; 40 OutputSection *Out::initArray; 41 OutputSection *Out::finiArray; 42 43 std::vector<OutputSection *> elf::outputSections; 44 45 uint32_t OutputSection::getPhdrFlags() const { 46 uint32_t ret = 0; 47 if (config->emachine != EM_ARM || !(flags & SHF_ARM_PURECODE)) 48 ret |= PF_R; 49 if (flags & SHF_WRITE) 50 ret |= PF_W; 51 if (flags & SHF_EXECINSTR) 52 ret |= PF_X; 53 return ret; 54 } 55 56 template <class ELFT> 57 void OutputSection::writeHeaderTo(typename ELFT::Shdr *shdr) { 58 shdr->sh_entsize = entsize; 59 shdr->sh_addralign = alignment; 60 shdr->sh_type = type; 61 shdr->sh_offset = offset; 62 shdr->sh_flags = flags; 63 shdr->sh_info = info; 64 shdr->sh_link = link; 65 shdr->sh_addr = addr; 66 shdr->sh_size = size; 67 shdr->sh_name = shName; 68 } 69 70 OutputSection::OutputSection(StringRef name, uint32_t type, uint64_t flags) 71 : BaseCommand(OutputSectionKind), 72 SectionBase(Output, name, flags, /*Entsize*/ 0, /*Alignment*/ 1, type, 73 /*Info*/ 0, /*Link*/ 0) {} 74 75 // We allow sections of types listed below to merged into a 76 // single progbits section. This is typically done by linker 77 // scripts. Merging nobits and progbits will force disk space 78 // to be allocated for nobits sections. Other ones don't require 79 // any special treatment on top of progbits, so there doesn't 80 // seem to be a harm in merging them. 81 static bool canMergeToProgbits(unsigned type) { 82 return type == SHT_NOBITS || type == SHT_PROGBITS || type == SHT_INIT_ARRAY || 83 type == SHT_PREINIT_ARRAY || type == SHT_FINI_ARRAY || 84 type == SHT_NOTE; 85 } 86 87 // Record that isec will be placed in the OutputSection. isec does not become 88 // permanent until finalizeInputSections() is called. The function should not be 89 // used after finalizeInputSections() is called. If you need to add an 90 // InputSection post finalizeInputSections(), then you must do the following: 91 // 92 // 1. Find or create an InputSectionDescription to hold InputSection. 93 // 2. Add the InputSection to the InputSectionDescription::sections. 94 // 3. Call commitSection(isec). 95 void OutputSection::recordSection(InputSectionBase *isec) { 96 partition = isec->partition; 97 isec->parent = this; 98 if (sectionCommands.empty() || 99 !isa<InputSectionDescription>(sectionCommands.back())) 100 sectionCommands.push_back(make<InputSectionDescription>("")); 101 auto *isd = cast<InputSectionDescription>(sectionCommands.back()); 102 isd->sectionBases.push_back(isec); 103 } 104 105 // Update fields (type, flags, alignment, etc) according to the InputSection 106 // isec. Also check whether the InputSection flags and type are consistent with 107 // other InputSections. 108 void OutputSection::commitSection(InputSection *isec) { 109 if (!hasInputSections) { 110 // If IS is the first section to be added to this section, 111 // initialize type, entsize and flags from isec. 112 hasInputSections = true; 113 type = isec->type; 114 entsize = isec->entsize; 115 flags = isec->flags; 116 } else { 117 // Otherwise, check if new type or flags are compatible with existing ones. 118 if ((flags ^ isec->flags) & SHF_TLS) 119 error("incompatible section flags for " + name + "\n>>> " + toString(isec) + 120 ": 0x" + utohexstr(isec->flags) + "\n>>> output section " + name + 121 ": 0x" + utohexstr(flags)); 122 123 if (type != isec->type) { 124 if (!canMergeToProgbits(type) || !canMergeToProgbits(isec->type)) 125 error("section type mismatch for " + isec->name + "\n>>> " + 126 toString(isec) + ": " + 127 getELFSectionTypeName(config->emachine, isec->type) + 128 "\n>>> output section " + name + ": " + 129 getELFSectionTypeName(config->emachine, type)); 130 type = SHT_PROGBITS; 131 } 132 } 133 if (noload) 134 type = SHT_NOBITS; 135 136 isec->parent = this; 137 uint64_t andMask = 138 config->emachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0; 139 uint64_t orMask = ~andMask; 140 uint64_t andFlags = (flags & isec->flags) & andMask; 141 uint64_t orFlags = (flags | isec->flags) & orMask; 142 flags = andFlags | orFlags; 143 if (nonAlloc) 144 flags &= ~(uint64_t)SHF_ALLOC; 145 146 alignment = std::max(alignment, isec->alignment); 147 148 // If this section contains a table of fixed-size entries, sh_entsize 149 // holds the element size. If it contains elements of different size we 150 // set sh_entsize to 0. 151 if (entsize != isec->entsize) 152 entsize = 0; 153 } 154 155 // This function scans over the InputSectionBase list sectionBases to create 156 // InputSectionDescription::sections. 157 // 158 // It removes MergeInputSections from the input section array and adds 159 // new synthetic sections at the location of the first input section 160 // that it replaces. It then finalizes each synthetic section in order 161 // to compute an output offset for each piece of each input section. 162 void OutputSection::finalizeInputSections() { 163 std::vector<MergeSyntheticSection *> mergeSections; 164 for (BaseCommand *base : sectionCommands) { 165 auto *cmd = dyn_cast<InputSectionDescription>(base); 166 if (!cmd) 167 continue; 168 cmd->sections.reserve(cmd->sectionBases.size()); 169 for (InputSectionBase *s : cmd->sectionBases) { 170 MergeInputSection *ms = dyn_cast<MergeInputSection>(s); 171 if (!ms) { 172 cmd->sections.push_back(cast<InputSection>(s)); 173 continue; 174 } 175 176 // We do not want to handle sections that are not alive, so just remove 177 // them instead of trying to merge. 178 if (!ms->isLive()) 179 continue; 180 181 auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) { 182 // While we could create a single synthetic section for two different 183 // values of Entsize, it is better to take Entsize into consideration. 184 // 185 // With a single synthetic section no two pieces with different Entsize 186 // could be equal, so we may as well have two sections. 187 // 188 // Using Entsize in here also allows us to propagate it to the synthetic 189 // section. 190 // 191 // SHF_STRINGS section with different alignments should not be merged. 192 return sec->flags == ms->flags && sec->entsize == ms->entsize && 193 (sec->alignment == ms->alignment || !(sec->flags & SHF_STRINGS)); 194 }); 195 if (i == mergeSections.end()) { 196 MergeSyntheticSection *syn = 197 createMergeSynthetic(name, ms->type, ms->flags, ms->alignment); 198 mergeSections.push_back(syn); 199 i = std::prev(mergeSections.end()); 200 syn->entsize = ms->entsize; 201 cmd->sections.push_back(syn); 202 } 203 (*i)->addSection(ms); 204 } 205 206 // sectionBases should not be used from this point onwards. Clear it to 207 // catch misuses. 208 cmd->sectionBases.clear(); 209 210 // Some input sections may be removed from the list after ICF. 211 for (InputSection *s : cmd->sections) 212 commitSection(s); 213 } 214 for (auto *ms : mergeSections) 215 ms->finalizeContents(); 216 } 217 218 static void sortByOrder(MutableArrayRef<InputSection *> in, 219 llvm::function_ref<int(InputSectionBase *s)> order) { 220 std::vector<std::pair<int, InputSection *>> v; 221 for (InputSection *s : in) 222 v.push_back({order(s), s}); 223 llvm::stable_sort(v, less_first()); 224 225 for (size_t i = 0; i < v.size(); ++i) 226 in[i] = v[i].second; 227 } 228 229 uint64_t elf::getHeaderSize() { 230 if (config->oFormatBinary) 231 return 0; 232 return Out::elfHeader->size + Out::programHeaders->size; 233 } 234 235 bool OutputSection::classof(const BaseCommand *c) { 236 return c->kind == OutputSectionKind; 237 } 238 239 void OutputSection::sort(llvm::function_ref<int(InputSectionBase *s)> order) { 240 assert(isLive()); 241 for (BaseCommand *b : sectionCommands) 242 if (auto *isd = dyn_cast<InputSectionDescription>(b)) 243 sortByOrder(isd->sections, order); 244 } 245 246 static void nopInstrFill(uint8_t *buf, size_t size) { 247 if (size == 0) 248 return; 249 unsigned i = 0; 250 if (size == 0) 251 return; 252 std::vector<std::vector<uint8_t>> nopFiller = *target->nopInstrs; 253 unsigned num = size / nopFiller.back().size(); 254 for (unsigned c = 0; c < num; ++c) { 255 memcpy(buf + i, nopFiller.back().data(), nopFiller.back().size()); 256 i += nopFiller.back().size(); 257 } 258 unsigned remaining = size - i; 259 if (!remaining) 260 return; 261 assert(nopFiller[remaining - 1].size() == remaining); 262 memcpy(buf + i, nopFiller[remaining - 1].data(), remaining); 263 } 264 265 // Fill [Buf, Buf + Size) with Filler. 266 // This is used for linker script "=fillexp" command. 267 static void fill(uint8_t *buf, size_t size, 268 const std::array<uint8_t, 4> &filler) { 269 size_t i = 0; 270 for (; i + 4 < size; i += 4) 271 memcpy(buf + i, filler.data(), 4); 272 memcpy(buf + i, filler.data(), size - i); 273 } 274 275 // Compress section contents if this section contains debug info. 276 template <class ELFT> void OutputSection::maybeCompress() { 277 using Elf_Chdr = typename ELFT::Chdr; 278 279 // Compress only DWARF debug sections. 280 if (!config->compressDebugSections || (flags & SHF_ALLOC) || 281 !name.startswith(".debug_")) 282 return; 283 284 // Create a section header. 285 zDebugHeader.resize(sizeof(Elf_Chdr)); 286 auto *hdr = reinterpret_cast<Elf_Chdr *>(zDebugHeader.data()); 287 hdr->ch_type = ELFCOMPRESS_ZLIB; 288 hdr->ch_size = size; 289 hdr->ch_addralign = alignment; 290 291 // Write section contents to a temporary buffer and compress it. 292 std::vector<uint8_t> buf(size); 293 writeTo<ELFT>(buf.data()); 294 // We chose 1 as the default compression level because it is the fastest. If 295 // -O2 is given, we use level 6 to compress debug info more by ~15%. We found 296 // that level 7 to 9 doesn't make much difference (~1% more compression) while 297 // they take significant amount of time (~2x), so level 6 seems enough. 298 if (Error e = zlib::compress(toStringRef(buf), compressedData, 299 config->optimize >= 2 ? 6 : 1)) 300 fatal("compress failed: " + llvm::toString(std::move(e))); 301 302 // Update section headers. 303 size = sizeof(Elf_Chdr) + compressedData.size(); 304 flags |= SHF_COMPRESSED; 305 } 306 307 static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) { 308 if (size == 1) 309 *buf = data; 310 else if (size == 2) 311 write16(buf, data); 312 else if (size == 4) 313 write32(buf, data); 314 else if (size == 8) 315 write64(buf, data); 316 else 317 llvm_unreachable("unsupported Size argument"); 318 } 319 320 template <class ELFT> void OutputSection::writeTo(uint8_t *buf) { 321 if (type == SHT_NOBITS) 322 return; 323 324 // If -compress-debug-section is specified and if this is a debug section, 325 // we've already compressed section contents. If that's the case, 326 // just write it down. 327 if (!compressedData.empty()) { 328 memcpy(buf, zDebugHeader.data(), zDebugHeader.size()); 329 memcpy(buf + zDebugHeader.size(), compressedData.data(), 330 compressedData.size()); 331 return; 332 } 333 334 // Write leading padding. 335 std::vector<InputSection *> sections = getInputSections(this); 336 std::array<uint8_t, 4> filler = getFiller(); 337 bool nonZeroFiller = read32(filler.data()) != 0; 338 if (nonZeroFiller) 339 fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler); 340 341 parallelForEachN(0, sections.size(), [&](size_t i) { 342 InputSection *isec = sections[i]; 343 isec->writeTo<ELFT>(buf); 344 345 // Fill gaps between sections. 346 if (nonZeroFiller) { 347 uint8_t *start = buf + isec->outSecOff + isec->getSize(); 348 uint8_t *end; 349 if (i + 1 == sections.size()) 350 end = buf + size; 351 else 352 end = buf + sections[i + 1]->outSecOff; 353 if (isec->nopFiller) { 354 assert(target->nopInstrs); 355 nopInstrFill(start, end - start); 356 } else 357 fill(start, end - start, filler); 358 } 359 }); 360 361 // Linker scripts may have BYTE()-family commands with which you 362 // can write arbitrary bytes to the output. Process them if any. 363 for (BaseCommand *base : sectionCommands) 364 if (auto *data = dyn_cast<ByteCommand>(base)) 365 writeInt(buf + data->offset, data->expression().getValue(), data->size); 366 } 367 368 static void finalizeShtGroup(OutputSection *os, 369 InputSection *section) { 370 assert(config->relocatable); 371 372 // sh_link field for SHT_GROUP sections should contain the section index of 373 // the symbol table. 374 os->link = in.symTab->getParent()->sectionIndex; 375 376 // sh_info then contain index of an entry in symbol table section which 377 // provides signature of the section group. 378 ArrayRef<Symbol *> symbols = section->file->getSymbols(); 379 os->info = in.symTab->getSymbolIndex(symbols[section->info]); 380 381 // Some group members may be combined or discarded, so we need to compute the 382 // new size. The content will be rewritten in InputSection::copyShtGroup. 383 std::unordered_set<uint32_t> seen; 384 ArrayRef<InputSectionBase *> sections = section->file->getSections(); 385 for (const uint32_t &idx : section->getDataAs<uint32_t>().slice(1)) 386 if (OutputSection *osec = sections[read32(&idx)]->getOutputSection()) 387 seen.insert(osec->sectionIndex); 388 os->size = (1 + seen.size()) * sizeof(uint32_t); 389 } 390 391 void OutputSection::finalize() { 392 InputSection *first = getFirstInputSection(this); 393 394 if (flags & SHF_LINK_ORDER) { 395 // We must preserve the link order dependency of sections with the 396 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 397 // need to translate the InputSection sh_link to the OutputSection sh_link, 398 // all InputSections in the OutputSection have the same dependency. 399 if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first)) 400 link = ex->getLinkOrderDep()->getParent()->sectionIndex; 401 else if (first->flags & SHF_LINK_ORDER) 402 if (auto *d = first->getLinkOrderDep()) 403 link = d->getParent()->sectionIndex; 404 } 405 406 if (type == SHT_GROUP) { 407 finalizeShtGroup(this, first); 408 return; 409 } 410 411 if (!config->copyRelocs || (type != SHT_RELA && type != SHT_REL)) 412 return; 413 414 if (isa<SyntheticSection>(first)) 415 return; 416 417 link = in.symTab->getParent()->sectionIndex; 418 // sh_info for SHT_REL[A] sections should contain the section header index of 419 // the section to which the relocation applies. 420 InputSectionBase *s = first->getRelocatedSection(); 421 info = s->getOutputSection()->sectionIndex; 422 flags |= SHF_INFO_LINK; 423 } 424 425 // Returns true if S is in one of the many forms the compiler driver may pass 426 // crtbegin files. 427 // 428 // Gcc uses any of crtbegin[<empty>|S|T].o. 429 // Clang uses Gcc's plus clang_rt.crtbegin[<empty>|S|T][-<arch>|<empty>].o. 430 431 static bool isCrtbegin(StringRef s) { 432 static std::regex re(R"((clang_rt\.)?crtbegin[ST]?(-.*)?\.o)"); 433 s = sys::path::filename(s); 434 return std::regex_match(s.begin(), s.end(), re); 435 } 436 437 static bool isCrtend(StringRef s) { 438 static std::regex re(R"((clang_rt\.)?crtend[ST]?(-.*)?\.o)"); 439 s = sys::path::filename(s); 440 return std::regex_match(s.begin(), s.end(), re); 441 } 442 443 // .ctors and .dtors are sorted by this priority from highest to lowest. 444 // 445 // 1. The section was contained in crtbegin (crtbegin contains 446 // some sentinel value in its .ctors and .dtors so that the runtime 447 // can find the beginning of the sections.) 448 // 449 // 2. The section has an optional priority value in the form of ".ctors.N" 450 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 451 // they are compared as string rather than number. 452 // 453 // 3. The section is just ".ctors" or ".dtors". 454 // 455 // 4. The section was contained in crtend, which contains an end marker. 456 // 457 // In an ideal world, we don't need this function because .init_array and 458 // .ctors are duplicate features (and .init_array is newer.) However, there 459 // are too many real-world use cases of .ctors, so we had no choice to 460 // support that with this rather ad-hoc semantics. 461 static bool compCtors(const InputSection *a, const InputSection *b) { 462 bool beginA = isCrtbegin(a->file->getName()); 463 bool beginB = isCrtbegin(b->file->getName()); 464 if (beginA != beginB) 465 return beginA; 466 bool endA = isCrtend(a->file->getName()); 467 bool endB = isCrtend(b->file->getName()); 468 if (endA != endB) 469 return endB; 470 StringRef x = a->name; 471 StringRef y = b->name; 472 assert(x.startswith(".ctors") || x.startswith(".dtors")); 473 assert(y.startswith(".ctors") || y.startswith(".dtors")); 474 x = x.substr(6); 475 y = y.substr(6); 476 return x < y; 477 } 478 479 // Sorts input sections by the special rules for .ctors and .dtors. 480 // Unfortunately, the rules are different from the one for .{init,fini}_array. 481 // Read the comment above. 482 void OutputSection::sortCtorsDtors() { 483 assert(sectionCommands.size() == 1); 484 auto *isd = cast<InputSectionDescription>(sectionCommands[0]); 485 llvm::stable_sort(isd->sections, compCtors); 486 } 487 488 // If an input string is in the form of "foo.N" where N is a number, 489 // return N. Otherwise, returns 65536, which is one greater than the 490 // lowest priority. 491 int elf::getPriority(StringRef s) { 492 size_t pos = s.rfind('.'); 493 if (pos == StringRef::npos) 494 return 65536; 495 int v; 496 if (!to_integer(s.substr(pos + 1), v, 10)) 497 return 65536; 498 return v; 499 } 500 501 InputSection *elf::getFirstInputSection(const OutputSection *os) { 502 for (BaseCommand *base : os->sectionCommands) 503 if (auto *isd = dyn_cast<InputSectionDescription>(base)) 504 if (!isd->sections.empty()) 505 return isd->sections[0]; 506 return nullptr; 507 } 508 509 std::vector<InputSection *> elf::getInputSections(const OutputSection *os) { 510 std::vector<InputSection *> ret; 511 for (BaseCommand *base : os->sectionCommands) 512 if (auto *isd = dyn_cast<InputSectionDescription>(base)) 513 ret.insert(ret.end(), isd->sections.begin(), isd->sections.end()); 514 return ret; 515 } 516 517 // Sorts input sections by section name suffixes, so that .foo.N comes 518 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 519 // We want to keep the original order if the priorities are the same 520 // because the compiler keeps the original initialization order in a 521 // translation unit and we need to respect that. 522 // For more detail, read the section of the GCC's manual about init_priority. 523 void OutputSection::sortInitFini() { 524 // Sort sections by priority. 525 sort([](InputSectionBase *s) { return getPriority(s->name); }); 526 } 527 528 std::array<uint8_t, 4> OutputSection::getFiller() { 529 if (filler) 530 return *filler; 531 if (flags & SHF_EXECINSTR) 532 return target->trapInstr; 533 return {0, 0, 0, 0}; 534 } 535 536 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr); 537 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr); 538 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr); 539 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr); 540 541 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf); 542 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf); 543 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf); 544 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf); 545 546 template void OutputSection::maybeCompress<ELF32LE>(); 547 template void OutputSection::maybeCompress<ELF32BE>(); 548 template void OutputSection::maybeCompress<ELF64LE>(); 549 template void OutputSection::maybeCompress<ELF64BE>(); 550