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 "Memory.h" 14 #include "Strings.h" 15 #include "SymbolTable.h" 16 #include "SyntheticSections.h" 17 #include "Target.h" 18 #include "Threads.h" 19 #include "llvm/Support/Compression.h" 20 #include "llvm/Support/Dwarf.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::support::endian; 29 using namespace llvm::ELF; 30 31 using namespace lld; 32 using namespace lld::elf; 33 34 uint8_t Out::First; 35 OutputSection *Out::Opd; 36 uint8_t *Out::OpdBuf; 37 PhdrEntry *Out::TlsPhdr; 38 OutputSection *Out::DebugInfo; 39 OutputSection *Out::ElfHeader; 40 OutputSection *Out::ProgramHeaders; 41 OutputSection *Out::PreinitArray; 42 OutputSection *Out::InitArray; 43 OutputSection *Out::FiniArray; 44 45 uint32_t OutputSection::getPhdrFlags() const { 46 uint32_t 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 : SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type, 70 /*Info*/ 0, 71 /*Link*/ 0) {} 72 73 static bool compareByFilePosition(InputSection *A, InputSection *B) { 74 // Synthetic doesn't have link order dependecy, stable_sort will keep it last 75 if (A->kind() == InputSectionBase::Synthetic || 76 B->kind() == InputSectionBase::Synthetic) 77 return false; 78 auto *LA = cast<InputSection>(A->getLinkOrderDep()); 79 auto *LB = cast<InputSection>(B->getLinkOrderDep()); 80 OutputSection *AOut = LA->OutSec; 81 OutputSection *BOut = LB->OutSec; 82 if (AOut != BOut) 83 return AOut->SectionIndex < BOut->SectionIndex; 84 return LA->OutSecOff < LB->OutSecOff; 85 } 86 87 // Compress section contents if this section contains debug info. 88 template <class ELFT> void OutputSection::maybeCompress() { 89 typedef typename ELFT::Chdr Elf_Chdr; 90 91 // Compress only DWARF debug sections. 92 if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) || 93 !Name.startswith(".debug_")) 94 return; 95 96 // Create a section header. 97 ZDebugHeader.resize(sizeof(Elf_Chdr)); 98 auto *Hdr = reinterpret_cast<Elf_Chdr *>(ZDebugHeader.data()); 99 Hdr->ch_type = ELFCOMPRESS_ZLIB; 100 Hdr->ch_size = Size; 101 Hdr->ch_addralign = Alignment; 102 103 // Write section contents to a temporary buffer and compress it. 104 std::vector<uint8_t> Buf(Size); 105 writeTo<ELFT>(Buf.data()); 106 if (Error E = zlib::compress(toStringRef(Buf), CompressedData)) 107 fatal("compress failed: " + llvm::toString(std::move(E))); 108 109 // Update section headers. 110 Size = sizeof(Elf_Chdr) + CompressedData.size(); 111 Flags |= SHF_COMPRESSED; 112 } 113 114 template <class ELFT> void OutputSection::finalize() { 115 if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) { 116 std::sort(Sections.begin(), Sections.end(), compareByFilePosition); 117 assignOffsets(); 118 119 // We must preserve the link order dependency of sections with the 120 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 121 // need to translate the InputSection sh_link to the OutputSection sh_link, 122 // all InputSections in the OutputSection have the same dependency. 123 if (auto *D = this->Sections.front()->getLinkOrderDep()) 124 this->Link = D->OutSec->SectionIndex; 125 } 126 127 uint32_t Type = this->Type; 128 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL)) 129 return; 130 131 InputSection *First = Sections[0]; 132 if (isa<SyntheticSection>(First)) 133 return; 134 135 this->Link = In<ELFT>::SymTab->OutSec->SectionIndex; 136 // sh_info for SHT_REL[A] sections should contain the section header index of 137 // the section to which the relocation applies. 138 InputSectionBase *S = First->getRelocatedSection(); 139 this->Info = S->OutSec->SectionIndex; 140 } 141 142 void OutputSection::addSection(InputSection *S) { 143 assert(S->Live); 144 Sections.push_back(S); 145 S->OutSec = this; 146 this->updateAlignment(S->Alignment); 147 148 // If this section contains a table of fixed-size entries, sh_entsize 149 // holds the element size. Consequently, if this contains two or more 150 // input sections, all of them must have the same sh_entsize. However, 151 // you can put different types of input sections into one output 152 // sectin by using linker scripts. I don't know what to do here. 153 // Probably we sholuld handle that as an error. But for now we just 154 // pick the largest sh_entsize. 155 this->Entsize = std::max(this->Entsize, S->Entsize); 156 } 157 158 // This function is called after we sort input sections 159 // and scan relocations to setup sections' offsets. 160 void OutputSection::assignOffsets() { 161 uint64_t Off = 0; 162 for (InputSection *S : Sections) { 163 Off = alignTo(Off, S->Alignment); 164 S->OutSecOff = Off; 165 Off += S->getSize(); 166 } 167 this->Size = Off; 168 } 169 170 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) { 171 typedef std::pair<unsigned, InputSection *> Pair; 172 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; }; 173 174 std::vector<Pair> V; 175 for (InputSection *S : Sections) 176 V.push_back({Order(S), S}); 177 std::stable_sort(V.begin(), V.end(), Comp); 178 Sections.clear(); 179 for (Pair &P : V) 180 Sections.push_back(P.second); 181 } 182 183 // Sorts input sections by section name suffixes, so that .foo.N comes 184 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 185 // We want to keep the original order if the priorities are the same 186 // because the compiler keeps the original initialization order in a 187 // translation unit and we need to respect that. 188 // For more detail, read the section of the GCC's manual about init_priority. 189 void OutputSection::sortInitFini() { 190 // Sort sections by priority. 191 sort([](InputSectionBase *S) { return getPriority(S->Name); }); 192 } 193 194 // Returns true if S matches /Filename.?\.o$/. 195 static bool isCrtBeginEnd(StringRef S, StringRef Filename) { 196 if (!S.endswith(".o")) 197 return false; 198 S = S.drop_back(2); 199 if (S.endswith(Filename)) 200 return true; 201 return !S.empty() && S.drop_back().endswith(Filename); 202 } 203 204 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); } 205 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); } 206 207 // .ctors and .dtors are sorted by this priority from highest to lowest. 208 // 209 // 1. The section was contained in crtbegin (crtbegin contains 210 // some sentinel value in its .ctors and .dtors so that the runtime 211 // can find the beginning of the sections.) 212 // 213 // 2. The section has an optional priority value in the form of ".ctors.N" 214 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 215 // they are compared as string rather than number. 216 // 217 // 3. The section is just ".ctors" or ".dtors". 218 // 219 // 4. The section was contained in crtend, which contains an end marker. 220 // 221 // In an ideal world, we don't need this function because .init_array and 222 // .ctors are duplicate features (and .init_array is newer.) However, there 223 // are too many real-world use cases of .ctors, so we had no choice to 224 // support that with this rather ad-hoc semantics. 225 static bool compCtors(const InputSection *A, const InputSection *B) { 226 bool BeginA = isCrtbegin(A->File->getName()); 227 bool BeginB = isCrtbegin(B->File->getName()); 228 if (BeginA != BeginB) 229 return BeginA; 230 bool EndA = isCrtend(A->File->getName()); 231 bool EndB = isCrtend(B->File->getName()); 232 if (EndA != EndB) 233 return EndB; 234 StringRef X = A->Name; 235 StringRef Y = B->Name; 236 assert(X.startswith(".ctors") || X.startswith(".dtors")); 237 assert(Y.startswith(".ctors") || Y.startswith(".dtors")); 238 X = X.substr(6); 239 Y = Y.substr(6); 240 if (X.empty() && Y.empty()) 241 return false; 242 return X < Y; 243 } 244 245 // Sorts input sections by the special rules for .ctors and .dtors. 246 // Unfortunately, the rules are different from the one for .{init,fini}_array. 247 // Read the comment above. 248 void OutputSection::sortCtorsDtors() { 249 std::stable_sort(Sections.begin(), Sections.end(), compCtors); 250 } 251 252 // Fill [Buf, Buf + Size) with Filler. 253 // This is used for linker script "=fillexp" command. 254 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) { 255 size_t I = 0; 256 for (; I + 4 < Size; I += 4) 257 memcpy(Buf + I, &Filler, 4); 258 memcpy(Buf + I, &Filler, Size - I); 259 } 260 261 uint32_t OutputSection::getFiller() { 262 // Determine what to fill gaps between InputSections with, as specified by the 263 // linker script. If nothing is specified and this is an executable section, 264 // fall back to trap instructions to prevent bad diassembly and detect invalid 265 // jumps to padding. 266 if (Optional<uint32_t> Filler = Script->getFiller(Name)) 267 return *Filler; 268 if (Flags & SHF_EXECINSTR) 269 return Target->TrapInstr; 270 return 0; 271 } 272 273 template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) { 274 Loc = Buf; 275 276 // We may have already rendered compressed content when using 277 // -compress-debug-sections option. Write it together with header. 278 if (!CompressedData.empty()) { 279 memcpy(Buf, ZDebugHeader.data(), ZDebugHeader.size()); 280 memcpy(Buf + ZDebugHeader.size(), CompressedData.data(), 281 CompressedData.size()); 282 return; 283 } 284 285 // Write leading padding. 286 uint32_t Filler = getFiller(); 287 if (Filler) 288 fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler); 289 290 parallelFor(0, Sections.size(), [=](size_t I) { 291 InputSection *Sec = Sections[I]; 292 Sec->writeTo<ELFT>(Buf); 293 294 // Fill gaps between sections. 295 if (Filler) { 296 uint8_t *Start = Buf + Sec->OutSecOff + Sec->getSize(); 297 uint8_t *End; 298 if (I + 1 == Sections.size()) 299 End = Buf + Size; 300 else 301 End = Buf + Sections[I + 1]->OutSecOff; 302 fill(Start, End - Start, Filler); 303 } 304 }); 305 306 // Linker scripts may have BYTE()-family commands with which you 307 // can write arbitrary bytes to the output. Process them if any. 308 Script->writeDataBytes(Name, Buf); 309 } 310 311 static uint64_t getOutFlags(InputSectionBase *S) { 312 return S->Flags & ~SHF_GROUP & ~SHF_COMPRESSED; 313 } 314 315 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) { 316 // The ELF spec just says 317 // ---------------------------------------------------------------- 318 // In the first phase, input sections that match in name, type and 319 // attribute flags should be concatenated into single sections. 320 // ---------------------------------------------------------------- 321 // 322 // However, it is clear that at least some flags have to be ignored for 323 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be 324 // ignored. We should not have two output .text sections just because one was 325 // in a group and another was not for example. 326 // 327 // It also seems that that wording was a late addition and didn't get the 328 // necessary scrutiny. 329 // 330 // Merging sections with different flags is expected by some users. One 331 // reason is that if one file has 332 // 333 // int *const bar __attribute__((section(".foo"))) = (int *)0; 334 // 335 // gcc with -fPIC will produce a read only .foo section. But if another 336 // file has 337 // 338 // int zed; 339 // int *const bar __attribute__((section(".foo"))) = (int *)&zed; 340 // 341 // gcc with -fPIC will produce a read write section. 342 // 343 // Last but not least, when using linker script the merge rules are forced by 344 // the script. Unfortunately, linker scripts are name based. This means that 345 // expressions like *(.foo*) can refer to multiple input sections with 346 // different flags. We cannot put them in different output sections or we 347 // would produce wrong results for 348 // 349 // start = .; *(.foo.*) end = .; *(.bar) 350 // 351 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to 352 // another. The problem is that there is no way to layout those output 353 // sections such that the .foo sections are the only thing between the start 354 // and end symbols. 355 // 356 // Given the above issues, we instead merge sections by name and error on 357 // incompatible types and flags. 358 359 uint32_t Alignment = 0; 360 uint64_t Flags = 0; 361 if (Config->Relocatable && (C->Flags & SHF_MERGE)) { 362 Alignment = std::max<uint64_t>(C->Alignment, C->Entsize); 363 Flags = C->Flags & (SHF_MERGE | SHF_STRINGS); 364 } 365 366 return SectionKey{OutsecName, Flags, Alignment}; 367 } 368 369 OutputSectionFactory::OutputSectionFactory( 370 std::vector<OutputSection *> &OutputSections) 371 : OutputSections(OutputSections) {} 372 373 static uint64_t getIncompatibleFlags(uint64_t Flags) { 374 return Flags & (SHF_ALLOC | SHF_TLS); 375 } 376 377 // We allow sections of types listed below to merged into a 378 // single progbits section. This is typically done by linker 379 // scripts. Merging nobits and progbits will force disk space 380 // to be allocated for nobits sections. Other ones don't require 381 // any special treatment on top of progbits, so there doesn't 382 // seem to be a harm in merging them. 383 static bool canMergeToProgbits(unsigned Type) { 384 return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY || 385 Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY || 386 Type == SHT_NOTE; 387 } 388 389 static void reportDiscarded(InputSectionBase *IS) { 390 if (!Config->PrintGcSections) 391 return; 392 message("removing unused section from '" + IS->Name + "' in file '" + 393 IS->File->getName()); 394 } 395 396 void OutputSectionFactory::addInputSec(InputSectionBase *IS, 397 StringRef OutsecName) { 398 if (!IS->Live) { 399 reportDiscarded(IS); 400 return; 401 } 402 403 SectionKey Key = createKey(IS, OutsecName); 404 uint64_t Flags = getOutFlags(IS); 405 OutputSection *&Sec = Map[Key]; 406 if (Sec) { 407 if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags)) 408 error("Section has flags incompatible with others with the same name " + 409 toString(IS)); 410 if (Sec->Type != IS->Type) { 411 if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type)) 412 Sec->Type = SHT_PROGBITS; 413 else 414 error("Section has different type from others with the same name " + 415 toString(IS)); 416 } 417 Sec->Flags |= Flags; 418 } else { 419 Sec = make<OutputSection>(Key.Name, IS->Type, Flags); 420 OutputSections.push_back(Sec); 421 } 422 423 Sec->addSection(cast<InputSection>(IS)); 424 } 425 426 OutputSectionFactory::~OutputSectionFactory() {} 427 428 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() { 429 return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0}; 430 } 431 432 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() { 433 return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0}; 434 } 435 436 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) { 437 return hash_combine(Val.Name, Val.Flags, Val.Alignment); 438 } 439 440 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS, 441 const SectionKey &RHS) { 442 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) && 443 LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment; 444 } 445 446 uint64_t elf::getHeaderSize() { 447 if (Config->OFormatBinary) 448 return 0; 449 return Out::ElfHeader->Size + Out::ProgramHeaders->Size; 450 } 451 452 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr); 453 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr); 454 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr); 455 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr); 456 457 template void OutputSection::finalize<ELF32LE>(); 458 template void OutputSection::finalize<ELF32BE>(); 459 template void OutputSection::finalize<ELF64LE>(); 460 template void OutputSection::finalize<ELF64BE>(); 461 462 template void OutputSection::maybeCompress<ELF32LE>(); 463 template void OutputSection::maybeCompress<ELF32BE>(); 464 template void OutputSection::maybeCompress<ELF64LE>(); 465 template void OutputSection::maybeCompress<ELF64BE>(); 466 467 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf); 468 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf); 469 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf); 470 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf); 471