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 24 using namespace llvm; 25 using namespace llvm::dwarf; 26 using namespace llvm::object; 27 using namespace llvm::support::endian; 28 using namespace llvm::ELF; 29 30 using namespace lld; 31 using namespace lld::elf; 32 33 uint8_t Out::First; 34 PhdrEntry *Out::TlsPhdr; 35 OutputSection *Out::ElfHeader; 36 OutputSection *Out::ProgramHeaders; 37 OutputSection *Out::PreinitArray; 38 OutputSection *Out::InitArray; 39 OutputSection *Out::FiniArray; 40 41 std::vector<OutputSection *> elf::OutputSections; 42 43 uint32_t OutputSection::getPhdrFlags() const { 44 uint32_t Ret = 0; 45 if (Config->EMachine != EM_ARM || !(Flags & SHF_ARM_PURECODE)) 46 Ret |= PF_R; 47 if (Flags & SHF_WRITE) 48 Ret |= PF_W; 49 if (Flags & SHF_EXECINSTR) 50 Ret |= PF_X; 51 return Ret; 52 } 53 54 template <class ELFT> 55 void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) { 56 Shdr->sh_entsize = Entsize; 57 Shdr->sh_addralign = Alignment; 58 Shdr->sh_type = Type; 59 Shdr->sh_offset = Offset; 60 Shdr->sh_flags = Flags; 61 Shdr->sh_info = Info; 62 Shdr->sh_link = Link; 63 Shdr->sh_addr = Addr; 64 Shdr->sh_size = Size; 65 Shdr->sh_name = ShName; 66 } 67 68 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags) 69 : BaseCommand(OutputSectionKind), 70 SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type, 71 /*Info*/ 0, /*Link*/ 0) { 72 Live = false; 73 } 74 75 // We allow sections of types listed below to merged into a 76 // single progbits section. This is typically done by linker 77 // scripts. Merging nobits and progbits will force disk space 78 // to be allocated for nobits sections. Other ones don't require 79 // any special treatment on top of progbits, so there doesn't 80 // seem to be a harm in merging them. 81 static bool canMergeToProgbits(unsigned Type) { 82 return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY || 83 Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY || 84 Type == SHT_NOTE; 85 } 86 87 void OutputSection::addSection(InputSection *IS) { 88 if (!Live) { 89 // If IS is the first section to be added to this section, 90 // initialize Type, Entsize and flags from IS. 91 Live = true; 92 Type = IS->Type; 93 Entsize = IS->Entsize; 94 Flags = IS->Flags; 95 } else { 96 // Otherwise, check if new type or flags are compatible with existing ones. 97 unsigned Mask = SHF_TLS | SHF_LINK_ORDER; 98 if ((Flags & Mask) != (IS->Flags & Mask)) 99 error("incompatible section flags for " + Name + "\n>>> " + toString(IS) + 100 ": 0x" + utohexstr(IS->Flags) + "\n>>> output section " + Name + 101 ": 0x" + utohexstr(Flags)); 102 103 if (Type != IS->Type) { 104 if (!canMergeToProgbits(Type) || !canMergeToProgbits(IS->Type)) 105 error("section type mismatch for " + IS->Name + "\n>>> " + 106 toString(IS) + ": " + 107 getELFSectionTypeName(Config->EMachine, IS->Type) + 108 "\n>>> output section " + Name + ": " + 109 getELFSectionTypeName(Config->EMachine, Type)); 110 Type = SHT_PROGBITS; 111 } 112 } 113 114 IS->Parent = this; 115 uint64_t AndMask = 116 Config->EMachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0; 117 uint64_t OrMask = ~AndMask; 118 uint64_t AndFlags = (Flags & IS->Flags) & AndMask; 119 uint64_t OrFlags = (Flags | IS->Flags) & OrMask; 120 Flags = AndFlags | OrFlags; 121 122 Alignment = std::max(Alignment, IS->Alignment); 123 124 // If this section contains a table of fixed-size entries, sh_entsize 125 // holds the element size. If it contains elements of different size we 126 // set sh_entsize to 0. 127 if (Entsize != IS->Entsize) 128 Entsize = 0; 129 130 if (!IS->Assigned) { 131 IS->Assigned = true; 132 if (SectionCommands.empty() || 133 !isa<InputSectionDescription>(SectionCommands.back())) 134 SectionCommands.push_back(make<InputSectionDescription>("")); 135 auto *ISD = cast<InputSectionDescription>(SectionCommands.back()); 136 ISD->Sections.push_back(IS); 137 } 138 } 139 140 static void sortByOrder(MutableArrayRef<InputSection *> In, 141 llvm::function_ref<int(InputSectionBase *S)> Order) { 142 typedef std::pair<int, InputSection *> Pair; 143 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; }; 144 145 std::vector<Pair> V; 146 for (InputSection *S : In) 147 V.push_back({Order(S), S}); 148 std::stable_sort(V.begin(), V.end(), Comp); 149 150 for (size_t I = 0; I < V.size(); ++I) 151 In[I] = V[I].second; 152 } 153 154 uint64_t elf::getHeaderSize() { 155 if (Config->OFormatBinary) 156 return 0; 157 return Out::ElfHeader->Size + Out::ProgramHeaders->Size; 158 } 159 160 bool OutputSection::classof(const BaseCommand *C) { 161 return C->Kind == OutputSectionKind; 162 } 163 164 void OutputSection::sort(llvm::function_ref<int(InputSectionBase *S)> Order) { 165 assert(Live); 166 for (BaseCommand *B : SectionCommands) 167 if (auto *ISD = dyn_cast<InputSectionDescription>(B)) 168 sortByOrder(ISD->Sections, Order); 169 } 170 171 // Fill [Buf, Buf + Size) with Filler. 172 // This is used for linker script "=fillexp" command. 173 static void fill(uint8_t *Buf, size_t Size, 174 const std::array<uint8_t, 4> &Filler) { 175 size_t I = 0; 176 for (; I + 4 < Size; I += 4) 177 memcpy(Buf + I, Filler.data(), 4); 178 memcpy(Buf + I, Filler.data(), Size - I); 179 } 180 181 // Compress section contents if this section contains debug info. 182 template <class ELFT> void OutputSection::maybeCompress() { 183 typedef typename ELFT::Chdr Elf_Chdr; 184 185 // Compress only DWARF debug sections. 186 if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) || 187 !Name.startswith(".debug_")) 188 return; 189 190 // Create a section header. 191 ZDebugHeader.resize(sizeof(Elf_Chdr)); 192 auto *Hdr = reinterpret_cast<Elf_Chdr *>(ZDebugHeader.data()); 193 Hdr->ch_type = ELFCOMPRESS_ZLIB; 194 Hdr->ch_size = Size; 195 Hdr->ch_addralign = Alignment; 196 197 // Write section contents to a temporary buffer and compress it. 198 std::vector<uint8_t> Buf(Size); 199 writeTo<ELFT>(Buf.data()); 200 if (Error E = zlib::compress(toStringRef(Buf), CompressedData)) 201 fatal("compress failed: " + llvm::toString(std::move(E))); 202 203 // Update section headers. 204 Size = sizeof(Elf_Chdr) + CompressedData.size(); 205 Flags |= SHF_COMPRESSED; 206 } 207 208 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) { 209 if (Size == 1) 210 *Buf = Data; 211 else if (Size == 2) 212 write16(Buf, Data); 213 else if (Size == 4) 214 write32(Buf, Data); 215 else if (Size == 8) 216 write64(Buf, Data); 217 else 218 llvm_unreachable("unsupported Size argument"); 219 } 220 221 template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) { 222 if (Type == SHT_NOBITS) 223 return; 224 225 Loc = Buf; 226 227 // If -compress-debug-section is specified and if this is a debug seciton, 228 // we've already compressed section contents. If that's the case, 229 // just write it down. 230 if (!CompressedData.empty()) { 231 memcpy(Buf, ZDebugHeader.data(), ZDebugHeader.size()); 232 memcpy(Buf + ZDebugHeader.size(), CompressedData.data(), 233 CompressedData.size()); 234 return; 235 } 236 237 // Write leading padding. 238 std::vector<InputSection *> Sections = getInputSections(this); 239 std::array<uint8_t, 4> Filler = getFiller(); 240 bool NonZeroFiller = read32(Filler.data()) != 0; 241 if (NonZeroFiller) 242 fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler); 243 244 parallelForEachN(0, Sections.size(), [&](size_t I) { 245 InputSection *IS = Sections[I]; 246 IS->writeTo<ELFT>(Buf); 247 248 // Fill gaps between sections. 249 if (NonZeroFiller) { 250 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize(); 251 uint8_t *End; 252 if (I + 1 == Sections.size()) 253 End = Buf + Size; 254 else 255 End = Buf + Sections[I + 1]->OutSecOff; 256 fill(Start, End - Start, Filler); 257 } 258 }); 259 260 // Linker scripts may have BYTE()-family commands with which you 261 // can write arbitrary bytes to the output. Process them if any. 262 for (BaseCommand *Base : SectionCommands) 263 if (auto *Data = dyn_cast<ByteCommand>(Base)) 264 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size); 265 } 266 267 template <class ELFT> 268 static void finalizeShtGroup(OutputSection *OS, 269 InputSection *Section) { 270 assert(Config->Relocatable); 271 272 // sh_link field for SHT_GROUP sections should contain the section index of 273 // the symbol table. 274 OS->Link = In.SymTab->getParent()->SectionIndex; 275 276 // sh_info then contain index of an entry in symbol table section which 277 // provides signature of the section group. 278 ObjFile<ELFT> *Obj = Section->getFile<ELFT>(); 279 ArrayRef<Symbol *> Symbols = Obj->getSymbols(); 280 OS->Info = In.SymTab->getSymbolIndex(Symbols[Section->Info]); 281 } 282 283 template <class ELFT> void OutputSection::finalize() { 284 if (Type == SHT_NOBITS) 285 for (BaseCommand *Base : SectionCommands) 286 if (isa<ByteCommand>(Base)) 287 Type = SHT_PROGBITS; 288 289 std::vector<InputSection *> V = getInputSections(this); 290 InputSection *First = V.empty() ? nullptr : V[0]; 291 292 if (Flags & SHF_LINK_ORDER) { 293 // We must preserve the link order dependency of sections with the 294 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 295 // need to translate the InputSection sh_link to the OutputSection sh_link, 296 // all InputSections in the OutputSection have the same dependency. 297 if (auto *D = First->getLinkOrderDep()) 298 Link = D->getParent()->SectionIndex; 299 } 300 301 if (Type == SHT_GROUP) { 302 finalizeShtGroup<ELFT>(this, First); 303 return; 304 } 305 306 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL)) 307 return; 308 309 if (isa<SyntheticSection>(First)) 310 return; 311 312 Link = In.SymTab->getParent()->SectionIndex; 313 // sh_info for SHT_REL[A] sections should contain the section header index of 314 // the section to which the relocation applies. 315 InputSectionBase *S = First->getRelocatedSection(); 316 Info = S->getOutputSection()->SectionIndex; 317 Flags |= SHF_INFO_LINK; 318 } 319 320 // Returns true if S matches /Filename.?\.o$/. 321 static bool isCrtBeginEnd(StringRef S, StringRef Filename) { 322 if (!S.endswith(".o")) 323 return false; 324 S = S.drop_back(2); 325 if (S.endswith(Filename)) 326 return true; 327 return !S.empty() && S.drop_back().endswith(Filename); 328 } 329 330 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); } 331 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); } 332 333 // .ctors and .dtors are sorted by this priority from highest to lowest. 334 // 335 // 1. The section was contained in crtbegin (crtbegin contains 336 // some sentinel value in its .ctors and .dtors so that the runtime 337 // can find the beginning of the sections.) 338 // 339 // 2. The section has an optional priority value in the form of ".ctors.N" 340 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 341 // they are compared as string rather than number. 342 // 343 // 3. The section is just ".ctors" or ".dtors". 344 // 345 // 4. The section was contained in crtend, which contains an end marker. 346 // 347 // In an ideal world, we don't need this function because .init_array and 348 // .ctors are duplicate features (and .init_array is newer.) However, there 349 // are too many real-world use cases of .ctors, so we had no choice to 350 // support that with this rather ad-hoc semantics. 351 static bool compCtors(const InputSection *A, const InputSection *B) { 352 bool BeginA = isCrtbegin(A->File->getName()); 353 bool BeginB = isCrtbegin(B->File->getName()); 354 if (BeginA != BeginB) 355 return BeginA; 356 bool EndA = isCrtend(A->File->getName()); 357 bool EndB = isCrtend(B->File->getName()); 358 if (EndA != EndB) 359 return EndB; 360 StringRef X = A->Name; 361 StringRef Y = B->Name; 362 assert(X.startswith(".ctors") || X.startswith(".dtors")); 363 assert(Y.startswith(".ctors") || Y.startswith(".dtors")); 364 X = X.substr(6); 365 Y = Y.substr(6); 366 return X < Y; 367 } 368 369 // Sorts input sections by the special rules for .ctors and .dtors. 370 // Unfortunately, the rules are different from the one for .{init,fini}_array. 371 // Read the comment above. 372 void OutputSection::sortCtorsDtors() { 373 assert(SectionCommands.size() == 1); 374 auto *ISD = cast<InputSectionDescription>(SectionCommands[0]); 375 std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors); 376 } 377 378 // If an input string is in the form of "foo.N" where N is a number, 379 // return N. Otherwise, returns 65536, which is one greater than the 380 // lowest priority. 381 int elf::getPriority(StringRef S) { 382 size_t Pos = S.rfind('.'); 383 if (Pos == StringRef::npos) 384 return 65536; 385 int V; 386 if (!to_integer(S.substr(Pos + 1), V, 10)) 387 return 65536; 388 return V; 389 } 390 391 std::vector<InputSection *> elf::getInputSections(OutputSection *OS) { 392 std::vector<InputSection *> Ret; 393 for (BaseCommand *Base : OS->SectionCommands) 394 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) 395 Ret.insert(Ret.end(), ISD->Sections.begin(), ISD->Sections.end()); 396 return Ret; 397 } 398 399 // Sorts input sections by section name suffixes, so that .foo.N comes 400 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 401 // We want to keep the original order if the priorities are the same 402 // because the compiler keeps the original initialization order in a 403 // translation unit and we need to respect that. 404 // For more detail, read the section of the GCC's manual about init_priority. 405 void OutputSection::sortInitFini() { 406 // Sort sections by priority. 407 sort([](InputSectionBase *S) { return getPriority(S->Name); }); 408 } 409 410 std::array<uint8_t, 4> OutputSection::getFiller() { 411 if (Filler) 412 return *Filler; 413 if (Flags & SHF_EXECINSTR) 414 return Target->TrapInstr; 415 return {0, 0, 0, 0}; 416 } 417 418 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr); 419 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr); 420 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr); 421 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr); 422 423 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf); 424 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf); 425 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf); 426 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf); 427 428 template void OutputSection::maybeCompress<ELF32LE>(); 429 template void OutputSection::maybeCompress<ELF32BE>(); 430 template void OutputSection::maybeCompress<ELF64LE>(); 431 template void OutputSection::maybeCompress<ELF64BE>(); 432 433 template void OutputSection::finalize<ELF32LE>(); 434 template void OutputSection::finalize<ELF32BE>(); 435 template void OutputSection::finalize<ELF64LE>(); 436 template void OutputSection::finalize<ELF64BE>(); 437