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 "lld/Common/Threads.h" 18 #include "llvm/BinaryFormat/Dwarf.h" 19 #include "llvm/Support/Compression.h" 20 #include "llvm/Support/MD5.h" 21 #include "llvm/Support/MathExtras.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 31 namespace lld { 32 namespace elf { 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 *> 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 InputSectionDesciption::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 unsigned mask = SHF_TLS | SHF_LINK_ORDER; 118 if ((flags & mask) != (isec->flags & mask)) 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 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 // Fill [Buf, Buf + Size) with Filler. 247 // This is used for linker script "=fillexp" command. 248 static void fill(uint8_t *buf, size_t size, 249 const std::array<uint8_t, 4> &filler) { 250 size_t i = 0; 251 for (; i + 4 < size; i += 4) 252 memcpy(buf + i, filler.data(), 4); 253 memcpy(buf + i, filler.data(), size - i); 254 } 255 256 // Compress section contents if this section contains debug info. 257 template <class ELFT> void OutputSection::maybeCompress() { 258 using Elf_Chdr = typename ELFT::Chdr; 259 260 // Compress only DWARF debug sections. 261 if (!config->compressDebugSections || (flags & SHF_ALLOC) || 262 !name.startswith(".debug_")) 263 return; 264 265 // Create a section header. 266 zDebugHeader.resize(sizeof(Elf_Chdr)); 267 auto *hdr = reinterpret_cast<Elf_Chdr *>(zDebugHeader.data()); 268 hdr->ch_type = ELFCOMPRESS_ZLIB; 269 hdr->ch_size = size; 270 hdr->ch_addralign = alignment; 271 272 // Write section contents to a temporary buffer and compress it. 273 std::vector<uint8_t> buf(size); 274 writeTo<ELFT>(buf.data()); 275 if (Error e = zlib::compress(toStringRef(buf), compressedData)) 276 fatal("compress failed: " + llvm::toString(std::move(e))); 277 278 // Update section headers. 279 size = sizeof(Elf_Chdr) + compressedData.size(); 280 flags |= SHF_COMPRESSED; 281 } 282 283 static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) { 284 if (size == 1) 285 *buf = data; 286 else if (size == 2) 287 write16(buf, data); 288 else if (size == 4) 289 write32(buf, data); 290 else if (size == 8) 291 write64(buf, data); 292 else 293 llvm_unreachable("unsupported Size argument"); 294 } 295 296 template <class ELFT> void OutputSection::writeTo(uint8_t *buf) { 297 if (type == SHT_NOBITS) 298 return; 299 300 // If -compress-debug-section is specified and if this is a debug section, 301 // we've already compressed section contents. If that's the case, 302 // just write it down. 303 if (!compressedData.empty()) { 304 memcpy(buf, zDebugHeader.data(), zDebugHeader.size()); 305 memcpy(buf + zDebugHeader.size(), compressedData.data(), 306 compressedData.size()); 307 return; 308 } 309 310 // Write leading padding. 311 std::vector<InputSection *> sections = getInputSections(this); 312 std::array<uint8_t, 4> filler = getFiller(); 313 bool nonZeroFiller = read32(filler.data()) != 0; 314 if (nonZeroFiller) 315 fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler); 316 317 parallelForEachN(0, sections.size(), [&](size_t i) { 318 InputSection *isec = sections[i]; 319 isec->writeTo<ELFT>(buf); 320 321 // Fill gaps between sections. 322 if (nonZeroFiller) { 323 uint8_t *start = buf + isec->outSecOff + isec->getSize(); 324 uint8_t *end; 325 if (i + 1 == sections.size()) 326 end = buf + size; 327 else 328 end = buf + sections[i + 1]->outSecOff; 329 fill(start, end - start, filler); 330 } 331 }); 332 333 // Linker scripts may have BYTE()-family commands with which you 334 // can write arbitrary bytes to the output. Process them if any. 335 for (BaseCommand *base : sectionCommands) 336 if (auto *data = dyn_cast<ByteCommand>(base)) 337 writeInt(buf + data->offset, data->expression().getValue(), data->size); 338 } 339 340 static void finalizeShtGroup(OutputSection *os, 341 InputSection *section) { 342 assert(config->relocatable); 343 344 // sh_link field for SHT_GROUP sections should contain the section index of 345 // the symbol table. 346 os->link = in.symTab->getParent()->sectionIndex; 347 348 // sh_info then contain index of an entry in symbol table section which 349 // provides signature of the section group. 350 ArrayRef<Symbol *> symbols = section->file->getSymbols(); 351 os->info = in.symTab->getSymbolIndex(symbols[section->info]); 352 } 353 354 void OutputSection::finalize() { 355 std::vector<InputSection *> v = getInputSections(this); 356 InputSection *first = v.empty() ? nullptr : v[0]; 357 358 if (flags & SHF_LINK_ORDER) { 359 // We must preserve the link order dependency of sections with the 360 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 361 // need to translate the InputSection sh_link to the OutputSection sh_link, 362 // all InputSections in the OutputSection have the same dependency. 363 if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first)) 364 link = ex->getLinkOrderDep()->getParent()->sectionIndex; 365 else if (auto *d = first->getLinkOrderDep()) 366 link = d->getParent()->sectionIndex; 367 } 368 369 if (type == SHT_GROUP) { 370 finalizeShtGroup(this, first); 371 return; 372 } 373 374 if (!config->copyRelocs || (type != SHT_RELA && type != SHT_REL)) 375 return; 376 377 if (isa<SyntheticSection>(first)) 378 return; 379 380 link = in.symTab->getParent()->sectionIndex; 381 // sh_info for SHT_REL[A] sections should contain the section header index of 382 // the section to which the relocation applies. 383 InputSectionBase *s = first->getRelocatedSection(); 384 info = s->getOutputSection()->sectionIndex; 385 flags |= SHF_INFO_LINK; 386 } 387 388 // Returns true if S is in one of the many forms the compiler driver may pass 389 // crtbegin files. 390 // 391 // Gcc uses any of crtbegin[<empty>|S|T].o. 392 // Clang uses Gcc's plus clang_rt.crtbegin[<empty>|S|T][-<arch>|<empty>].o. 393 394 static bool isCrtbegin(StringRef s) { 395 static std::regex re(R"((clang_rt\.)?crtbegin[ST]?(-.*)?\.o)"); 396 s = sys::path::filename(s); 397 return std::regex_match(s.begin(), s.end(), re); 398 } 399 400 static bool isCrtend(StringRef s) { 401 static std::regex re(R"((clang_rt\.)?crtend[ST]?(-.*)?\.o)"); 402 s = sys::path::filename(s); 403 return std::regex_match(s.begin(), s.end(), re); 404 } 405 406 // .ctors and .dtors are sorted by this priority from highest to lowest. 407 // 408 // 1. The section was contained in crtbegin (crtbegin contains 409 // some sentinel value in its .ctors and .dtors so that the runtime 410 // can find the beginning of the sections.) 411 // 412 // 2. The section has an optional priority value in the form of ".ctors.N" 413 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 414 // they are compared as string rather than number. 415 // 416 // 3. The section is just ".ctors" or ".dtors". 417 // 418 // 4. The section was contained in crtend, which contains an end marker. 419 // 420 // In an ideal world, we don't need this function because .init_array and 421 // .ctors are duplicate features (and .init_array is newer.) However, there 422 // are too many real-world use cases of .ctors, so we had no choice to 423 // support that with this rather ad-hoc semantics. 424 static bool compCtors(const InputSection *a, const InputSection *b) { 425 bool beginA = isCrtbegin(a->file->getName()); 426 bool beginB = isCrtbegin(b->file->getName()); 427 if (beginA != beginB) 428 return beginA; 429 bool endA = isCrtend(a->file->getName()); 430 bool endB = isCrtend(b->file->getName()); 431 if (endA != endB) 432 return endB; 433 StringRef x = a->name; 434 StringRef y = b->name; 435 assert(x.startswith(".ctors") || x.startswith(".dtors")); 436 assert(y.startswith(".ctors") || y.startswith(".dtors")); 437 x = x.substr(6); 438 y = y.substr(6); 439 return x < y; 440 } 441 442 // Sorts input sections by the special rules for .ctors and .dtors. 443 // Unfortunately, the rules are different from the one for .{init,fini}_array. 444 // Read the comment above. 445 void OutputSection::sortCtorsDtors() { 446 assert(sectionCommands.size() == 1); 447 auto *isd = cast<InputSectionDescription>(sectionCommands[0]); 448 llvm::stable_sort(isd->sections, compCtors); 449 } 450 451 // If an input string is in the form of "foo.N" where N is a number, 452 // return N. Otherwise, returns 65536, which is one greater than the 453 // lowest priority. 454 int getPriority(StringRef s) { 455 size_t pos = s.rfind('.'); 456 if (pos == StringRef::npos) 457 return 65536; 458 int v; 459 if (!to_integer(s.substr(pos + 1), v, 10)) 460 return 65536; 461 return v; 462 } 463 464 std::vector<InputSection *> getInputSections(OutputSection *os) { 465 std::vector<InputSection *> ret; 466 for (BaseCommand *base : os->sectionCommands) 467 if (auto *isd = dyn_cast<InputSectionDescription>(base)) 468 ret.insert(ret.end(), isd->sections.begin(), isd->sections.end()); 469 return ret; 470 } 471 472 // Sorts input sections by section name suffixes, so that .foo.N comes 473 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 474 // We want to keep the original order if the priorities are the same 475 // because the compiler keeps the original initialization order in a 476 // translation unit and we need to respect that. 477 // For more detail, read the section of the GCC's manual about init_priority. 478 void OutputSection::sortInitFini() { 479 // Sort sections by priority. 480 sort([](InputSectionBase *s) { return getPriority(s->name); }); 481 } 482 483 std::array<uint8_t, 4> OutputSection::getFiller() { 484 if (filler) 485 return *filler; 486 if (flags & SHF_EXECINSTR) 487 return target->trapInstr; 488 return {0, 0, 0, 0}; 489 } 490 491 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr); 492 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr); 493 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr); 494 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr); 495 496 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf); 497 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf); 498 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf); 499 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf); 500 501 template void OutputSection::maybeCompress<ELF32LE>(); 502 template void OutputSection::maybeCompress<ELF32BE>(); 503 template void OutputSection::maybeCompress<ELF64LE>(); 504 template void OutputSection::maybeCompress<ELF64BE>(); 505 506 } // namespace elf 507 } // namespace lld 508