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 "Symbols.h" 13 #include "SyntheticSections.h" 14 #include "Target.h" 15 #include "lld/Common/Arrays.h" 16 #include "lld/Common/Memory.h" 17 #include "llvm/BinaryFormat/Dwarf.h" 18 #include "llvm/Config/llvm-config.h" // LLVM_ENABLE_ZLIB 19 #include "llvm/Support/Parallel.h" 20 #include "llvm/Support/Path.h" 21 #include "llvm/Support/TimeProfiler.h" 22 #if LLVM_ENABLE_ZLIB 23 #include <zlib.h> 24 #endif 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 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 SmallVector<OutputSection *, 0> 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 : SectionCommand(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 // 81 // NOTE: clang since rL252300 emits SHT_X86_64_UNWIND .eh_frame sections. Allow 82 // them to be merged into SHT_PROGBITS .eh_frame (GNU as .cfi_*). 83 static bool canMergeToProgbits(unsigned type) { 84 return type == SHT_NOBITS || type == SHT_PROGBITS || type == SHT_INIT_ARRAY || 85 type == SHT_PREINIT_ARRAY || type == SHT_FINI_ARRAY || 86 type == SHT_NOTE || 87 (type == SHT_X86_64_UNWIND && config->emachine == EM_X86_64); 88 } 89 90 // Record that isec will be placed in the OutputSection. isec does not become 91 // permanent until finalizeInputSections() is called. The function should not be 92 // used after finalizeInputSections() is called. If you need to add an 93 // InputSection post finalizeInputSections(), then you must do the following: 94 // 95 // 1. Find or create an InputSectionDescription to hold InputSection. 96 // 2. Add the InputSection to the InputSectionDescription::sections. 97 // 3. Call commitSection(isec). 98 void OutputSection::recordSection(InputSectionBase *isec) { 99 partition = isec->partition; 100 isec->parent = this; 101 if (commands.empty() || !isa<InputSectionDescription>(commands.back())) 102 commands.push_back(make<InputSectionDescription>("")); 103 auto *isd = cast<InputSectionDescription>(commands.back()); 104 isd->sectionBases.push_back(isec); 105 } 106 107 // Update fields (type, flags, alignment, etc) according to the InputSection 108 // isec. Also check whether the InputSection flags and type are consistent with 109 // other InputSections. 110 void OutputSection::commitSection(InputSection *isec) { 111 if (LLVM_UNLIKELY(type != isec->type)) { 112 if (hasInputSections || typeIsSet) { 113 if (typeIsSet || !canMergeToProgbits(type) || 114 !canMergeToProgbits(isec->type)) { 115 errorOrWarn("section type mismatch for " + isec->name + "\n>>> " + 116 toString(isec) + ": " + 117 getELFSectionTypeName(config->emachine, isec->type) + 118 "\n>>> output section " + name + ": " + 119 getELFSectionTypeName(config->emachine, type)); 120 } 121 type = SHT_PROGBITS; 122 } else { 123 type = isec->type; 124 } 125 } 126 if (!hasInputSections) { 127 // If IS is the first section to be added to this section, 128 // initialize type, entsize and flags from isec. 129 hasInputSections = true; 130 entsize = isec->entsize; 131 flags = isec->flags; 132 } else { 133 // Otherwise, check if new type or flags are compatible with existing ones. 134 if ((flags ^ isec->flags) & SHF_TLS) 135 error("incompatible section flags for " + name + "\n>>> " + 136 toString(isec) + ": 0x" + utohexstr(isec->flags) + 137 "\n>>> output section " + name + ": 0x" + utohexstr(flags)); 138 } 139 140 isec->parent = this; 141 uint64_t andMask = 142 config->emachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0; 143 uint64_t orMask = ~andMask; 144 uint64_t andFlags = (flags & isec->flags) & andMask; 145 uint64_t orFlags = (flags | isec->flags) & orMask; 146 flags = andFlags | orFlags; 147 if (nonAlloc) 148 flags &= ~(uint64_t)SHF_ALLOC; 149 150 alignment = std::max(alignment, isec->alignment); 151 152 // If this section contains a table of fixed-size entries, sh_entsize 153 // holds the element size. If it contains elements of different size we 154 // set sh_entsize to 0. 155 if (entsize != isec->entsize) 156 entsize = 0; 157 } 158 159 static MergeSyntheticSection *createMergeSynthetic(StringRef name, 160 uint32_t type, 161 uint64_t flags, 162 uint32_t alignment) { 163 if ((flags & SHF_STRINGS) && config->optimize >= 2) 164 return make<MergeTailSection>(name, type, flags, alignment); 165 return make<MergeNoTailSection>(name, type, flags, alignment); 166 } 167 168 // This function scans over the InputSectionBase list sectionBases to create 169 // InputSectionDescription::sections. 170 // 171 // It removes MergeInputSections from the input section array and adds 172 // new synthetic sections at the location of the first input section 173 // that it replaces. It then finalizes each synthetic section in order 174 // to compute an output offset for each piece of each input section. 175 void OutputSection::finalizeInputSections() { 176 std::vector<MergeSyntheticSection *> mergeSections; 177 for (SectionCommand *cmd : commands) { 178 auto *isd = dyn_cast<InputSectionDescription>(cmd); 179 if (!isd) 180 continue; 181 isd->sections.reserve(isd->sectionBases.size()); 182 for (InputSectionBase *s : isd->sectionBases) { 183 MergeInputSection *ms = dyn_cast<MergeInputSection>(s); 184 if (!ms) { 185 isd->sections.push_back(cast<InputSection>(s)); 186 continue; 187 } 188 189 // We do not want to handle sections that are not alive, so just remove 190 // them instead of trying to merge. 191 if (!ms->isLive()) 192 continue; 193 194 auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) { 195 // While we could create a single synthetic section for two different 196 // values of Entsize, it is better to take Entsize into consideration. 197 // 198 // With a single synthetic section no two pieces with different Entsize 199 // could be equal, so we may as well have two sections. 200 // 201 // Using Entsize in here also allows us to propagate it to the synthetic 202 // section. 203 // 204 // SHF_STRINGS section with different alignments should not be merged. 205 return sec->flags == ms->flags && sec->entsize == ms->entsize && 206 (sec->alignment == ms->alignment || !(sec->flags & SHF_STRINGS)); 207 }); 208 if (i == mergeSections.end()) { 209 MergeSyntheticSection *syn = 210 createMergeSynthetic(name, ms->type, ms->flags, ms->alignment); 211 mergeSections.push_back(syn); 212 i = std::prev(mergeSections.end()); 213 syn->entsize = ms->entsize; 214 isd->sections.push_back(syn); 215 } 216 (*i)->addSection(ms); 217 } 218 219 // sectionBases should not be used from this point onwards. Clear it to 220 // catch misuses. 221 isd->sectionBases.clear(); 222 223 // Some input sections may be removed from the list after ICF. 224 for (InputSection *s : isd->sections) 225 commitSection(s); 226 } 227 for (auto *ms : mergeSections) 228 ms->finalizeContents(); 229 } 230 231 static void sortByOrder(MutableArrayRef<InputSection *> in, 232 llvm::function_ref<int(InputSectionBase *s)> order) { 233 std::vector<std::pair<int, InputSection *>> v; 234 for (InputSection *s : in) 235 v.push_back({order(s), s}); 236 llvm::stable_sort(v, less_first()); 237 238 for (size_t i = 0; i < v.size(); ++i) 239 in[i] = v[i].second; 240 } 241 242 uint64_t elf::getHeaderSize() { 243 if (config->oFormatBinary) 244 return 0; 245 return Out::elfHeader->size + Out::programHeaders->size; 246 } 247 248 bool OutputSection::classof(const SectionCommand *c) { 249 return c->kind == OutputSectionKind; 250 } 251 252 void OutputSection::sort(llvm::function_ref<int(InputSectionBase *s)> order) { 253 assert(isLive()); 254 for (SectionCommand *b : commands) 255 if (auto *isd = dyn_cast<InputSectionDescription>(b)) 256 sortByOrder(isd->sections, order); 257 } 258 259 static void nopInstrFill(uint8_t *buf, size_t size) { 260 if (size == 0) 261 return; 262 unsigned i = 0; 263 if (size == 0) 264 return; 265 std::vector<std::vector<uint8_t>> nopFiller = *target->nopInstrs; 266 unsigned num = size / nopFiller.back().size(); 267 for (unsigned c = 0; c < num; ++c) { 268 memcpy(buf + i, nopFiller.back().data(), nopFiller.back().size()); 269 i += nopFiller.back().size(); 270 } 271 unsigned remaining = size - i; 272 if (!remaining) 273 return; 274 assert(nopFiller[remaining - 1].size() == remaining); 275 memcpy(buf + i, nopFiller[remaining - 1].data(), remaining); 276 } 277 278 // Fill [Buf, Buf + Size) with Filler. 279 // This is used for linker script "=fillexp" command. 280 static void fill(uint8_t *buf, size_t size, 281 const std::array<uint8_t, 4> &filler) { 282 size_t i = 0; 283 for (; i + 4 < size; i += 4) 284 memcpy(buf + i, filler.data(), 4); 285 memcpy(buf + i, filler.data(), size - i); 286 } 287 288 #if LLVM_ENABLE_ZLIB 289 static SmallVector<uint8_t, 0> deflateShard(ArrayRef<uint8_t> in, int level, 290 int flush) { 291 // 15 and 8 are default. windowBits=-15 is negative to generate raw deflate 292 // data with no zlib header or trailer. 293 z_stream s = {}; 294 deflateInit2(&s, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); 295 s.next_in = const_cast<uint8_t *>(in.data()); 296 s.avail_in = in.size(); 297 298 // Allocate a buffer of half of the input size, and grow it by 1.5x if 299 // insufficient. 300 SmallVector<uint8_t, 0> out; 301 size_t pos = 0; 302 out.resize_for_overwrite(std::max<size_t>(in.size() / 2, 64)); 303 do { 304 if (pos == out.size()) 305 out.resize_for_overwrite(out.size() * 3 / 2); 306 s.next_out = out.data() + pos; 307 s.avail_out = out.size() - pos; 308 (void)deflate(&s, flush); 309 pos = s.next_out - out.data(); 310 } while (s.avail_out == 0); 311 assert(s.avail_in == 0); 312 313 out.truncate(pos); 314 deflateEnd(&s); 315 return out; 316 } 317 #endif 318 319 // Compress section contents if this section contains debug info. 320 template <class ELFT> void OutputSection::maybeCompress() { 321 #if LLVM_ENABLE_ZLIB 322 using Elf_Chdr = typename ELFT::Chdr; 323 324 // Compress only DWARF debug sections. 325 if (!config->compressDebugSections || (flags & SHF_ALLOC) || 326 !name.startswith(".debug_") || size == 0) 327 return; 328 329 llvm::TimeTraceScope timeScope("Compress debug sections"); 330 331 // Write uncompressed data to a temporary zero-initialized buffer. 332 auto buf = std::make_unique<uint8_t[]>(size); 333 writeTo<ELFT>(buf.get()); 334 // We chose 1 (Z_BEST_SPEED) as the default compression level because it is 335 // the fastest. If -O2 is given, we use level 6 to compress debug info more by 336 // ~15%. We found that level 7 to 9 doesn't make much difference (~1% more 337 // compression) while they take significant amount of time (~2x), so level 6 338 // seems enough. 339 const int level = config->optimize >= 2 ? 6 : Z_BEST_SPEED; 340 341 // Split input into 1-MiB shards. 342 constexpr size_t shardSize = 1 << 20; 343 auto shardsIn = split(makeArrayRef<uint8_t>(buf.get(), size), shardSize); 344 const size_t numShards = shardsIn.size(); 345 346 // Compress shards and compute Alder-32 checksums. Use Z_SYNC_FLUSH for all 347 // shards but the last to flush the output to a byte boundary to be 348 // concatenated with the next shard. 349 auto shardsOut = std::make_unique<SmallVector<uint8_t, 0>[]>(numShards); 350 auto shardsAdler = std::make_unique<uint32_t[]>(numShards); 351 parallelForEachN(0, numShards, [&](size_t i) { 352 shardsOut[i] = deflateShard(shardsIn[i], level, 353 i != numShards - 1 ? Z_SYNC_FLUSH : Z_FINISH); 354 shardsAdler[i] = adler32(1, shardsIn[i].data(), shardsIn[i].size()); 355 }); 356 357 // Update section size and combine Alder-32 checksums. 358 uint32_t checksum = 1; // Initial Adler-32 value 359 compressed.uncompressedSize = size; 360 size = sizeof(Elf_Chdr) + 2; // Elf_Chdir and zlib header 361 for (size_t i = 0; i != numShards; ++i) { 362 size += shardsOut[i].size(); 363 checksum = adler32_combine(checksum, shardsAdler[i], shardsIn[i].size()); 364 } 365 size += 4; // checksum 366 367 compressed.shards = std::move(shardsOut); 368 compressed.numShards = numShards; 369 compressed.checksum = checksum; 370 flags |= SHF_COMPRESSED; 371 #endif 372 } 373 374 static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) { 375 if (size == 1) 376 *buf = data; 377 else if (size == 2) 378 write16(buf, data); 379 else if (size == 4) 380 write32(buf, data); 381 else if (size == 8) 382 write64(buf, data); 383 else 384 llvm_unreachable("unsupported Size argument"); 385 } 386 387 template <class ELFT> void OutputSection::writeTo(uint8_t *buf) { 388 llvm::TimeTraceScope timeScope("Write sections", name); 389 if (type == SHT_NOBITS) 390 return; 391 392 // If --compress-debug-section is specified and if this is a debug section, 393 // we've already compressed section contents. If that's the case, 394 // just write it down. 395 if (compressed.shards) { 396 auto *chdr = reinterpret_cast<typename ELFT::Chdr *>(buf); 397 chdr->ch_type = ELFCOMPRESS_ZLIB; 398 chdr->ch_size = compressed.uncompressedSize; 399 chdr->ch_addralign = alignment; 400 buf += sizeof(*chdr); 401 402 // Compute shard offsets. 403 auto offsets = std::make_unique<size_t[]>(compressed.numShards); 404 offsets[0] = 2; // zlib header 405 for (size_t i = 1; i != compressed.numShards; ++i) 406 offsets[i] = offsets[i - 1] + compressed.shards[i - 1].size(); 407 408 buf[0] = 0x78; // CMF 409 buf[1] = 0x01; // FLG: best speed 410 parallelForEachN(0, compressed.numShards, [&](size_t i) { 411 memcpy(buf + offsets[i], compressed.shards[i].data(), 412 compressed.shards[i].size()); 413 }); 414 415 write32be(buf + (size - sizeof(*chdr) - 4), compressed.checksum); 416 return; 417 } 418 419 // Write leading padding. 420 SmallVector<InputSection *, 0> sections = getInputSections(*this); 421 std::array<uint8_t, 4> filler = getFiller(); 422 bool nonZeroFiller = read32(filler.data()) != 0; 423 if (nonZeroFiller) 424 fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler); 425 426 parallelForEachN(0, sections.size(), [&](size_t i) { 427 InputSection *isec = sections[i]; 428 isec->writeTo<ELFT>(buf + isec->outSecOff); 429 430 // Fill gaps between sections. 431 if (nonZeroFiller) { 432 uint8_t *start = buf + isec->outSecOff + isec->getSize(); 433 uint8_t *end; 434 if (i + 1 == sections.size()) 435 end = buf + size; 436 else 437 end = buf + sections[i + 1]->outSecOff; 438 if (isec->nopFiller) { 439 assert(target->nopInstrs); 440 nopInstrFill(start, end - start); 441 } else 442 fill(start, end - start, filler); 443 } 444 }); 445 446 // Linker scripts may have BYTE()-family commands with which you 447 // can write arbitrary bytes to the output. Process them if any. 448 for (SectionCommand *cmd : commands) 449 if (auto *data = dyn_cast<ByteCommand>(cmd)) 450 writeInt(buf + data->offset, data->expression().getValue(), data->size); 451 } 452 453 static void finalizeShtGroup(OutputSection *os, InputSection *section) { 454 // sh_link field for SHT_GROUP sections should contain the section index of 455 // the symbol table. 456 os->link = in.symTab->getParent()->sectionIndex; 457 458 if (!section) 459 return; 460 461 // sh_info then contain index of an entry in symbol table section which 462 // provides signature of the section group. 463 ArrayRef<Symbol *> symbols = section->file->getSymbols(); 464 os->info = in.symTab->getSymbolIndex(symbols[section->info]); 465 466 // Some group members may be combined or discarded, so we need to compute the 467 // new size. The content will be rewritten in InputSection::copyShtGroup. 468 DenseSet<uint32_t> seen; 469 ArrayRef<InputSectionBase *> sections = section->file->getSections(); 470 for (const uint32_t &idx : section->getDataAs<uint32_t>().slice(1)) 471 if (OutputSection *osec = sections[read32(&idx)]->getOutputSection()) 472 seen.insert(osec->sectionIndex); 473 os->size = (1 + seen.size()) * sizeof(uint32_t); 474 } 475 476 void OutputSection::finalize() { 477 InputSection *first = getFirstInputSection(this); 478 479 if (flags & SHF_LINK_ORDER) { 480 // We must preserve the link order dependency of sections with the 481 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 482 // need to translate the InputSection sh_link to the OutputSection sh_link, 483 // all InputSections in the OutputSection have the same dependency. 484 if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first)) 485 link = ex->getLinkOrderDep()->getParent()->sectionIndex; 486 else if (first->flags & SHF_LINK_ORDER) 487 if (auto *d = first->getLinkOrderDep()) 488 link = d->getParent()->sectionIndex; 489 } 490 491 if (type == SHT_GROUP) { 492 finalizeShtGroup(this, first); 493 return; 494 } 495 496 if (!config->copyRelocs || (type != SHT_RELA && type != SHT_REL)) 497 return; 498 499 // Skip if 'first' is synthetic, i.e. not a section created by --emit-relocs. 500 // Normally 'type' was changed by 'first' so 'first' should be non-null. 501 // However, if the output section is .rela.dyn, 'type' can be set by the empty 502 // synthetic .rela.plt and first can be null. 503 if (!first || isa<SyntheticSection>(first)) 504 return; 505 506 link = in.symTab->getParent()->sectionIndex; 507 // sh_info for SHT_REL[A] sections should contain the section header index of 508 // the section to which the relocation applies. 509 InputSectionBase *s = first->getRelocatedSection(); 510 info = s->getOutputSection()->sectionIndex; 511 flags |= SHF_INFO_LINK; 512 } 513 514 // Returns true if S is in one of the many forms the compiler driver may pass 515 // crtbegin files. 516 // 517 // Gcc uses any of crtbegin[<empty>|S|T].o. 518 // Clang uses Gcc's plus clang_rt.crtbegin[-<arch>|<empty>].o. 519 520 static bool isCrt(StringRef s, StringRef beginEnd) { 521 s = sys::path::filename(s); 522 if (!s.consume_back(".o")) 523 return false; 524 if (s.consume_front("clang_rt.")) 525 return s.consume_front(beginEnd); 526 return s.consume_front(beginEnd) && s.size() <= 1; 527 } 528 529 // .ctors and .dtors are sorted by this order: 530 // 531 // 1. .ctors/.dtors in crtbegin (which contains a sentinel value -1). 532 // 2. The section is named ".ctors" or ".dtors" (priority: 65536). 533 // 3. The section has an optional priority value in the form of ".ctors.N" or 534 // ".dtors.N" where N is a number in the form of %05u (priority: 65535-N). 535 // 4. .ctors/.dtors in crtend (which contains a sentinel value 0). 536 // 537 // For 2 and 3, the sections are sorted by priority from high to low, e.g. 538 // .ctors (65536), .ctors.00100 (65436), .ctors.00200 (65336). In GNU ld's 539 // internal linker scripts, the sorting is by string comparison which can 540 // achieve the same goal given the optional priority values are of the same 541 // length. 542 // 543 // In an ideal world, we don't need this function because .init_array and 544 // .ctors are duplicate features (and .init_array is newer.) However, there 545 // are too many real-world use cases of .ctors, so we had no choice to 546 // support that with this rather ad-hoc semantics. 547 static bool compCtors(const InputSection *a, const InputSection *b) { 548 bool beginA = isCrt(a->file->getName(), "crtbegin"); 549 bool beginB = isCrt(b->file->getName(), "crtbegin"); 550 if (beginA != beginB) 551 return beginA; 552 bool endA = isCrt(a->file->getName(), "crtend"); 553 bool endB = isCrt(b->file->getName(), "crtend"); 554 if (endA != endB) 555 return endB; 556 return getPriority(a->name) > getPriority(b->name); 557 } 558 559 // Sorts input sections by the special rules for .ctors and .dtors. 560 // Unfortunately, the rules are different from the one for .{init,fini}_array. 561 // Read the comment above. 562 void OutputSection::sortCtorsDtors() { 563 assert(commands.size() == 1); 564 auto *isd = cast<InputSectionDescription>(commands[0]); 565 llvm::stable_sort(isd->sections, compCtors); 566 } 567 568 // If an input string is in the form of "foo.N" where N is a number, return N 569 // (65535-N if .ctors.N or .dtors.N). Otherwise, returns 65536, which is one 570 // greater than the lowest priority. 571 int elf::getPriority(StringRef s) { 572 size_t pos = s.rfind('.'); 573 if (pos == StringRef::npos) 574 return 65536; 575 int v = 65536; 576 if (to_integer(s.substr(pos + 1), v, 10) && 577 (pos == 6 && (s.startswith(".ctors") || s.startswith(".dtors")))) 578 v = 65535 - v; 579 return v; 580 } 581 582 InputSection *elf::getFirstInputSection(const OutputSection *os) { 583 for (SectionCommand *cmd : os->commands) 584 if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) 585 if (!isd->sections.empty()) 586 return isd->sections[0]; 587 return nullptr; 588 } 589 590 SmallVector<InputSection *, 0> elf::getInputSections(const OutputSection &os) { 591 SmallVector<InputSection *, 0> ret; 592 for (SectionCommand *cmd : os.commands) 593 if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) 594 ret.insert(ret.end(), isd->sections.begin(), isd->sections.end()); 595 return ret; 596 } 597 598 // Sorts input sections by section name suffixes, so that .foo.N comes 599 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 600 // We want to keep the original order if the priorities are the same 601 // because the compiler keeps the original initialization order in a 602 // translation unit and we need to respect that. 603 // For more detail, read the section of the GCC's manual about init_priority. 604 void OutputSection::sortInitFini() { 605 // Sort sections by priority. 606 sort([](InputSectionBase *s) { return getPriority(s->name); }); 607 } 608 609 std::array<uint8_t, 4> OutputSection::getFiller() { 610 if (filler) 611 return *filler; 612 if (flags & SHF_EXECINSTR) 613 return target->trapInstr; 614 return {0, 0, 0, 0}; 615 } 616 617 void OutputSection::checkDynRelAddends(const uint8_t *bufStart) { 618 assert(config->writeAddends && config->checkDynamicRelocs); 619 assert(type == SHT_REL || type == SHT_RELA); 620 SmallVector<InputSection *, 0> sections = getInputSections(*this); 621 parallelForEachN(0, sections.size(), [&](size_t i) { 622 // When linking with -r or --emit-relocs we might also call this function 623 // for input .rel[a].<sec> sections which we simply pass through to the 624 // output. We skip over those and only look at the synthetic relocation 625 // sections created during linking. 626 const auto *sec = dyn_cast<RelocationBaseSection>(sections[i]); 627 if (!sec) 628 return; 629 for (const DynamicReloc &rel : sec->relocs) { 630 int64_t addend = rel.addend; 631 const OutputSection *relOsec = rel.inputSec->getOutputSection(); 632 assert(relOsec != nullptr && "missing output section for relocation"); 633 const uint8_t *relocTarget = 634 bufStart + relOsec->offset + rel.inputSec->getOffset(rel.offsetInSec); 635 // For SHT_NOBITS the written addend is always zero. 636 int64_t writtenAddend = 637 relOsec->type == SHT_NOBITS 638 ? 0 639 : target->getImplicitAddend(relocTarget, rel.type); 640 if (addend != writtenAddend) 641 internalLinkerError( 642 getErrorLocation(relocTarget), 643 "wrote incorrect addend value 0x" + utohexstr(writtenAddend) + 644 " instead of 0x" + utohexstr(addend) + 645 " for dynamic relocation " + toString(rel.type) + 646 " at offset 0x" + utohexstr(rel.getOffset()) + 647 (rel.sym ? " against symbol " + toString(*rel.sym) : "")); 648 } 649 }); 650 } 651 652 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr); 653 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr); 654 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr); 655 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr); 656 657 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf); 658 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf); 659 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf); 660 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf); 661 662 template void OutputSection::maybeCompress<ELF32LE>(); 663 template void OutputSection::maybeCompress<ELF32BE>(); 664 template void OutputSection::maybeCompress<ELF64LE>(); 665 template void OutputSection::maybeCompress<ELF64BE>(); 666