10b57cec5SDimitry Andric //===- OutputSections.cpp -------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric 90b57cec5SDimitry Andric #include "OutputSections.h" 100b57cec5SDimitry Andric #include "Config.h" 1181ad6265SDimitry Andric #include "InputFiles.h" 120b57cec5SDimitry Andric #include "LinkerScript.h" 1381ad6265SDimitry Andric #include "Symbols.h" 140b57cec5SDimitry Andric #include "SyntheticSections.h" 150b57cec5SDimitry Andric #include "Target.h" 161fd87a68SDimitry Andric #include "lld/Common/Arrays.h" 170b57cec5SDimitry Andric #include "lld/Common/Memory.h" 180b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h" 19d56accc7SDimitry Andric #include "llvm/Config/llvm-config.h" // LLVM_ENABLE_ZLIB 20bdd1243dSDimitry Andric #include "llvm/Support/Compression.h" 21*52418fc2SDimitry Andric #include "llvm/Support/LEB128.h" 225ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 2381ad6265SDimitry Andric #include "llvm/Support/Path.h" 24e8d8bef9SDimitry Andric #include "llvm/Support/TimeProfiler.h" 2504eeddc0SDimitry Andric #if LLVM_ENABLE_ZLIB 265f757f3fSDimitry Andric // Avoid introducing max as a macro from Windows headers. 275f757f3fSDimitry Andric #define NOMINMAX 2804eeddc0SDimitry Andric #include <zlib.h> 2904eeddc0SDimitry Andric #endif 30bdd1243dSDimitry Andric #if LLVM_ENABLE_ZSTD 31bdd1243dSDimitry Andric #include <zstd.h> 32bdd1243dSDimitry Andric #endif 330b57cec5SDimitry Andric 340b57cec5SDimitry Andric using namespace llvm; 350b57cec5SDimitry Andric using namespace llvm::dwarf; 360b57cec5SDimitry Andric using namespace llvm::object; 370b57cec5SDimitry Andric using namespace llvm::support::endian; 380b57cec5SDimitry Andric using namespace llvm::ELF; 395ffd83dbSDimitry Andric using namespace lld; 405ffd83dbSDimitry Andric using namespace lld::elf; 410b57cec5SDimitry Andric 420b57cec5SDimitry Andric uint8_t *Out::bufferStart; 430b57cec5SDimitry Andric PhdrEntry *Out::tlsPhdr; 440b57cec5SDimitry Andric OutputSection *Out::elfHeader; 450b57cec5SDimitry Andric OutputSection *Out::programHeaders; 460b57cec5SDimitry Andric OutputSection *Out::preinitArray; 470b57cec5SDimitry Andric OutputSection *Out::initArray; 480b57cec5SDimitry Andric OutputSection *Out::finiArray; 490b57cec5SDimitry Andric 500eae32dcSDimitry Andric SmallVector<OutputSection *, 0> elf::outputSections; 510b57cec5SDimitry Andric 520b57cec5SDimitry Andric uint32_t OutputSection::getPhdrFlags() const { 530b57cec5SDimitry Andric uint32_t ret = 0; 540b57cec5SDimitry Andric if (config->emachine != EM_ARM || !(flags & SHF_ARM_PURECODE)) 550b57cec5SDimitry Andric ret |= PF_R; 560b57cec5SDimitry Andric if (flags & SHF_WRITE) 570b57cec5SDimitry Andric ret |= PF_W; 580b57cec5SDimitry Andric if (flags & SHF_EXECINSTR) 590b57cec5SDimitry Andric ret |= PF_X; 600b57cec5SDimitry Andric return ret; 610b57cec5SDimitry Andric } 620b57cec5SDimitry Andric 630b57cec5SDimitry Andric template <class ELFT> 640b57cec5SDimitry Andric void OutputSection::writeHeaderTo(typename ELFT::Shdr *shdr) { 650b57cec5SDimitry Andric shdr->sh_entsize = entsize; 66bdd1243dSDimitry Andric shdr->sh_addralign = addralign; 670b57cec5SDimitry Andric shdr->sh_type = type; 680b57cec5SDimitry Andric shdr->sh_offset = offset; 690b57cec5SDimitry Andric shdr->sh_flags = flags; 700b57cec5SDimitry Andric shdr->sh_info = info; 710b57cec5SDimitry Andric shdr->sh_link = link; 720b57cec5SDimitry Andric shdr->sh_addr = addr; 730b57cec5SDimitry Andric shdr->sh_size = size; 740b57cec5SDimitry Andric shdr->sh_name = shName; 750b57cec5SDimitry Andric } 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric OutputSection::OutputSection(StringRef name, uint32_t type, uint64_t flags) 7881ad6265SDimitry Andric : SectionBase(Output, name, flags, /*Entsize*/ 0, /*Alignment*/ 1, type, 790b57cec5SDimitry Andric /*Info*/ 0, /*Link*/ 0) {} 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric // We allow sections of types listed below to merged into a 820b57cec5SDimitry Andric // single progbits section. This is typically done by linker 830b57cec5SDimitry Andric // scripts. Merging nobits and progbits will force disk space 840b57cec5SDimitry Andric // to be allocated for nobits sections. Other ones don't require 850b57cec5SDimitry Andric // any special treatment on top of progbits, so there doesn't 860b57cec5SDimitry Andric // seem to be a harm in merging them. 8716d6b3b3SDimitry Andric // 8816d6b3b3SDimitry Andric // NOTE: clang since rL252300 emits SHT_X86_64_UNWIND .eh_frame sections. Allow 8916d6b3b3SDimitry Andric // them to be merged into SHT_PROGBITS .eh_frame (GNU as .cfi_*). 900b57cec5SDimitry Andric static bool canMergeToProgbits(unsigned type) { 910b57cec5SDimitry Andric return type == SHT_NOBITS || type == SHT_PROGBITS || type == SHT_INIT_ARRAY || 920b57cec5SDimitry Andric type == SHT_PREINIT_ARRAY || type == SHT_FINI_ARRAY || 9316d6b3b3SDimitry Andric type == SHT_NOTE || 9416d6b3b3SDimitry Andric (type == SHT_X86_64_UNWIND && config->emachine == EM_X86_64); 950b57cec5SDimitry Andric } 960b57cec5SDimitry Andric 9785868e8aSDimitry Andric // Record that isec will be placed in the OutputSection. isec does not become 9885868e8aSDimitry Andric // permanent until finalizeInputSections() is called. The function should not be 9985868e8aSDimitry Andric // used after finalizeInputSections() is called. If you need to add an 10085868e8aSDimitry Andric // InputSection post finalizeInputSections(), then you must do the following: 10185868e8aSDimitry Andric // 10285868e8aSDimitry Andric // 1. Find or create an InputSectionDescription to hold InputSection. 103480093f4SDimitry Andric // 2. Add the InputSection to the InputSectionDescription::sections. 10485868e8aSDimitry Andric // 3. Call commitSection(isec). 10585868e8aSDimitry Andric void OutputSection::recordSection(InputSectionBase *isec) { 10685868e8aSDimitry Andric partition = isec->partition; 10785868e8aSDimitry Andric isec->parent = this; 1084824e7fdSDimitry Andric if (commands.empty() || !isa<InputSectionDescription>(commands.back())) 1094824e7fdSDimitry Andric commands.push_back(make<InputSectionDescription>("")); 1104824e7fdSDimitry Andric auto *isd = cast<InputSectionDescription>(commands.back()); 11185868e8aSDimitry Andric isd->sectionBases.push_back(isec); 11285868e8aSDimitry Andric } 11385868e8aSDimitry Andric 11485868e8aSDimitry Andric // Update fields (type, flags, alignment, etc) according to the InputSection 11585868e8aSDimitry Andric // isec. Also check whether the InputSection flags and type are consistent with 11685868e8aSDimitry Andric // other InputSections. 11785868e8aSDimitry Andric void OutputSection::commitSection(InputSection *isec) { 11881ad6265SDimitry Andric if (LLVM_UNLIKELY(type != isec->type)) { 119*52418fc2SDimitry Andric if (!hasInputSections && !typeIsSet) { 120*52418fc2SDimitry Andric type = isec->type; 121*52418fc2SDimitry Andric } else if (isStaticRelSecType(type) && isStaticRelSecType(isec->type) && 122*52418fc2SDimitry Andric (type == SHT_CREL) != (isec->type == SHT_CREL)) { 123*52418fc2SDimitry Andric // Combine mixed SHT_REL[A] and SHT_CREL to SHT_CREL. 124*52418fc2SDimitry Andric type = SHT_CREL; 125*52418fc2SDimitry Andric if (type == SHT_REL) { 126*52418fc2SDimitry Andric if (name.consume_front(".rel")) 127*52418fc2SDimitry Andric name = saver().save(".crel" + name); 128*52418fc2SDimitry Andric } else if (name.consume_front(".rela")) { 129*52418fc2SDimitry Andric name = saver().save(".crel" + name); 130*52418fc2SDimitry Andric } 131*52418fc2SDimitry Andric } else { 13281ad6265SDimitry Andric if (typeIsSet || !canMergeToProgbits(type) || 13381ad6265SDimitry Andric !canMergeToProgbits(isec->type)) { 13406c3fb27SDimitry Andric // The (NOLOAD) changes the section type to SHT_NOBITS, the intention is 13506c3fb27SDimitry Andric // that the contents at that address is provided by some other means. 13606c3fb27SDimitry Andric // Some projects (e.g. 13706c3fb27SDimitry Andric // https://github.com/ClangBuiltLinux/linux/issues/1597) rely on the 13806c3fb27SDimitry Andric // behavior. Other types get an error. 13906c3fb27SDimitry Andric if (type != SHT_NOBITS) { 14006c3fb27SDimitry Andric errorOrWarn("section type mismatch for " + isec->name + "\n>>> " + 14181ad6265SDimitry Andric toString(isec) + ": " + 14281ad6265SDimitry Andric getELFSectionTypeName(config->emachine, isec->type) + 14381ad6265SDimitry Andric "\n>>> output section " + name + ": " + 14481ad6265SDimitry Andric getELFSectionTypeName(config->emachine, type)); 14581ad6265SDimitry Andric } 14606c3fb27SDimitry Andric } 14781ad6265SDimitry Andric if (!typeIsSet) 14881ad6265SDimitry Andric type = SHT_PROGBITS; 14981ad6265SDimitry Andric } 15081ad6265SDimitry Andric } 1510b57cec5SDimitry Andric if (!hasInputSections) { 1520b57cec5SDimitry Andric // If IS is the first section to be added to this section, 15385868e8aSDimitry Andric // initialize type, entsize and flags from isec. 1540b57cec5SDimitry Andric hasInputSections = true; 1550b57cec5SDimitry Andric entsize = isec->entsize; 1560b57cec5SDimitry Andric flags = isec->flags; 1570b57cec5SDimitry Andric } else { 1580b57cec5SDimitry Andric // Otherwise, check if new type or flags are compatible with existing ones. 159d65cd7a5SDimitry Andric if ((flags ^ isec->flags) & SHF_TLS) 16081ad6265SDimitry Andric error("incompatible section flags for " + name + "\n>>> " + 16181ad6265SDimitry Andric toString(isec) + ": 0x" + utohexstr(isec->flags) + 16281ad6265SDimitry Andric "\n>>> output section " + name + ": 0x" + utohexstr(flags)); 1630b57cec5SDimitry Andric } 1640b57cec5SDimitry Andric 1650b57cec5SDimitry Andric isec->parent = this; 1660b57cec5SDimitry Andric uint64_t andMask = 1670b57cec5SDimitry Andric config->emachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0; 1680b57cec5SDimitry Andric uint64_t orMask = ~andMask; 1690b57cec5SDimitry Andric uint64_t andFlags = (flags & isec->flags) & andMask; 1700b57cec5SDimitry Andric uint64_t orFlags = (flags | isec->flags) & orMask; 1710b57cec5SDimitry Andric flags = andFlags | orFlags; 17285868e8aSDimitry Andric if (nonAlloc) 17385868e8aSDimitry Andric flags &= ~(uint64_t)SHF_ALLOC; 1740b57cec5SDimitry Andric 175bdd1243dSDimitry Andric addralign = std::max(addralign, isec->addralign); 1760b57cec5SDimitry Andric 1770b57cec5SDimitry Andric // If this section contains a table of fixed-size entries, sh_entsize 1780b57cec5SDimitry Andric // holds the element size. If it contains elements of different size we 1790b57cec5SDimitry Andric // set sh_entsize to 0. 1800b57cec5SDimitry Andric if (entsize != isec->entsize) 1810b57cec5SDimitry Andric entsize = 0; 1820b57cec5SDimitry Andric } 18385868e8aSDimitry Andric 1840eae32dcSDimitry Andric static MergeSyntheticSection *createMergeSynthetic(StringRef name, 1850eae32dcSDimitry Andric uint32_t type, 1860eae32dcSDimitry Andric uint64_t flags, 187bdd1243dSDimitry Andric uint32_t addralign) { 1880eae32dcSDimitry Andric if ((flags & SHF_STRINGS) && config->optimize >= 2) 189bdd1243dSDimitry Andric return make<MergeTailSection>(name, type, flags, addralign); 190bdd1243dSDimitry Andric return make<MergeNoTailSection>(name, type, flags, addralign); 1910eae32dcSDimitry Andric } 1920eae32dcSDimitry Andric 19385868e8aSDimitry Andric // This function scans over the InputSectionBase list sectionBases to create 19485868e8aSDimitry Andric // InputSectionDescription::sections. 19585868e8aSDimitry Andric // 19685868e8aSDimitry Andric // It removes MergeInputSections from the input section array and adds 19785868e8aSDimitry Andric // new synthetic sections at the location of the first input section 19885868e8aSDimitry Andric // that it replaces. It then finalizes each synthetic section in order 19985868e8aSDimitry Andric // to compute an output offset for each piece of each input section. 2000fca6ea1SDimitry Andric void OutputSection::finalizeInputSections(LinkerScript *script) { 20185868e8aSDimitry Andric std::vector<MergeSyntheticSection *> mergeSections; 2024824e7fdSDimitry Andric for (SectionCommand *cmd : commands) { 2034824e7fdSDimitry Andric auto *isd = dyn_cast<InputSectionDescription>(cmd); 2044824e7fdSDimitry Andric if (!isd) 20585868e8aSDimitry Andric continue; 2064824e7fdSDimitry Andric isd->sections.reserve(isd->sectionBases.size()); 2074824e7fdSDimitry Andric for (InputSectionBase *s : isd->sectionBases) { 20885868e8aSDimitry Andric MergeInputSection *ms = dyn_cast<MergeInputSection>(s); 20985868e8aSDimitry Andric if (!ms) { 2104824e7fdSDimitry Andric isd->sections.push_back(cast<InputSection>(s)); 21185868e8aSDimitry Andric continue; 21285868e8aSDimitry Andric } 21385868e8aSDimitry Andric 21485868e8aSDimitry Andric // We do not want to handle sections that are not alive, so just remove 21585868e8aSDimitry Andric // them instead of trying to merge. 21685868e8aSDimitry Andric if (!ms->isLive()) 21785868e8aSDimitry Andric continue; 21885868e8aSDimitry Andric 21985868e8aSDimitry Andric auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) { 22085868e8aSDimitry Andric // While we could create a single synthetic section for two different 22185868e8aSDimitry Andric // values of Entsize, it is better to take Entsize into consideration. 22285868e8aSDimitry Andric // 22385868e8aSDimitry Andric // With a single synthetic section no two pieces with different Entsize 22485868e8aSDimitry Andric // could be equal, so we may as well have two sections. 22585868e8aSDimitry Andric // 22685868e8aSDimitry Andric // Using Entsize in here also allows us to propagate it to the synthetic 22785868e8aSDimitry Andric // section. 22885868e8aSDimitry Andric // 22985868e8aSDimitry Andric // SHF_STRINGS section with different alignments should not be merged. 23085868e8aSDimitry Andric return sec->flags == ms->flags && sec->entsize == ms->entsize && 231bdd1243dSDimitry Andric (sec->addralign == ms->addralign || !(sec->flags & SHF_STRINGS)); 23285868e8aSDimitry Andric }); 23385868e8aSDimitry Andric if (i == mergeSections.end()) { 23485868e8aSDimitry Andric MergeSyntheticSection *syn = 23506c3fb27SDimitry Andric createMergeSynthetic(s->name, ms->type, ms->flags, ms->addralign); 23685868e8aSDimitry Andric mergeSections.push_back(syn); 23785868e8aSDimitry Andric i = std::prev(mergeSections.end()); 23885868e8aSDimitry Andric syn->entsize = ms->entsize; 2394824e7fdSDimitry Andric isd->sections.push_back(syn); 2400fca6ea1SDimitry Andric // The merge synthetic section inherits the potential spill locations of 2410fca6ea1SDimitry Andric // its first contained section. 2420fca6ea1SDimitry Andric auto it = script->potentialSpillLists.find(ms); 2430fca6ea1SDimitry Andric if (it != script->potentialSpillLists.end()) 2440fca6ea1SDimitry Andric script->potentialSpillLists.try_emplace(syn, it->second); 24585868e8aSDimitry Andric } 24685868e8aSDimitry Andric (*i)->addSection(ms); 24785868e8aSDimitry Andric } 24885868e8aSDimitry Andric 24985868e8aSDimitry Andric // sectionBases should not be used from this point onwards. Clear it to 25085868e8aSDimitry Andric // catch misuses. 2514824e7fdSDimitry Andric isd->sectionBases.clear(); 25285868e8aSDimitry Andric 25385868e8aSDimitry Andric // Some input sections may be removed from the list after ICF. 2544824e7fdSDimitry Andric for (InputSection *s : isd->sections) 25585868e8aSDimitry Andric commitSection(s); 25685868e8aSDimitry Andric } 25785868e8aSDimitry Andric for (auto *ms : mergeSections) 25885868e8aSDimitry Andric ms->finalizeContents(); 2590b57cec5SDimitry Andric } 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric static void sortByOrder(MutableArrayRef<InputSection *> in, 2620b57cec5SDimitry Andric llvm::function_ref<int(InputSectionBase *s)> order) { 2630b57cec5SDimitry Andric std::vector<std::pair<int, InputSection *>> v; 2640b57cec5SDimitry Andric for (InputSection *s : in) 26506c3fb27SDimitry Andric v.emplace_back(order(s), s); 2660b57cec5SDimitry Andric llvm::stable_sort(v, less_first()); 2670b57cec5SDimitry Andric 2680b57cec5SDimitry Andric for (size_t i = 0; i < v.size(); ++i) 2690b57cec5SDimitry Andric in[i] = v[i].second; 2700b57cec5SDimitry Andric } 2710b57cec5SDimitry Andric 2725ffd83dbSDimitry Andric uint64_t elf::getHeaderSize() { 2730b57cec5SDimitry Andric if (config->oFormatBinary) 2740b57cec5SDimitry Andric return 0; 2750b57cec5SDimitry Andric return Out::elfHeader->size + Out::programHeaders->size; 2760b57cec5SDimitry Andric } 2770b57cec5SDimitry Andric 2780b57cec5SDimitry Andric void OutputSection::sort(llvm::function_ref<int(InputSectionBase *s)> order) { 2790b57cec5SDimitry Andric assert(isLive()); 2804824e7fdSDimitry Andric for (SectionCommand *b : commands) 2810b57cec5SDimitry Andric if (auto *isd = dyn_cast<InputSectionDescription>(b)) 2820b57cec5SDimitry Andric sortByOrder(isd->sections, order); 2830b57cec5SDimitry Andric } 2840b57cec5SDimitry Andric 2855ffd83dbSDimitry Andric static void nopInstrFill(uint8_t *buf, size_t size) { 2865ffd83dbSDimitry Andric if (size == 0) 2875ffd83dbSDimitry Andric return; 2885ffd83dbSDimitry Andric unsigned i = 0; 2895ffd83dbSDimitry Andric if (size == 0) 2905ffd83dbSDimitry Andric return; 2915ffd83dbSDimitry Andric std::vector<std::vector<uint8_t>> nopFiller = *target->nopInstrs; 2925ffd83dbSDimitry Andric unsigned num = size / nopFiller.back().size(); 2935ffd83dbSDimitry Andric for (unsigned c = 0; c < num; ++c) { 2945ffd83dbSDimitry Andric memcpy(buf + i, nopFiller.back().data(), nopFiller.back().size()); 2955ffd83dbSDimitry Andric i += nopFiller.back().size(); 2965ffd83dbSDimitry Andric } 2975ffd83dbSDimitry Andric unsigned remaining = size - i; 2985ffd83dbSDimitry Andric if (!remaining) 2995ffd83dbSDimitry Andric return; 3005ffd83dbSDimitry Andric assert(nopFiller[remaining - 1].size() == remaining); 3015ffd83dbSDimitry Andric memcpy(buf + i, nopFiller[remaining - 1].data(), remaining); 3025ffd83dbSDimitry Andric } 3035ffd83dbSDimitry Andric 3040b57cec5SDimitry Andric // Fill [Buf, Buf + Size) with Filler. 3050b57cec5SDimitry Andric // This is used for linker script "=fillexp" command. 3060b57cec5SDimitry Andric static void fill(uint8_t *buf, size_t size, 3070b57cec5SDimitry Andric const std::array<uint8_t, 4> &filler) { 3080b57cec5SDimitry Andric size_t i = 0; 3090b57cec5SDimitry Andric for (; i + 4 < size; i += 4) 3100b57cec5SDimitry Andric memcpy(buf + i, filler.data(), 4); 3110b57cec5SDimitry Andric memcpy(buf + i, filler.data(), size - i); 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 31404eeddc0SDimitry Andric #if LLVM_ENABLE_ZLIB 31504eeddc0SDimitry Andric static SmallVector<uint8_t, 0> deflateShard(ArrayRef<uint8_t> in, int level, 31604eeddc0SDimitry Andric int flush) { 31704eeddc0SDimitry Andric // 15 and 8 are default. windowBits=-15 is negative to generate raw deflate 31804eeddc0SDimitry Andric // data with no zlib header or trailer. 31904eeddc0SDimitry Andric z_stream s = {}; 3200fca6ea1SDimitry Andric auto res = deflateInit2(&s, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); 3210fca6ea1SDimitry Andric if (res != 0) { 3220fca6ea1SDimitry Andric errorOrWarn("--compress-sections: deflateInit2 returned " + Twine(res)); 3230fca6ea1SDimitry Andric return {}; 3240fca6ea1SDimitry Andric } 32504eeddc0SDimitry Andric s.next_in = const_cast<uint8_t *>(in.data()); 32604eeddc0SDimitry Andric s.avail_in = in.size(); 32704eeddc0SDimitry Andric 32804eeddc0SDimitry Andric // Allocate a buffer of half of the input size, and grow it by 1.5x if 32904eeddc0SDimitry Andric // insufficient. 33004eeddc0SDimitry Andric SmallVector<uint8_t, 0> out; 33104eeddc0SDimitry Andric size_t pos = 0; 33204eeddc0SDimitry Andric out.resize_for_overwrite(std::max<size_t>(in.size() / 2, 64)); 33304eeddc0SDimitry Andric do { 33404eeddc0SDimitry Andric if (pos == out.size()) 33504eeddc0SDimitry Andric out.resize_for_overwrite(out.size() * 3 / 2); 33604eeddc0SDimitry Andric s.next_out = out.data() + pos; 33704eeddc0SDimitry Andric s.avail_out = out.size() - pos; 33804eeddc0SDimitry Andric (void)deflate(&s, flush); 33904eeddc0SDimitry Andric pos = s.next_out - out.data(); 34004eeddc0SDimitry Andric } while (s.avail_out == 0); 34104eeddc0SDimitry Andric assert(s.avail_in == 0); 34204eeddc0SDimitry Andric 34304eeddc0SDimitry Andric out.truncate(pos); 34404eeddc0SDimitry Andric deflateEnd(&s); 34504eeddc0SDimitry Andric return out; 34604eeddc0SDimitry Andric } 34704eeddc0SDimitry Andric #endif 34804eeddc0SDimitry Andric 3490fca6ea1SDimitry Andric // Compress certain non-SHF_ALLOC sections: 3500fca6ea1SDimitry Andric // 3510fca6ea1SDimitry Andric // * (if --compress-debug-sections is specified) non-empty .debug_* sections 3520fca6ea1SDimitry Andric // * (if --compress-sections is specified) matched sections 3530b57cec5SDimitry Andric template <class ELFT> void OutputSection::maybeCompress() { 3540b57cec5SDimitry Andric using Elf_Chdr = typename ELFT::Chdr; 355bdd1243dSDimitry Andric (void)sizeof(Elf_Chdr); 3560b57cec5SDimitry Andric 3570fca6ea1SDimitry Andric DebugCompressionType ctype = DebugCompressionType::None; 3580fca6ea1SDimitry Andric size_t compressedSize = sizeof(Elf_Chdr); 3590fca6ea1SDimitry Andric unsigned level = 0; // default compression level 3600fca6ea1SDimitry Andric if (!(flags & SHF_ALLOC) && config->compressDebugSections && 3610fca6ea1SDimitry Andric name.starts_with(".debug_")) 3620fca6ea1SDimitry Andric ctype = *config->compressDebugSections; 3630fca6ea1SDimitry Andric for (auto &[glob, t, l] : config->compressSections) 3640fca6ea1SDimitry Andric if (glob.match(name)) 3650fca6ea1SDimitry Andric std::tie(ctype, level) = {t, l}; 3660fca6ea1SDimitry Andric if (ctype == DebugCompressionType::None) 3670b57cec5SDimitry Andric return; 3680fca6ea1SDimitry Andric if (flags & SHF_ALLOC) { 3690fca6ea1SDimitry Andric errorOrWarn("--compress-sections: section '" + name + 3700fca6ea1SDimitry Andric "' with the SHF_ALLOC flag cannot be compressed"); 3710fca6ea1SDimitry Andric return; 3720fca6ea1SDimitry Andric } 3730b57cec5SDimitry Andric 3740fca6ea1SDimitry Andric llvm::TimeTraceScope timeScope("Compress sections"); 37504eeddc0SDimitry Andric auto buf = std::make_unique<uint8_t[]>(size); 376bdd1243dSDimitry Andric // Write uncompressed data to a temporary zero-initialized buffer. 377bdd1243dSDimitry Andric { 378bdd1243dSDimitry Andric parallel::TaskGroup tg; 379bdd1243dSDimitry Andric writeTo<ELFT>(buf.get(), tg); 380bdd1243dSDimitry Andric } 3810fca6ea1SDimitry Andric // The generic ABI specifies "The sh_size and sh_addralign fields of the 3820fca6ea1SDimitry Andric // section header for a compressed section reflect the requirements of the 3830fca6ea1SDimitry Andric // compressed section." However, 1-byte alignment has been wildly accepted 3840fca6ea1SDimitry Andric // and utilized for a long time. Removing alignment padding is particularly 3850fca6ea1SDimitry Andric // useful when there are many compressed output sections. 3860fca6ea1SDimitry Andric addralign = 1; 3870fca6ea1SDimitry Andric 3880fca6ea1SDimitry Andric // Split input into 1-MiB shards. 3890fca6ea1SDimitry Andric [[maybe_unused]] constexpr size_t shardSize = 1 << 20; 3900fca6ea1SDimitry Andric auto shardsIn = split(ArrayRef<uint8_t>(buf.get(), size), shardSize); 3910fca6ea1SDimitry Andric const size_t numShards = shardsIn.size(); 3920fca6ea1SDimitry Andric auto shardsOut = std::make_unique<SmallVector<uint8_t, 0>[]>(numShards); 393bdd1243dSDimitry Andric 394bdd1243dSDimitry Andric #if LLVM_ENABLE_ZSTD 3950fca6ea1SDimitry Andric // Use ZSTD's streaming compression API. See 3960fca6ea1SDimitry Andric // http://facebook.github.io/zstd/zstd_manual.html "Streaming compression - 3970fca6ea1SDimitry Andric // HowTo". 3980fca6ea1SDimitry Andric if (ctype == DebugCompressionType::Zstd) { 3990fca6ea1SDimitry Andric parallelFor(0, numShards, [&](size_t i) { 4000fca6ea1SDimitry Andric SmallVector<uint8_t, 0> out; 4010fca6ea1SDimitry Andric ZSTD_CCtx *cctx = ZSTD_createCCtx(); 4020fca6ea1SDimitry Andric ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, level); 4030fca6ea1SDimitry Andric ZSTD_inBuffer zib = {shardsIn[i].data(), shardsIn[i].size(), 0}; 4040fca6ea1SDimitry Andric ZSTD_outBuffer zob = {nullptr, 0, 0}; 4050fca6ea1SDimitry Andric size_t size; 4060fca6ea1SDimitry Andric do { 407bdd1243dSDimitry Andric // Allocate a buffer of half of the input size, and grow it by 1.5x if 408bdd1243dSDimitry Andric // insufficient. 409bdd1243dSDimitry Andric if (zob.pos == zob.size) { 4100fca6ea1SDimitry Andric out.resize_for_overwrite( 4110fca6ea1SDimitry Andric zob.size ? zob.size * 3 / 2 : std::max<size_t>(zib.size / 4, 64)); 4120fca6ea1SDimitry Andric zob = {out.data(), out.size(), zob.pos}; 413bdd1243dSDimitry Andric } 4140fca6ea1SDimitry Andric size = ZSTD_compressStream2(cctx, &zob, &zib, ZSTD_e_end); 4150fca6ea1SDimitry Andric assert(!ZSTD_isError(size)); 4160fca6ea1SDimitry Andric } while (size != 0); 4170fca6ea1SDimitry Andric out.truncate(zob.pos); 418bdd1243dSDimitry Andric ZSTD_freeCCtx(cctx); 4190fca6ea1SDimitry Andric shardsOut[i] = std::move(out); 4200fca6ea1SDimitry Andric }); 4210fca6ea1SDimitry Andric compressed.type = ELFCOMPRESS_ZSTD; 4220fca6ea1SDimitry Andric for (size_t i = 0; i != numShards; ++i) 4230fca6ea1SDimitry Andric compressedSize += shardsOut[i].size(); 424bdd1243dSDimitry Andric } 425bdd1243dSDimitry Andric #endif 426bdd1243dSDimitry Andric 427bdd1243dSDimitry Andric #if LLVM_ENABLE_ZLIB 42804eeddc0SDimitry Andric // We chose 1 (Z_BEST_SPEED) as the default compression level because it is 4290fca6ea1SDimitry Andric // fast and provides decent compression ratios. 4300fca6ea1SDimitry Andric if (ctype == DebugCompressionType::Zlib) { 4310fca6ea1SDimitry Andric if (!level) 4320fca6ea1SDimitry Andric level = Z_BEST_SPEED; 4330b57cec5SDimitry Andric 43404eeddc0SDimitry Andric // Compress shards and compute Alder-32 checksums. Use Z_SYNC_FLUSH for all 43504eeddc0SDimitry Andric // shards but the last to flush the output to a byte boundary to be 43604eeddc0SDimitry Andric // concatenated with the next shard. 43704eeddc0SDimitry Andric auto shardsAdler = std::make_unique<uint32_t[]>(numShards); 43881ad6265SDimitry Andric parallelFor(0, numShards, [&](size_t i) { 43904eeddc0SDimitry Andric shardsOut[i] = deflateShard(shardsIn[i], level, 44004eeddc0SDimitry Andric i != numShards - 1 ? Z_SYNC_FLUSH : Z_FINISH); 44104eeddc0SDimitry Andric shardsAdler[i] = adler32(1, shardsIn[i].data(), shardsIn[i].size()); 44204eeddc0SDimitry Andric }); 44304eeddc0SDimitry Andric 44404eeddc0SDimitry Andric // Update section size and combine Alder-32 checksums. 44504eeddc0SDimitry Andric uint32_t checksum = 1; // Initial Adler-32 value 4460fca6ea1SDimitry Andric compressedSize += 2; // Elf_Chdir and zlib header 44704eeddc0SDimitry Andric for (size_t i = 0; i != numShards; ++i) { 4480fca6ea1SDimitry Andric compressedSize += shardsOut[i].size(); 44904eeddc0SDimitry Andric checksum = adler32_combine(checksum, shardsAdler[i], shardsIn[i].size()); 45004eeddc0SDimitry Andric } 4510fca6ea1SDimitry Andric compressedSize += 4; // checksum 4520fca6ea1SDimitry Andric compressed.type = ELFCOMPRESS_ZLIB; 4530fca6ea1SDimitry Andric compressed.checksum = checksum; 4540fca6ea1SDimitry Andric } 4550fca6ea1SDimitry Andric #endif 45604eeddc0SDimitry Andric 4570fca6ea1SDimitry Andric if (compressedSize >= size) 4580fca6ea1SDimitry Andric return; 4590fca6ea1SDimitry Andric compressed.uncompressedSize = size; 46004eeddc0SDimitry Andric compressed.shards = std::move(shardsOut); 46104eeddc0SDimitry Andric compressed.numShards = numShards; 4620fca6ea1SDimitry Andric size = compressedSize; 4630b57cec5SDimitry Andric flags |= SHF_COMPRESSED; 4640b57cec5SDimitry Andric } 4650b57cec5SDimitry Andric 4660b57cec5SDimitry Andric static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) { 4670b57cec5SDimitry Andric if (size == 1) 4680b57cec5SDimitry Andric *buf = data; 4690b57cec5SDimitry Andric else if (size == 2) 4700b57cec5SDimitry Andric write16(buf, data); 4710b57cec5SDimitry Andric else if (size == 4) 4720b57cec5SDimitry Andric write32(buf, data); 4730b57cec5SDimitry Andric else if (size == 8) 4740b57cec5SDimitry Andric write64(buf, data); 4750b57cec5SDimitry Andric else 4760b57cec5SDimitry Andric llvm_unreachable("unsupported Size argument"); 4770b57cec5SDimitry Andric } 4780b57cec5SDimitry Andric 479bdd1243dSDimitry Andric template <class ELFT> 480bdd1243dSDimitry Andric void OutputSection::writeTo(uint8_t *buf, parallel::TaskGroup &tg) { 4810eae32dcSDimitry Andric llvm::TimeTraceScope timeScope("Write sections", name); 4820b57cec5SDimitry Andric if (type == SHT_NOBITS) 4830b57cec5SDimitry Andric return; 484*52418fc2SDimitry Andric if (type == SHT_CREL && !(flags & SHF_ALLOC)) { 485*52418fc2SDimitry Andric buf += encodeULEB128(crelHeader, buf); 486*52418fc2SDimitry Andric memcpy(buf, crelBody.data(), crelBody.size()); 487*52418fc2SDimitry Andric return; 488*52418fc2SDimitry Andric } 4890b57cec5SDimitry Andric 4900fca6ea1SDimitry Andric // If the section is compressed due to 4910fca6ea1SDimitry Andric // --compress-debug-section/--compress-sections, the content is already known. 49204eeddc0SDimitry Andric if (compressed.shards) { 49304eeddc0SDimitry Andric auto *chdr = reinterpret_cast<typename ELFT::Chdr *>(buf); 4940fca6ea1SDimitry Andric chdr->ch_type = compressed.type; 49504eeddc0SDimitry Andric chdr->ch_size = compressed.uncompressedSize; 496bdd1243dSDimitry Andric chdr->ch_addralign = addralign; 49704eeddc0SDimitry Andric buf += sizeof(*chdr); 49804eeddc0SDimitry Andric 49904eeddc0SDimitry Andric auto offsets = std::make_unique<size_t[]>(compressed.numShards); 5000fca6ea1SDimitry Andric if (compressed.type == ELFCOMPRESS_ZLIB) { 50104eeddc0SDimitry Andric buf[0] = 0x78; // CMF 50204eeddc0SDimitry Andric buf[1] = 0x01; // FLG: best speed 5030fca6ea1SDimitry Andric offsets[0] = 2; // zlib header 5040fca6ea1SDimitry Andric write32be(buf + (size - sizeof(*chdr) - 4), compressed.checksum); 5050fca6ea1SDimitry Andric } 5060fca6ea1SDimitry Andric 5070fca6ea1SDimitry Andric // Compute shard offsets. 5080fca6ea1SDimitry Andric for (size_t i = 1; i != compressed.numShards; ++i) 5090fca6ea1SDimitry Andric offsets[i] = offsets[i - 1] + compressed.shards[i - 1].size(); 51081ad6265SDimitry Andric parallelFor(0, compressed.numShards, [&](size_t i) { 51104eeddc0SDimitry Andric memcpy(buf + offsets[i], compressed.shards[i].data(), 51204eeddc0SDimitry Andric compressed.shards[i].size()); 51304eeddc0SDimitry Andric }); 5140b57cec5SDimitry Andric return; 5150b57cec5SDimitry Andric } 5160b57cec5SDimitry Andric 5170b57cec5SDimitry Andric // Write leading padding. 518753f127fSDimitry Andric ArrayRef<InputSection *> sections = getInputSections(*this, storage); 5190b57cec5SDimitry Andric std::array<uint8_t, 4> filler = getFiller(); 5200b57cec5SDimitry Andric bool nonZeroFiller = read32(filler.data()) != 0; 5210b57cec5SDimitry Andric if (nonZeroFiller) 5220b57cec5SDimitry Andric fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler); 5230b57cec5SDimitry Andric 524*52418fc2SDimitry Andric if (type == SHT_CREL && !(flags & SHF_ALLOC)) { 525*52418fc2SDimitry Andric buf += encodeULEB128(crelHeader, buf); 526*52418fc2SDimitry Andric memcpy(buf, crelBody.data(), crelBody.size()); 527*52418fc2SDimitry Andric return; 528*52418fc2SDimitry Andric } 529*52418fc2SDimitry Andric 530bdd1243dSDimitry Andric auto fn = [=](size_t begin, size_t end) { 531bdd1243dSDimitry Andric size_t numSections = sections.size(); 532bdd1243dSDimitry Andric for (size_t i = begin; i != end; ++i) { 5330b57cec5SDimitry Andric InputSection *isec = sections[i]; 53481ad6265SDimitry Andric if (auto *s = dyn_cast<SyntheticSection>(isec)) 53581ad6265SDimitry Andric s->writeTo(buf + isec->outSecOff); 53681ad6265SDimitry Andric else 53704eeddc0SDimitry Andric isec->writeTo<ELFT>(buf + isec->outSecOff); 5380b57cec5SDimitry Andric 53906c3fb27SDimitry Andric // When in Arm BE8 mode, the linker has to convert the big-endian 54006c3fb27SDimitry Andric // instructions to little-endian, leaving the data big-endian. 54106c3fb27SDimitry Andric if (config->emachine == EM_ARM && !config->isLE && config->armBe8 && 54206c3fb27SDimitry Andric (flags & SHF_EXECINSTR)) 54306c3fb27SDimitry Andric convertArmInstructionstoBE8(isec, buf + isec->outSecOff); 54406c3fb27SDimitry Andric 5450b57cec5SDimitry Andric // Fill gaps between sections. 5460b57cec5SDimitry Andric if (nonZeroFiller) { 5470b57cec5SDimitry Andric uint8_t *start = buf + isec->outSecOff + isec->getSize(); 5480b57cec5SDimitry Andric uint8_t *end; 549bdd1243dSDimitry Andric if (i + 1 == numSections) 5500b57cec5SDimitry Andric end = buf + size; 5510b57cec5SDimitry Andric else 5520b57cec5SDimitry Andric end = buf + sections[i + 1]->outSecOff; 5535ffd83dbSDimitry Andric if (isec->nopFiller) { 5545ffd83dbSDimitry Andric assert(target->nopInstrs); 5555ffd83dbSDimitry Andric nopInstrFill(start, end - start); 5565ffd83dbSDimitry Andric } else 5570b57cec5SDimitry Andric fill(start, end - start, filler); 5580b57cec5SDimitry Andric } 559bdd1243dSDimitry Andric } 560bdd1243dSDimitry Andric }; 5610b57cec5SDimitry Andric 562bdd1243dSDimitry Andric // If there is any BYTE()-family command (rare), write the section content 563bdd1243dSDimitry Andric // first then process BYTE to overwrite the filler content. The write is 564bdd1243dSDimitry Andric // serial due to the limitation of llvm/Support/Parallel.h. 565bdd1243dSDimitry Andric bool written = false; 566bdd1243dSDimitry Andric size_t numSections = sections.size(); 5674824e7fdSDimitry Andric for (SectionCommand *cmd : commands) 568bdd1243dSDimitry Andric if (auto *data = dyn_cast<ByteCommand>(cmd)) { 569bdd1243dSDimitry Andric if (!std::exchange(written, true)) 570bdd1243dSDimitry Andric fn(0, numSections); 5710b57cec5SDimitry Andric writeInt(buf + data->offset, data->expression().getValue(), data->size); 5720b57cec5SDimitry Andric } 573bdd1243dSDimitry Andric if (written || !numSections) 574bdd1243dSDimitry Andric return; 575bdd1243dSDimitry Andric 576bdd1243dSDimitry Andric // There is no data command. Write content asynchronously to overlap the write 577bdd1243dSDimitry Andric // time with other output sections. Note, if a linker script specifies 578bdd1243dSDimitry Andric // overlapping output sections (needs --noinhibit-exec or --no-check-sections 579bdd1243dSDimitry Andric // to supress the error), the output may be non-deterministic. 580bdd1243dSDimitry Andric const size_t taskSizeLimit = 4 << 20; 581bdd1243dSDimitry Andric for (size_t begin = 0, i = 0, taskSize = 0;;) { 582bdd1243dSDimitry Andric taskSize += sections[i]->getSize(); 583bdd1243dSDimitry Andric bool done = ++i == numSections; 584bdd1243dSDimitry Andric if (done || taskSize >= taskSizeLimit) { 58506c3fb27SDimitry Andric tg.spawn([=] { fn(begin, i); }); 586bdd1243dSDimitry Andric if (done) 587bdd1243dSDimitry Andric break; 588bdd1243dSDimitry Andric begin = i; 589bdd1243dSDimitry Andric taskSize = 0; 590bdd1243dSDimitry Andric } 591bdd1243dSDimitry Andric } 592bdd1243dSDimitry Andric } 5930b57cec5SDimitry Andric 59481ad6265SDimitry Andric static void finalizeShtGroup(OutputSection *os, InputSection *section) { 5950b57cec5SDimitry Andric // sh_link field for SHT_GROUP sections should contain the section index of 5960b57cec5SDimitry Andric // the symbol table. 5970b57cec5SDimitry Andric os->link = in.symTab->getParent()->sectionIndex; 5980b57cec5SDimitry Andric 59981ad6265SDimitry Andric if (!section) 60081ad6265SDimitry Andric return; 60181ad6265SDimitry Andric 6020b57cec5SDimitry Andric // sh_info then contain index of an entry in symbol table section which 6030b57cec5SDimitry Andric // provides signature of the section group. 6040b57cec5SDimitry Andric ArrayRef<Symbol *> symbols = section->file->getSymbols(); 6050fca6ea1SDimitry Andric os->info = in.symTab->getSymbolIndex(*symbols[section->info]); 606e8d8bef9SDimitry Andric 607e8d8bef9SDimitry Andric // Some group members may be combined or discarded, so we need to compute the 608e8d8bef9SDimitry Andric // new size. The content will be rewritten in InputSection::copyShtGroup. 6091fd87a68SDimitry Andric DenseSet<uint32_t> seen; 610e8d8bef9SDimitry Andric ArrayRef<InputSectionBase *> sections = section->file->getSections(); 611e8d8bef9SDimitry Andric for (const uint32_t &idx : section->getDataAs<uint32_t>().slice(1)) 612e8d8bef9SDimitry Andric if (OutputSection *osec = sections[read32(&idx)]->getOutputSection()) 613e8d8bef9SDimitry Andric seen.insert(osec->sectionIndex); 614e8d8bef9SDimitry Andric os->size = (1 + seen.size()) * sizeof(uint32_t); 6150b57cec5SDimitry Andric } 6160b57cec5SDimitry Andric 617*52418fc2SDimitry Andric template <class uint> 618*52418fc2SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static void 619*52418fc2SDimitry Andric encodeOneCrel(raw_svector_ostream &os, Elf_Crel<sizeof(uint) == 8> &out, 620*52418fc2SDimitry Andric uint offset, const Symbol &sym, uint32_t type, uint addend) { 621*52418fc2SDimitry Andric const auto deltaOffset = static_cast<uint64_t>(offset - out.r_offset); 622*52418fc2SDimitry Andric out.r_offset = offset; 623*52418fc2SDimitry Andric int64_t symidx = in.symTab->getSymbolIndex(sym); 624*52418fc2SDimitry Andric if (sym.type == STT_SECTION) { 625*52418fc2SDimitry Andric auto *d = dyn_cast<Defined>(&sym); 626*52418fc2SDimitry Andric if (d) { 627*52418fc2SDimitry Andric SectionBase *section = d->section; 628*52418fc2SDimitry Andric assert(section->isLive()); 629*52418fc2SDimitry Andric addend = sym.getVA(addend) - section->getOutputSection()->addr; 630*52418fc2SDimitry Andric } else { 631*52418fc2SDimitry Andric // Encode R_*_NONE(symidx=0). 632*52418fc2SDimitry Andric symidx = type = addend = 0; 633*52418fc2SDimitry Andric } 634*52418fc2SDimitry Andric } 635*52418fc2SDimitry Andric 636*52418fc2SDimitry Andric // Similar to llvm::ELF::encodeCrel. 637*52418fc2SDimitry Andric uint8_t b = deltaOffset * 8 + (out.r_symidx != symidx) + 638*52418fc2SDimitry Andric (out.r_type != type ? 2 : 0) + 639*52418fc2SDimitry Andric (uint(out.r_addend) != addend ? 4 : 0); 640*52418fc2SDimitry Andric if (deltaOffset < 0x10) { 641*52418fc2SDimitry Andric os << char(b); 642*52418fc2SDimitry Andric } else { 643*52418fc2SDimitry Andric os << char(b | 0x80); 644*52418fc2SDimitry Andric encodeULEB128(deltaOffset >> 4, os); 645*52418fc2SDimitry Andric } 646*52418fc2SDimitry Andric if (b & 1) { 647*52418fc2SDimitry Andric encodeSLEB128(static_cast<int32_t>(symidx - out.r_symidx), os); 648*52418fc2SDimitry Andric out.r_symidx = symidx; 649*52418fc2SDimitry Andric } 650*52418fc2SDimitry Andric if (b & 2) { 651*52418fc2SDimitry Andric encodeSLEB128(static_cast<int32_t>(type - out.r_type), os); 652*52418fc2SDimitry Andric out.r_type = type; 653*52418fc2SDimitry Andric } 654*52418fc2SDimitry Andric if (b & 4) { 655*52418fc2SDimitry Andric encodeSLEB128(std::make_signed_t<uint>(addend - out.r_addend), os); 656*52418fc2SDimitry Andric out.r_addend = addend; 657*52418fc2SDimitry Andric } 658*52418fc2SDimitry Andric } 659*52418fc2SDimitry Andric 660*52418fc2SDimitry Andric template <class ELFT> 661*52418fc2SDimitry Andric static size_t relToCrel(raw_svector_ostream &os, Elf_Crel<ELFT::Is64Bits> &out, 662*52418fc2SDimitry Andric InputSection *relSec, InputSectionBase *sec) { 663*52418fc2SDimitry Andric const auto &file = *cast<ELFFileBase>(relSec->file); 664*52418fc2SDimitry Andric if (relSec->type == SHT_REL) { 665*52418fc2SDimitry Andric // REL conversion is complex and unsupported yet. 666*52418fc2SDimitry Andric errorOrWarn(toString(relSec) + ": REL cannot be converted to CREL"); 667*52418fc2SDimitry Andric return 0; 668*52418fc2SDimitry Andric } 669*52418fc2SDimitry Andric auto rels = relSec->getDataAs<typename ELFT::Rela>(); 670*52418fc2SDimitry Andric for (auto rel : rels) { 671*52418fc2SDimitry Andric encodeOneCrel<typename ELFT::uint>( 672*52418fc2SDimitry Andric os, out, sec->getVA(rel.r_offset), file.getRelocTargetSym(rel), 673*52418fc2SDimitry Andric rel.getType(config->isMips64EL), getAddend<ELFT>(rel)); 674*52418fc2SDimitry Andric } 675*52418fc2SDimitry Andric return rels.size(); 676*52418fc2SDimitry Andric } 677*52418fc2SDimitry Andric 678*52418fc2SDimitry Andric // Compute the content of a non-alloc CREL section due to -r or --emit-relocs. 679*52418fc2SDimitry Andric // Input CREL sections are decoded while REL[A] need to be converted. 680*52418fc2SDimitry Andric template <bool is64> void OutputSection::finalizeNonAllocCrel() { 681*52418fc2SDimitry Andric using uint = typename Elf_Crel_Impl<is64>::uint; 682*52418fc2SDimitry Andric raw_svector_ostream os(crelBody); 683*52418fc2SDimitry Andric uint64_t totalCount = 0; 684*52418fc2SDimitry Andric Elf_Crel<is64> out{}; 685*52418fc2SDimitry Andric assert(commands.size() == 1); 686*52418fc2SDimitry Andric auto *isd = cast<InputSectionDescription>(commands[0]); 687*52418fc2SDimitry Andric for (InputSection *relSec : isd->sections) { 688*52418fc2SDimitry Andric const auto &file = *cast<ELFFileBase>(relSec->file); 689*52418fc2SDimitry Andric InputSectionBase *sec = relSec->getRelocatedSection(); 690*52418fc2SDimitry Andric if (relSec->type == SHT_CREL) { 691*52418fc2SDimitry Andric RelocsCrel<is64> entries(relSec->content_); 692*52418fc2SDimitry Andric totalCount += entries.size(); 693*52418fc2SDimitry Andric for (Elf_Crel_Impl<is64> r : entries) { 694*52418fc2SDimitry Andric encodeOneCrel<uint>(os, out, uint(sec->getVA(r.r_offset)), 695*52418fc2SDimitry Andric file.getSymbol(r.r_symidx), r.r_type, r.r_addend); 696*52418fc2SDimitry Andric } 697*52418fc2SDimitry Andric continue; 698*52418fc2SDimitry Andric } 699*52418fc2SDimitry Andric 700*52418fc2SDimitry Andric // Convert REL[A] to CREL. 701*52418fc2SDimitry Andric if constexpr (is64) { 702*52418fc2SDimitry Andric totalCount += config->isLE ? relToCrel<ELF64LE>(os, out, relSec, sec) 703*52418fc2SDimitry Andric : relToCrel<ELF64BE>(os, out, relSec, sec); 704*52418fc2SDimitry Andric } else { 705*52418fc2SDimitry Andric totalCount += config->isLE ? relToCrel<ELF32LE>(os, out, relSec, sec) 706*52418fc2SDimitry Andric : relToCrel<ELF32BE>(os, out, relSec, sec); 707*52418fc2SDimitry Andric } 708*52418fc2SDimitry Andric } 709*52418fc2SDimitry Andric 710*52418fc2SDimitry Andric crelHeader = totalCount * 8 + 4; 711*52418fc2SDimitry Andric size = getULEB128Size(crelHeader) + crelBody.size(); 712*52418fc2SDimitry Andric } 713*52418fc2SDimitry Andric 7140b57cec5SDimitry Andric void OutputSection::finalize() { 7155ffd83dbSDimitry Andric InputSection *first = getFirstInputSection(this); 7160b57cec5SDimitry Andric 7170b57cec5SDimitry Andric if (flags & SHF_LINK_ORDER) { 7180b57cec5SDimitry Andric // We must preserve the link order dependency of sections with the 7190b57cec5SDimitry Andric // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 7200b57cec5SDimitry Andric // need to translate the InputSection sh_link to the OutputSection sh_link, 7210b57cec5SDimitry Andric // all InputSections in the OutputSection have the same dependency. 7220b57cec5SDimitry Andric if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first)) 7230b57cec5SDimitry Andric link = ex->getLinkOrderDep()->getParent()->sectionIndex; 724d65cd7a5SDimitry Andric else if (first->flags & SHF_LINK_ORDER) 725d65cd7a5SDimitry Andric if (auto *d = first->getLinkOrderDep()) 7260b57cec5SDimitry Andric link = d->getParent()->sectionIndex; 7270b57cec5SDimitry Andric } 7280b57cec5SDimitry Andric 7290b57cec5SDimitry Andric if (type == SHT_GROUP) { 7300b57cec5SDimitry Andric finalizeShtGroup(this, first); 7310b57cec5SDimitry Andric return; 7320b57cec5SDimitry Andric } 7330b57cec5SDimitry Andric 7340fca6ea1SDimitry Andric if (!config->copyRelocs || !isStaticRelSecType(type)) 7350b57cec5SDimitry Andric return; 7360b57cec5SDimitry Andric 737e8d8bef9SDimitry Andric // Skip if 'first' is synthetic, i.e. not a section created by --emit-relocs. 738e8d8bef9SDimitry Andric // Normally 'type' was changed by 'first' so 'first' should be non-null. 739e8d8bef9SDimitry Andric // However, if the output section is .rela.dyn, 'type' can be set by the empty 740e8d8bef9SDimitry Andric // synthetic .rela.plt and first can be null. 741e8d8bef9SDimitry Andric if (!first || isa<SyntheticSection>(first)) 7420b57cec5SDimitry Andric return; 7430b57cec5SDimitry Andric 7440b57cec5SDimitry Andric link = in.symTab->getParent()->sectionIndex; 7450b57cec5SDimitry Andric // sh_info for SHT_REL[A] sections should contain the section header index of 7460b57cec5SDimitry Andric // the section to which the relocation applies. 7470b57cec5SDimitry Andric InputSectionBase *s = first->getRelocatedSection(); 7480b57cec5SDimitry Andric info = s->getOutputSection()->sectionIndex; 7490b57cec5SDimitry Andric flags |= SHF_INFO_LINK; 750*52418fc2SDimitry Andric // Finalize the content of non-alloc CREL. 751*52418fc2SDimitry Andric if (type == SHT_CREL) { 752*52418fc2SDimitry Andric if (config->is64) 753*52418fc2SDimitry Andric finalizeNonAllocCrel<true>(); 754*52418fc2SDimitry Andric else 755*52418fc2SDimitry Andric finalizeNonAllocCrel<false>(); 756*52418fc2SDimitry Andric } 7570b57cec5SDimitry Andric } 7580b57cec5SDimitry Andric 759480093f4SDimitry Andric // Returns true if S is in one of the many forms the compiler driver may pass 760480093f4SDimitry Andric // crtbegin files. 761480093f4SDimitry Andric // 762480093f4SDimitry Andric // Gcc uses any of crtbegin[<empty>|S|T].o. 7631fd87a68SDimitry Andric // Clang uses Gcc's plus clang_rt.crtbegin[-<arch>|<empty>].o. 764480093f4SDimitry Andric 7651fd87a68SDimitry Andric static bool isCrt(StringRef s, StringRef beginEnd) { 766480093f4SDimitry Andric s = sys::path::filename(s); 7671fd87a68SDimitry Andric if (!s.consume_back(".o")) 7681fd87a68SDimitry Andric return false; 7691fd87a68SDimitry Andric if (s.consume_front("clang_rt.")) 7701fd87a68SDimitry Andric return s.consume_front(beginEnd); 7711fd87a68SDimitry Andric return s.consume_front(beginEnd) && s.size() <= 1; 772480093f4SDimitry Andric } 7730b57cec5SDimitry Andric 774e8d8bef9SDimitry Andric // .ctors and .dtors are sorted by this order: 7750b57cec5SDimitry Andric // 776e8d8bef9SDimitry Andric // 1. .ctors/.dtors in crtbegin (which contains a sentinel value -1). 777e8d8bef9SDimitry Andric // 2. The section is named ".ctors" or ".dtors" (priority: 65536). 778e8d8bef9SDimitry Andric // 3. The section has an optional priority value in the form of ".ctors.N" or 779e8d8bef9SDimitry Andric // ".dtors.N" where N is a number in the form of %05u (priority: 65535-N). 780e8d8bef9SDimitry Andric // 4. .ctors/.dtors in crtend (which contains a sentinel value 0). 7810b57cec5SDimitry Andric // 782e8d8bef9SDimitry Andric // For 2 and 3, the sections are sorted by priority from high to low, e.g. 783e8d8bef9SDimitry Andric // .ctors (65536), .ctors.00100 (65436), .ctors.00200 (65336). In GNU ld's 784e8d8bef9SDimitry Andric // internal linker scripts, the sorting is by string comparison which can 785e8d8bef9SDimitry Andric // achieve the same goal given the optional priority values are of the same 786e8d8bef9SDimitry Andric // length. 7870b57cec5SDimitry Andric // 7880b57cec5SDimitry Andric // In an ideal world, we don't need this function because .init_array and 7890b57cec5SDimitry Andric // .ctors are duplicate features (and .init_array is newer.) However, there 7900b57cec5SDimitry Andric // are too many real-world use cases of .ctors, so we had no choice to 7910b57cec5SDimitry Andric // support that with this rather ad-hoc semantics. 7920b57cec5SDimitry Andric static bool compCtors(const InputSection *a, const InputSection *b) { 7931fd87a68SDimitry Andric bool beginA = isCrt(a->file->getName(), "crtbegin"); 7941fd87a68SDimitry Andric bool beginB = isCrt(b->file->getName(), "crtbegin"); 7950b57cec5SDimitry Andric if (beginA != beginB) 7960b57cec5SDimitry Andric return beginA; 7971fd87a68SDimitry Andric bool endA = isCrt(a->file->getName(), "crtend"); 7981fd87a68SDimitry Andric bool endB = isCrt(b->file->getName(), "crtend"); 7990b57cec5SDimitry Andric if (endA != endB) 8000b57cec5SDimitry Andric return endB; 801e8d8bef9SDimitry Andric return getPriority(a->name) > getPriority(b->name); 8020b57cec5SDimitry Andric } 8030b57cec5SDimitry Andric 8040b57cec5SDimitry Andric // Sorts input sections by the special rules for .ctors and .dtors. 8050b57cec5SDimitry Andric // Unfortunately, the rules are different from the one for .{init,fini}_array. 8060b57cec5SDimitry Andric // Read the comment above. 8070b57cec5SDimitry Andric void OutputSection::sortCtorsDtors() { 8084824e7fdSDimitry Andric assert(commands.size() == 1); 8094824e7fdSDimitry Andric auto *isd = cast<InputSectionDescription>(commands[0]); 8100b57cec5SDimitry Andric llvm::stable_sort(isd->sections, compCtors); 8110b57cec5SDimitry Andric } 8120b57cec5SDimitry Andric 813e8d8bef9SDimitry Andric // If an input string is in the form of "foo.N" where N is a number, return N 814e8d8bef9SDimitry Andric // (65535-N if .ctors.N or .dtors.N). Otherwise, returns 65536, which is one 815e8d8bef9SDimitry Andric // greater than the lowest priority. 8165ffd83dbSDimitry Andric int elf::getPriority(StringRef s) { 8170b57cec5SDimitry Andric size_t pos = s.rfind('.'); 8180b57cec5SDimitry Andric if (pos == StringRef::npos) 8190b57cec5SDimitry Andric return 65536; 820e8d8bef9SDimitry Andric int v = 65536; 821e8d8bef9SDimitry Andric if (to_integer(s.substr(pos + 1), v, 10) && 82206c3fb27SDimitry Andric (pos == 6 && (s.starts_with(".ctors") || s.starts_with(".dtors")))) 823e8d8bef9SDimitry Andric v = 65535 - v; 8240b57cec5SDimitry Andric return v; 8250b57cec5SDimitry Andric } 8260b57cec5SDimitry Andric 8275ffd83dbSDimitry Andric InputSection *elf::getFirstInputSection(const OutputSection *os) { 8284824e7fdSDimitry Andric for (SectionCommand *cmd : os->commands) 8294824e7fdSDimitry Andric if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) 8305ffd83dbSDimitry Andric if (!isd->sections.empty()) 8315ffd83dbSDimitry Andric return isd->sections[0]; 8325ffd83dbSDimitry Andric return nullptr; 8335ffd83dbSDimitry Andric } 8345ffd83dbSDimitry Andric 835753f127fSDimitry Andric ArrayRef<InputSection *> 836753f127fSDimitry Andric elf::getInputSections(const OutputSection &os, 837753f127fSDimitry Andric SmallVector<InputSection *, 0> &storage) { 838753f127fSDimitry Andric ArrayRef<InputSection *> ret; 839753f127fSDimitry Andric storage.clear(); 840753f127fSDimitry Andric for (SectionCommand *cmd : os.commands) { 841753f127fSDimitry Andric auto *isd = dyn_cast<InputSectionDescription>(cmd); 842753f127fSDimitry Andric if (!isd) 843753f127fSDimitry Andric continue; 844753f127fSDimitry Andric if (ret.empty()) { 845753f127fSDimitry Andric ret = isd->sections; 846753f127fSDimitry Andric } else { 847753f127fSDimitry Andric if (storage.empty()) 848753f127fSDimitry Andric storage.assign(ret.begin(), ret.end()); 849753f127fSDimitry Andric storage.insert(storage.end(), isd->sections.begin(), isd->sections.end()); 850753f127fSDimitry Andric } 851753f127fSDimitry Andric } 852bdd1243dSDimitry Andric return storage.empty() ? ret : ArrayRef(storage); 8530b57cec5SDimitry Andric } 8540b57cec5SDimitry Andric 8550b57cec5SDimitry Andric // Sorts input sections by section name suffixes, so that .foo.N comes 8560b57cec5SDimitry Andric // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 8570b57cec5SDimitry Andric // We want to keep the original order if the priorities are the same 8580b57cec5SDimitry Andric // because the compiler keeps the original initialization order in a 8590b57cec5SDimitry Andric // translation unit and we need to respect that. 8600b57cec5SDimitry Andric // For more detail, read the section of the GCC's manual about init_priority. 8610b57cec5SDimitry Andric void OutputSection::sortInitFini() { 8620b57cec5SDimitry Andric // Sort sections by priority. 8630b57cec5SDimitry Andric sort([](InputSectionBase *s) { return getPriority(s->name); }); 8640b57cec5SDimitry Andric } 8650b57cec5SDimitry Andric 8660b57cec5SDimitry Andric std::array<uint8_t, 4> OutputSection::getFiller() { 8670b57cec5SDimitry Andric if (filler) 8680b57cec5SDimitry Andric return *filler; 8690b57cec5SDimitry Andric if (flags & SHF_EXECINSTR) 8700b57cec5SDimitry Andric return target->trapInstr; 8710b57cec5SDimitry Andric return {0, 0, 0, 0}; 8720b57cec5SDimitry Andric } 8730b57cec5SDimitry Andric 874fe6060f1SDimitry Andric void OutputSection::checkDynRelAddends(const uint8_t *bufStart) { 875fe6060f1SDimitry Andric assert(config->writeAddends && config->checkDynamicRelocs); 8760fca6ea1SDimitry Andric assert(isStaticRelSecType(type)); 877753f127fSDimitry Andric SmallVector<InputSection *, 0> storage; 878753f127fSDimitry Andric ArrayRef<InputSection *> sections = getInputSections(*this, storage); 87981ad6265SDimitry Andric parallelFor(0, sections.size(), [&](size_t i) { 880fe6060f1SDimitry Andric // When linking with -r or --emit-relocs we might also call this function 881fe6060f1SDimitry Andric // for input .rel[a].<sec> sections which we simply pass through to the 882fe6060f1SDimitry Andric // output. We skip over those and only look at the synthetic relocation 883fe6060f1SDimitry Andric // sections created during linking. 884fe6060f1SDimitry Andric const auto *sec = dyn_cast<RelocationBaseSection>(sections[i]); 885fe6060f1SDimitry Andric if (!sec) 886fe6060f1SDimitry Andric return; 887fe6060f1SDimitry Andric for (const DynamicReloc &rel : sec->relocs) { 8880eae32dcSDimitry Andric int64_t addend = rel.addend; 889fe6060f1SDimitry Andric const OutputSection *relOsec = rel.inputSec->getOutputSection(); 890fe6060f1SDimitry Andric assert(relOsec != nullptr && "missing output section for relocation"); 8915f757f3fSDimitry Andric // Some targets have NOBITS synthetic sections with dynamic relocations 8925f757f3fSDimitry Andric // with non-zero addends. Skip such sections. 8935f757f3fSDimitry Andric if (is_contained({EM_PPC, EM_PPC64}, config->emachine) && 8945f757f3fSDimitry Andric (rel.inputSec == in.ppc64LongBranchTarget.get() || 8955f757f3fSDimitry Andric rel.inputSec == in.igotPlt.get())) 8965f757f3fSDimitry Andric continue; 897fe6060f1SDimitry Andric const uint8_t *relocTarget = 898fe6060f1SDimitry Andric bufStart + relOsec->offset + rel.inputSec->getOffset(rel.offsetInSec); 899fe6060f1SDimitry Andric // For SHT_NOBITS the written addend is always zero. 900fe6060f1SDimitry Andric int64_t writtenAddend = 901fe6060f1SDimitry Andric relOsec->type == SHT_NOBITS 902fe6060f1SDimitry Andric ? 0 903fe6060f1SDimitry Andric : target->getImplicitAddend(relocTarget, rel.type); 904fe6060f1SDimitry Andric if (addend != writtenAddend) 905fe6060f1SDimitry Andric internalLinkerError( 906fe6060f1SDimitry Andric getErrorLocation(relocTarget), 907fe6060f1SDimitry Andric "wrote incorrect addend value 0x" + utohexstr(writtenAddend) + 908fe6060f1SDimitry Andric " instead of 0x" + utohexstr(addend) + 909fe6060f1SDimitry Andric " for dynamic relocation " + toString(rel.type) + 910fe6060f1SDimitry Andric " at offset 0x" + utohexstr(rel.getOffset()) + 911fe6060f1SDimitry Andric (rel.sym ? " against symbol " + toString(*rel.sym) : "")); 912fe6060f1SDimitry Andric } 913fe6060f1SDimitry Andric }); 914fe6060f1SDimitry Andric } 915fe6060f1SDimitry Andric 9160b57cec5SDimitry Andric template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr); 9170b57cec5SDimitry Andric template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr); 9180b57cec5SDimitry Andric template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr); 9190b57cec5SDimitry Andric template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr); 9200b57cec5SDimitry Andric 921bdd1243dSDimitry Andric template void OutputSection::writeTo<ELF32LE>(uint8_t *, 922bdd1243dSDimitry Andric llvm::parallel::TaskGroup &); 923bdd1243dSDimitry Andric template void OutputSection::writeTo<ELF32BE>(uint8_t *, 924bdd1243dSDimitry Andric llvm::parallel::TaskGroup &); 925bdd1243dSDimitry Andric template void OutputSection::writeTo<ELF64LE>(uint8_t *, 926bdd1243dSDimitry Andric llvm::parallel::TaskGroup &); 927bdd1243dSDimitry Andric template void OutputSection::writeTo<ELF64BE>(uint8_t *, 928bdd1243dSDimitry Andric llvm::parallel::TaskGroup &); 9290b57cec5SDimitry Andric 9300b57cec5SDimitry Andric template void OutputSection::maybeCompress<ELF32LE>(); 9310b57cec5SDimitry Andric template void OutputSection::maybeCompress<ELF32BE>(); 9320b57cec5SDimitry Andric template void OutputSection::maybeCompress<ELF64LE>(); 9330b57cec5SDimitry Andric template void OutputSection::maybeCompress<ELF64BE>(); 934