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