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