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