1 //===- LinkerScript.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 // This file contains the parser/evaluator of the linker script.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LinkerScript.h"
15 #include "Config.h"
16 #include "InputSection.h"
17 #include "Memory.h"
18 #include "OutputSections.h"
19 #include "Strings.h"
20 #include "SymbolTable.h"
21 #include "Symbols.h"
22 #include "SyntheticSections.h"
23 #include "Target.h"
24 #include "Threads.h"
25 #include "Writer.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/BinaryFormat/ELF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Path.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <iterator>
40 #include <limits>
41 #include <string>
42 #include <vector>
43 
44 using namespace llvm;
45 using namespace llvm::ELF;
46 using namespace llvm::object;
47 using namespace llvm::support::endian;
48 using namespace lld;
49 using namespace lld::elf;
50 
51 LinkerScript *elf::Script;
52 
53 uint64_t ExprValue::getValue() const {
54   if (Sec) {
55     if (OutputSection *OS = Sec->getOutputSection())
56       return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment);
57     error(Loc + ": unable to evaluate expression: input section " + Sec->Name +
58           " has no output section assigned");
59   }
60   return alignTo(Val, Alignment);
61 }
62 
63 uint64_t ExprValue::getSecAddr() const {
64   if (Sec)
65     return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
66   return 0;
67 }
68 
69 template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
70   Symbol *Sym;
71   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
72   std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
73       Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
74       /*File*/ nullptr);
75   Sym->Binding = STB_GLOBAL;
76   ExprValue Value = Cmd->Expression();
77   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
78 
79   // We want to set symbol values early if we can. This allows us to use symbols
80   // as variables in linker scripts. Doing so allows us to write expressions
81   // like this: `alignment = 16; . = ALIGN(., alignment)`
82   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
83   replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
84                               STT_NOTYPE, SymValue, 0, Sec, nullptr);
85   return Sym->body();
86 }
87 
88 OutputSectionCommand *
89 LinkerScript::createOutputSectionCommand(StringRef Name, StringRef Location) {
90   OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
91   OutputSectionCommand *Cmd;
92   if (CmdRef && CmdRef->Location.empty()) {
93     // There was a forward reference.
94     Cmd = CmdRef;
95   } else {
96     Cmd = make<OutputSectionCommand>(Name);
97     if (!CmdRef)
98       CmdRef = Cmd;
99   }
100   Cmd->Location = Location;
101   return Cmd;
102 }
103 
104 OutputSectionCommand *
105 LinkerScript::getOrCreateOutputSectionCommand(StringRef Name) {
106   OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
107   if (!CmdRef)
108     CmdRef = make<OutputSectionCommand>(Name);
109   return CmdRef;
110 }
111 
112 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
113   uint64_t Val = E().getValue();
114   if (Val < Dot) {
115     if (InSec)
116       error(Loc + ": unable to move location counter backward for: " +
117             CurAddressState->OutSec->Name);
118     else
119       error(Loc + ": unable to move location counter backward");
120   }
121   Dot = Val;
122   // Update to location counter means update to section size.
123   if (InSec)
124     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
125 }
126 
127 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
128 // symbols, whose value is an offset from beginning of section and regular
129 // symbols whose value is absolute.
130 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
131   if (Cmd->Name == ".") {
132     setDot(Cmd->Expression, Cmd->Location, InSec);
133     return;
134   }
135 
136   if (!Cmd->Sym)
137     return;
138 
139   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
140   ExprValue V = Cmd->Expression();
141   if (V.isAbsolute()) {
142     Sym->Value = V.getValue();
143   } else {
144     Sym->Section = V.Sec;
145     Sym->Value = alignTo(V.Val, V.Alignment);
146   }
147 }
148 
149 static SymbolBody *findSymbol(StringRef S) {
150   switch (Config->EKind) {
151   case ELF32LEKind:
152     return Symtab<ELF32LE>::X->find(S);
153   case ELF32BEKind:
154     return Symtab<ELF32BE>::X->find(S);
155   case ELF64LEKind:
156     return Symtab<ELF64LE>::X->find(S);
157   case ELF64BEKind:
158     return Symtab<ELF64BE>::X->find(S);
159   default:
160     llvm_unreachable("unknown Config->EKind");
161   }
162 }
163 
164 static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
165   switch (Config->EKind) {
166   case ELF32LEKind:
167     return addRegular<ELF32LE>(Cmd);
168   case ELF32BEKind:
169     return addRegular<ELF32BE>(Cmd);
170   case ELF64LEKind:
171     return addRegular<ELF64LE>(Cmd);
172   case ELF64BEKind:
173     return addRegular<ELF64BE>(Cmd);
174   default:
175     llvm_unreachable("unknown Config->EKind");
176   }
177 }
178 
179 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
180   if (Cmd->Name == ".")
181     return;
182 
183   // If a symbol was in PROVIDE(), we need to define it only when
184   // it is a referenced undefined symbol.
185   SymbolBody *B = findSymbol(Cmd->Name);
186   if (Cmd->Provide && (!B || B->isDefined()))
187     return;
188 
189   Cmd->Sym = addRegularSymbol(Cmd);
190 }
191 
192 bool SymbolAssignment::classof(const BaseCommand *C) {
193   return C->Kind == AssignmentKind;
194 }
195 
196 bool OutputSectionCommand::classof(const BaseCommand *C) {
197   return C->Kind == OutputSectionKind;
198 }
199 
200 // Fill [Buf, Buf + Size) with Filler.
201 // This is used for linker script "=fillexp" command.
202 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
203   size_t I = 0;
204   for (; I + 4 < Size; I += 4)
205     memcpy(Buf + I, &Filler, 4);
206   memcpy(Buf + I, &Filler, Size - I);
207 }
208 
209 bool InputSectionDescription::classof(const BaseCommand *C) {
210   return C->Kind == InputSectionKind;
211 }
212 
213 bool AssertCommand::classof(const BaseCommand *C) {
214   return C->Kind == AssertKind;
215 }
216 
217 bool BytesDataCommand::classof(const BaseCommand *C) {
218   return C->Kind == BytesDataKind;
219 }
220 
221 static StringRef basename(InputSectionBase *S) {
222   if (S->File)
223     return sys::path::filename(S->File->getName());
224   return "";
225 }
226 
227 bool LinkerScript::shouldKeep(InputSectionBase *S) {
228   for (InputSectionDescription *ID : Opt.KeptSections)
229     if (ID->FilePat.match(basename(S)))
230       for (SectionPattern &P : ID->SectionPatterns)
231         if (P.SectionPat.match(S->Name))
232           return true;
233   return false;
234 }
235 
236 // A helper function for the SORT() command.
237 static std::function<bool(InputSectionBase *, InputSectionBase *)>
238 getComparator(SortSectionPolicy K) {
239   switch (K) {
240   case SortSectionPolicy::Alignment:
241     return [](InputSectionBase *A, InputSectionBase *B) {
242       // ">" is not a mistake. Sections with larger alignments are placed
243       // before sections with smaller alignments in order to reduce the
244       // amount of padding necessary. This is compatible with GNU.
245       return A->Alignment > B->Alignment;
246     };
247   case SortSectionPolicy::Name:
248     return [](InputSectionBase *A, InputSectionBase *B) {
249       return A->Name < B->Name;
250     };
251   case SortSectionPolicy::Priority:
252     return [](InputSectionBase *A, InputSectionBase *B) {
253       return getPriority(A->Name) < getPriority(B->Name);
254     };
255   default:
256     llvm_unreachable("unknown sort policy");
257   }
258 }
259 
260 // A helper function for the SORT() command.
261 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
262                              ConstraintKind Kind) {
263   if (Kind == ConstraintKind::NoConstraint)
264     return true;
265 
266   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
267     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
268   });
269 
270   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
271          (!IsRW && Kind == ConstraintKind::ReadOnly);
272 }
273 
274 static void sortSections(InputSection **Begin, InputSection **End,
275                          SortSectionPolicy K) {
276   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
277     std::stable_sort(Begin, End, getComparator(K));
278 }
279 
280 // Compute and remember which sections the InputSectionDescription matches.
281 std::vector<InputSection *>
282 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
283   std::vector<InputSection *> Ret;
284 
285   // Collects all sections that satisfy constraints of Cmd.
286   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
287     size_t SizeBefore = Ret.size();
288 
289     for (InputSectionBase *Sec : InputSections) {
290       if (Sec->Assigned)
291         continue;
292 
293       if (!Sec->Live) {
294         reportDiscarded(Sec);
295         continue;
296       }
297 
298       // For -emit-relocs we have to ignore entries like
299       //   .rela.dyn : { *(.rela.data) }
300       // which are common because they are in the default bfd script.
301       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
302         continue;
303 
304       StringRef Filename = basename(Sec);
305       if (!Cmd->FilePat.match(Filename) ||
306           Pat.ExcludedFilePat.match(Filename) ||
307           !Pat.SectionPat.match(Sec->Name))
308         continue;
309 
310       Ret.push_back(cast<InputSection>(Sec));
311       Sec->Assigned = true;
312     }
313 
314     // Sort sections as instructed by SORT-family commands and --sort-section
315     // option. Because SORT-family commands can be nested at most two depth
316     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
317     // line option is respected even if a SORT command is given, the exact
318     // behavior we have here is a bit complicated. Here are the rules.
319     //
320     // 1. If two SORT commands are given, --sort-section is ignored.
321     // 2. If one SORT command is given, and if it is not SORT_NONE,
322     //    --sort-section is handled as an inner SORT command.
323     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
324     // 4. If no SORT command is given, sort according to --sort-section.
325     InputSection **Begin = Ret.data() + SizeBefore;
326     InputSection **End = Ret.data() + Ret.size();
327     if (Pat.SortOuter != SortSectionPolicy::None) {
328       if (Pat.SortInner == SortSectionPolicy::Default)
329         sortSections(Begin, End, Config->SortSection);
330       else
331         sortSections(Begin, End, Pat.SortInner);
332       sortSections(Begin, End, Pat.SortOuter);
333     }
334   }
335   return Ret;
336 }
337 
338 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
339   for (InputSectionBase *S : V) {
340     S->Live = false;
341     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
342         S == InX::DynStrTab)
343       error("discarding " + S->Name + " section is not allowed");
344     discard(S->DependentSections);
345   }
346 }
347 
348 std::vector<InputSectionBase *>
349 LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
350   std::vector<InputSectionBase *> Ret;
351 
352   for (BaseCommand *Base : OutCmd.Commands) {
353     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
354     if (!Cmd)
355       continue;
356 
357     Cmd->Sections = computeInputSections(Cmd);
358     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
359   }
360 
361   return Ret;
362 }
363 
364 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
365   // A symbol can be assigned before any section is mentioned in the linker
366   // script. In an DSO, the symbol values are addresses, so the only important
367   // section values are:
368   // * SHN_UNDEF
369   // * SHN_ABS
370   // * Any value meaning a regular section.
371   // To handle that, create a dummy aether section that fills the void before
372   // the linker scripts switches to another section. It has an index of one
373   // which will map to whatever the first actual section is.
374   Aether = make<OutputSection>("", 0, SHF_ALLOC);
375   Aether->SectionIndex = 1;
376   auto State = make_unique<AddressState>(Opt);
377   CurAddressState = State.get();
378   CurAddressState->OutSec = Aether;
379   Dot = 0;
380 
381   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
382     // Handle symbol assignments outside of any output section.
383     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
384       addSymbol(Cmd);
385       continue;
386     }
387 
388     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
389       std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
390 
391       // The output section name `/DISCARD/' is special.
392       // Any input section assigned to it is discarded.
393       if (Cmd->Name == "/DISCARD/") {
394         discard(V);
395         continue;
396       }
397 
398       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
399       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
400       // sections satisfy a given constraint. If not, a directive is handled
401       // as if it wasn't present from the beginning.
402       //
403       // Because we'll iterate over Commands many more times, the easiest
404       // way to "make it as if it wasn't present" is to just remove it.
405       if (!matchConstraints(V, Cmd->Constraint)) {
406         for (InputSectionBase *S : V)
407           S->Assigned = false;
408         Opt.Commands.erase(Opt.Commands.begin() + I);
409         --I;
410         continue;
411       }
412 
413       // A directive may contain symbol definitions like this:
414       // ".foo : { ...; bar = .; }". Handle them.
415       for (BaseCommand *Base : Cmd->Commands)
416         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
417           addSymbol(OutCmd);
418 
419       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
420       // is given, input sections are aligned to that value, whether the
421       // given value is larger or smaller than the original section alignment.
422       if (Cmd->SubalignExpr) {
423         uint32_t Subalign = Cmd->SubalignExpr().getValue();
424         for (InputSectionBase *S : V)
425           S->Alignment = Subalign;
426       }
427 
428       // Add input sections to an output section.
429       for (InputSectionBase *S : V)
430         Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
431       if (OutputSection *Sec = Cmd->Sec) {
432         assert(Sec->SectionIndex == INT_MAX);
433         Sec->SectionIndex = I;
434         if (Cmd->Noload)
435           Sec->Type = SHT_NOBITS;
436         SecToCommand[Sec] = Cmd;
437       }
438     }
439   }
440 }
441 
442 void LinkerScript::fabricateDefaultCommands() {
443   std::vector<BaseCommand *> Commands;
444 
445   // Define start address
446   uint64_t StartAddr = -1;
447 
448   // The Sections with -T<section> have been sorted in order of ascending
449   // address. We must lower StartAddr if the lowest -T<section address> as
450   // calls to setDot() must be monotonically increasing.
451   for (auto& KV : Config->SectionStartMap)
452     StartAddr = std::min(StartAddr, KV.second);
453 
454   Commands.push_back(make<SymbolAssignment>(
455       ".",
456       [=] {
457         return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
458       },
459       ""));
460 
461   // For each OutputSection that needs a VA fabricate an OutputSectionCommand
462   // with an InputSectionDescription describing the InputSections
463   for (OutputSection *Sec : OutputSections) {
464     auto *OSCmd = createOutputSectionCommand(Sec->Name, "<internal>");
465     OSCmd->Sec = Sec;
466     SecToCommand[Sec] = OSCmd;
467 
468     Commands.push_back(OSCmd);
469     if (Sec->Sections.size()) {
470       auto *ISD = make<InputSectionDescription>("");
471       OSCmd->Commands.push_back(ISD);
472       for (InputSection *ISec : Sec->Sections) {
473         ISD->Sections.push_back(ISec);
474         ISec->Assigned = true;
475       }
476     }
477   }
478   // SECTIONS commands run before other non SECTIONS commands
479   Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
480   Opt.Commands = std::move(Commands);
481 }
482 
483 // Add sections that didn't match any sections command.
484 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
485   unsigned NumCommands = Opt.Commands.size();
486   for (InputSectionBase *S : InputSections) {
487     if (!S->Live || S->Parent)
488       continue;
489     StringRef Name = getOutputSectionName(S->Name);
490     auto End = Opt.Commands.begin() + NumCommands;
491     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
492       if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
493         return Cmd->Name == Name;
494       return false;
495     });
496     OutputSectionCommand *Cmd;
497     if (I == End) {
498       Factory.addInputSec(S, Name);
499       OutputSection *Sec = S->getOutputSection();
500       assert(Sec->SectionIndex == INT_MAX);
501       OutputSectionCommand *&CmdRef = SecToCommand[Sec];
502       if (!CmdRef) {
503         CmdRef = createOutputSectionCommand(Sec->Name, "<internal>");
504         CmdRef->Sec = Sec;
505         Opt.Commands.push_back(CmdRef);
506       }
507       Cmd = CmdRef;
508     } else {
509       Cmd = cast<OutputSectionCommand>(*I);
510       Factory.addInputSec(S, Name, Cmd->Sec);
511       if (OutputSection *Sec = Cmd->Sec) {
512         SecToCommand[Sec] = Cmd;
513         unsigned Index = std::distance(Opt.Commands.begin(), I);
514         assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
515         Sec->SectionIndex = Index;
516       }
517     }
518     auto *ISD = make<InputSectionDescription>("");
519     ISD->Sections.push_back(cast<InputSection>(S));
520     Cmd->Commands.push_back(ISD);
521   }
522 }
523 
524 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
525   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
526                 CurAddressState->OutSec->Type == SHT_NOBITS;
527   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
528   Start = alignTo(Start, Align);
529   uint64_t End = Start + Size;
530 
531   if (IsTbss)
532     CurAddressState->ThreadBssOffset = End - Dot;
533   else
534     Dot = End;
535   return End;
536 }
537 
538 void LinkerScript::output(InputSection *S) {
539   uint64_t Pos = advance(S->getSize(), S->Alignment);
540   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
541 
542   // Update output section size after adding each section. This is so that
543   // SIZEOF works correctly in the case below:
544   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
545   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
546 
547   // If there is a memory region associated with this input section, then
548   // place the section in that region and update the region index.
549   if (CurAddressState->MemRegion) {
550     uint64_t &CurOffset =
551         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
552     CurOffset += CurAddressState->OutSec->Size;
553     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
554     if (CurSize > CurAddressState->MemRegion->Length) {
555       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
556       error("section '" + CurAddressState->OutSec->Name +
557             "' will not fit in region '" + CurAddressState->MemRegion->Name +
558             "': overflowed by " + Twine(OverflowAmt) + " bytes");
559     }
560   }
561 }
562 
563 void LinkerScript::switchTo(OutputSection *Sec) {
564   if (CurAddressState->OutSec == Sec)
565     return;
566 
567   CurAddressState->OutSec = Sec;
568   CurAddressState->OutSec->Addr =
569       advance(0, CurAddressState->OutSec->Alignment);
570 
571   // If neither AT nor AT> is specified for an allocatable section, the linker
572   // will set the LMA such that the difference between VMA and LMA for the
573   // section is the same as the preceding output section in the same region
574   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
575   if (CurAddressState->LMAOffset)
576     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
577 }
578 
579 void LinkerScript::process(BaseCommand &Base) {
580   // This handles the assignments to symbol or to the dot.
581   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
582     assignSymbol(Cmd, true);
583     return;
584   }
585 
586   // Handle BYTE(), SHORT(), LONG(), or QUAD().
587   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
588     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
589     Dot += Cmd->Size;
590     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
591     return;
592   }
593 
594   // Handle ASSERT().
595   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
596     Cmd->Expression();
597     return;
598   }
599 
600   // Handle a single input section description command.
601   // It calculates and assigns the offsets for each section and also
602   // updates the output section size.
603   auto &Cmd = cast<InputSectionDescription>(Base);
604   for (InputSection *Sec : Cmd.Sections) {
605     // We tentatively added all synthetic sections at the beginning and removed
606     // empty ones afterwards (because there is no way to know whether they were
607     // going be empty or not other than actually running linker scripts.)
608     // We need to ignore remains of empty sections.
609     if (auto *S = dyn_cast<SyntheticSection>(Sec))
610       if (S->empty())
611         continue;
612 
613     if (!Sec->Live)
614       continue;
615     assert(CurAddressState->OutSec == Sec->getParent());
616     output(Sec);
617   }
618 }
619 
620 // This function searches for a memory region to place the given output
621 // section in. If found, a pointer to the appropriate memory region is
622 // returned. Otherwise, a nullptr is returned.
623 MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
624   // If a memory region name was specified in the output section command,
625   // then try to find that region first.
626   if (!Cmd->MemoryRegionName.empty()) {
627     auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
628     if (It != Opt.MemoryRegions.end())
629       return &It->second;
630     error("memory region '" + Cmd->MemoryRegionName + "' not declared");
631     return nullptr;
632   }
633 
634   // If at least one memory region is defined, all sections must
635   // belong to some memory region. Otherwise, we don't need to do
636   // anything for memory regions.
637   if (Opt.MemoryRegions.empty())
638     return nullptr;
639 
640   OutputSection *Sec = Cmd->Sec;
641   // See if a region can be found by matching section flags.
642   for (auto &Pair : Opt.MemoryRegions) {
643     MemoryRegion &M = Pair.second;
644     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
645       return &M;
646   }
647 
648   // Otherwise, no suitable region was found.
649   if (Sec->Flags & SHF_ALLOC)
650     error("no memory region specified for section '" + Sec->Name + "'");
651   return nullptr;
652 }
653 
654 // This function assigns offsets to input sections and an output section
655 // for a single sections command (e.g. ".text { *(.text); }").
656 void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
657   OutputSection *Sec = Cmd->Sec;
658   if (!Sec)
659     return;
660 
661   if (!(Sec->Flags & SHF_ALLOC))
662     Dot = 0;
663   else if (Cmd->AddrExpr)
664     setDot(Cmd->AddrExpr, Cmd->Location, false);
665 
666   if (Cmd->LMAExpr) {
667     uint64_t D = Dot;
668     CurAddressState->LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
669   }
670 
671   CurAddressState->MemRegion = Cmd->MemRegion;
672   if (CurAddressState->MemRegion)
673     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
674   switchTo(Sec);
675 
676   // We do not support custom layout for compressed debug sectons.
677   // At this point we already know their size and have compressed content.
678   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
679     return;
680 
681   for (BaseCommand *C : Cmd->Commands)
682     process(*C);
683 }
684 
685 void LinkerScript::removeEmptyCommands() {
686   // It is common practice to use very generic linker scripts. So for any
687   // given run some of the output sections in the script will be empty.
688   // We could create corresponding empty output sections, but that would
689   // clutter the output.
690   // We instead remove trivially empty sections. The bfd linker seems even
691   // more aggressive at removing them.
692   auto Pos = std::remove_if(
693       Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
694         if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
695           return Cmd->Sec == nullptr;
696         return false;
697       });
698   Opt.Commands.erase(Pos, Opt.Commands.end());
699 }
700 
701 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
702   for (BaseCommand *Base : Cmd.Commands)
703     if (!isa<InputSectionDescription>(*Base))
704       return false;
705   return true;
706 }
707 
708 void LinkerScript::adjustSectionsBeforeSorting() {
709   // If the output section contains only symbol assignments, create a
710   // corresponding output section. The bfd linker seems to only create them if
711   // '.' is assigned to, but creating these section should not have any bad
712   // consequeces and gives us a section to put the symbol in.
713   uint64_t Flags = SHF_ALLOC;
714 
715   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
716     auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
717     if (!Cmd)
718       continue;
719     if (OutputSection *Sec = Cmd->Sec) {
720       Flags = Sec->Flags;
721       continue;
722     }
723 
724     if (isAllSectionDescription(*Cmd))
725       continue;
726 
727     auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
728     OutSec->SectionIndex = I;
729     Cmd->Sec = OutSec;
730     SecToCommand[OutSec] = Cmd;
731   }
732 }
733 
734 void LinkerScript::adjustSectionsAfterSorting() {
735   // Try and find an appropriate memory region to assign offsets in.
736   for (BaseCommand *Base : Opt.Commands) {
737     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
738       Cmd->MemRegion = findMemoryRegion(Cmd);
739       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
740       if (Cmd->AlignExpr)
741 	Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
742     }
743   }
744 
745   // If output section command doesn't specify any segments,
746   // and we haven't previously assigned any section to segment,
747   // then we simply assign section to the very first load segment.
748   // Below is an example of such linker script:
749   // PHDRS { seg PT_LOAD; }
750   // SECTIONS { .aaa : { *(.aaa) } }
751   std::vector<StringRef> DefPhdrs;
752   auto FirstPtLoad =
753       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
754                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
755   if (FirstPtLoad != Opt.PhdrsCommands.end())
756     DefPhdrs.push_back(FirstPtLoad->Name);
757 
758   // Walk the commands and propagate the program headers to commands that don't
759   // explicitly specify them.
760   for (BaseCommand *Base : Opt.Commands) {
761     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
762     if (!Cmd)
763       continue;
764 
765     if (Cmd->Phdrs.empty()) {
766       OutputSection *Sec = Cmd->Sec;
767       // To match the bfd linker script behaviour, only propagate program
768       // headers to sections that are allocated.
769       if (Sec && (Sec->Flags & SHF_ALLOC))
770         Cmd->Phdrs = DefPhdrs;
771     } else {
772       DefPhdrs = Cmd->Phdrs;
773     }
774   }
775 
776   removeEmptyCommands();
777 }
778 
779 void LinkerScript::processNonSectionCommands() {
780   for (BaseCommand *Base : Opt.Commands) {
781     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
782       assignSymbol(Cmd, false);
783     else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
784       Cmd->Expression();
785   }
786 }
787 
788 void LinkerScript::allocateHeaders(std::vector<PhdrEntry> &Phdrs) {
789   uint64_t Min = std::numeric_limits<uint64_t>::max();
790   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
791     OutputSection *Sec = Cmd->Sec;
792     if (Sec->Flags & SHF_ALLOC)
793       Min = std::min<uint64_t>(Min, Sec->Addr);
794   }
795 
796   auto FirstPTLoad = llvm::find_if(
797       Phdrs, [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
798   if (FirstPTLoad == Phdrs.end())
799     return;
800 
801   uint64_t HeaderSize = getHeaderSize();
802   if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
803     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
804     Out::ElfHeader->Addr = Min;
805     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
806     return;
807   }
808 
809   assert(FirstPTLoad->First == Out::ElfHeader);
810   OutputSection *ActualFirst = nullptr;
811   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
812     OutputSection *Sec = Cmd->Sec;
813     if (Sec->FirstInPtLoad == Out::ElfHeader) {
814       ActualFirst = Sec;
815       break;
816     }
817   }
818   if (ActualFirst) {
819     for (OutputSectionCommand *Cmd : OutputSectionCommands) {
820       OutputSection *Sec = Cmd->Sec;
821       if (Sec->FirstInPtLoad == Out::ElfHeader)
822         Sec->FirstInPtLoad = ActualFirst;
823     }
824     FirstPTLoad->First = ActualFirst;
825   } else {
826     Phdrs.erase(FirstPTLoad);
827   }
828 
829   auto PhdrI = llvm::find_if(
830       Phdrs, [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
831   if (PhdrI != Phdrs.end())
832     Phdrs.erase(PhdrI);
833 }
834 
835 LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
836   for (auto &MRI : Opt.MemoryRegions) {
837     const MemoryRegion *MR = &MRI.second;
838     MemRegionOffset[MR] = MR->Origin;
839   }
840 }
841 
842 void LinkerScript::assignAddresses() {
843   // Assign addresses as instructed by linker script SECTIONS sub-commands.
844   Dot = 0;
845   auto State = make_unique<AddressState>(Opt);
846   CurAddressState = State.get();
847   ErrorOnMissingSection = true;
848   switchTo(Aether);
849 
850   for (BaseCommand *Base : Opt.Commands) {
851     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
852       assignSymbol(Cmd, false);
853       continue;
854     }
855 
856     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
857       Cmd->Expression();
858       continue;
859     }
860 
861     auto *Cmd = cast<OutputSectionCommand>(Base);
862     assignOffsets(Cmd);
863   }
864 }
865 
866 // Creates program headers as instructed by PHDRS linker script command.
867 std::vector<PhdrEntry> LinkerScript::createPhdrs() {
868   std::vector<PhdrEntry> Ret;
869 
870   // Process PHDRS and FILEHDR keywords because they are not
871   // real output sections and cannot be added in the following loop.
872   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
873     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
874     PhdrEntry &Phdr = Ret.back();
875 
876     if (Cmd.HasFilehdr)
877       Phdr.add(Out::ElfHeader);
878     if (Cmd.HasPhdrs)
879       Phdr.add(Out::ProgramHeaders);
880 
881     if (Cmd.LMAExpr) {
882       Phdr.p_paddr = Cmd.LMAExpr().getValue();
883       Phdr.HasLMA = true;
884     }
885   }
886 
887   // Add output sections to program headers.
888   for (OutputSectionCommand *Cmd : OutputSectionCommands) {
889     // Assign headers specified by linker script
890     for (size_t Id : getPhdrIndices(Cmd)) {
891       OutputSection *Sec = Cmd->Sec;
892       Ret[Id].add(Sec);
893       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
894         Ret[Id].p_flags |= Sec->getPhdrFlags();
895     }
896   }
897   return Ret;
898 }
899 
900 bool LinkerScript::ignoreInterpSection() {
901   // Ignore .interp section in case we have PHDRS specification
902   // and PT_INTERP isn't listed.
903   if (Opt.PhdrsCommands.empty())
904     return false;
905   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
906     if (Cmd.Type == PT_INTERP)
907       return false;
908   return true;
909 }
910 
911 OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
912   auto I = SecToCommand.find(Sec);
913   if (I == SecToCommand.end())
914     return nullptr;
915   return I->second;
916 }
917 
918 void OutputSectionCommand::sort(std::function<int(InputSectionBase *S)> Order) {
919   typedef std::pair<unsigned, InputSection *> Pair;
920   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
921 
922   std::vector<Pair> V;
923   assert(Commands.size() == 1);
924   auto *ISD = cast<InputSectionDescription>(Commands[0]);
925   for (InputSection *S : ISD->Sections)
926     V.push_back({Order(S), S});
927   std::stable_sort(V.begin(), V.end(), Comp);
928   ISD->Sections.clear();
929   for (Pair &P : V)
930     ISD->Sections.push_back(P.second);
931 }
932 
933 // Returns true if S matches /Filename.?\.o$/.
934 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
935   if (!S.endswith(".o"))
936     return false;
937   S = S.drop_back(2);
938   if (S.endswith(Filename))
939     return true;
940   return !S.empty() && S.drop_back().endswith(Filename);
941 }
942 
943 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
944 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
945 
946 // .ctors and .dtors are sorted by this priority from highest to lowest.
947 //
948 //  1. The section was contained in crtbegin (crtbegin contains
949 //     some sentinel value in its .ctors and .dtors so that the runtime
950 //     can find the beginning of the sections.)
951 //
952 //  2. The section has an optional priority value in the form of ".ctors.N"
953 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
954 //     they are compared as string rather than number.
955 //
956 //  3. The section is just ".ctors" or ".dtors".
957 //
958 //  4. The section was contained in crtend, which contains an end marker.
959 //
960 // In an ideal world, we don't need this function because .init_array and
961 // .ctors are duplicate features (and .init_array is newer.) However, there
962 // are too many real-world use cases of .ctors, so we had no choice to
963 // support that with this rather ad-hoc semantics.
964 static bool compCtors(const InputSection *A, const InputSection *B) {
965   bool BeginA = isCrtbegin(A->File->getName());
966   bool BeginB = isCrtbegin(B->File->getName());
967   if (BeginA != BeginB)
968     return BeginA;
969   bool EndA = isCrtend(A->File->getName());
970   bool EndB = isCrtend(B->File->getName());
971   if (EndA != EndB)
972     return EndB;
973   StringRef X = A->Name;
974   StringRef Y = B->Name;
975   assert(X.startswith(".ctors") || X.startswith(".dtors"));
976   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
977   X = X.substr(6);
978   Y = Y.substr(6);
979   if (X.empty() && Y.empty())
980     return false;
981   return X < Y;
982 }
983 
984 // Sorts input sections by the special rules for .ctors and .dtors.
985 // Unfortunately, the rules are different from the one for .{init,fini}_array.
986 // Read the comment above.
987 void OutputSectionCommand::sortCtorsDtors() {
988   assert(Commands.size() == 1);
989   auto *ISD = cast<InputSectionDescription>(Commands[0]);
990   std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors);
991 }
992 
993 // Sorts input sections by section name suffixes, so that .foo.N comes
994 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
995 // We want to keep the original order if the priorities are the same
996 // because the compiler keeps the original initialization order in a
997 // translation unit and we need to respect that.
998 // For more detail, read the section of the GCC's manual about init_priority.
999 void OutputSectionCommand::sortInitFini() {
1000   // Sort sections by priority.
1001   sort([](InputSectionBase *S) { return getPriority(S->Name); });
1002 }
1003 
1004 uint32_t OutputSectionCommand::getFiller() {
1005   if (Filler)
1006     return *Filler;
1007   if (Sec->Flags & SHF_EXECINSTR)
1008     return Target->TrapInstr;
1009   return 0;
1010 }
1011 
1012 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
1013   if (Size == 1)
1014     *Buf = Data;
1015   else if (Size == 2)
1016     write16(Buf, Data, Config->Endianness);
1017   else if (Size == 4)
1018     write32(Buf, Data, Config->Endianness);
1019   else if (Size == 8)
1020     write64(Buf, Data, Config->Endianness);
1021   else
1022     llvm_unreachable("unsupported Size argument");
1023 }
1024 
1025 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1026   // Synthetic doesn't have link order dependecy, stable_sort will keep it last
1027   if (A->kind() == InputSectionBase::Synthetic ||
1028       B->kind() == InputSectionBase::Synthetic)
1029     return false;
1030   InputSection *LA = A->getLinkOrderDep();
1031   InputSection *LB = B->getLinkOrderDep();
1032   OutputSection *AOut = LA->getParent();
1033   OutputSection *BOut = LB->getParent();
1034   if (AOut != BOut)
1035     return AOut->SectionIndex < BOut->SectionIndex;
1036   return LA->OutSecOff < LB->OutSecOff;
1037 }
1038 
1039 template <class ELFT>
1040 static void finalizeShtGroup(OutputSection *OS,
1041                              ArrayRef<InputSection *> Sections) {
1042   assert(Config->Relocatable && Sections.size() == 1);
1043 
1044   // sh_link field for SHT_GROUP sections should contain the section index of
1045   // the symbol table.
1046   OS->Link = InX::SymTab->getParent()->SectionIndex;
1047 
1048   // sh_info then contain index of an entry in symbol table section which
1049   // provides signature of the section group.
1050   elf::ObjectFile<ELFT> *Obj = Sections[0]->getFile<ELFT>();
1051   ArrayRef<SymbolBody *> Symbols = Obj->getSymbols();
1052   OS->Info = InX::SymTab->getSymbolIndex(Symbols[Sections[0]->Info - 1]);
1053 }
1054 
1055 template <class ELFT> void OutputSectionCommand::finalize() {
1056   // Link order may be distributed across several InputSectionDescriptions
1057   // but sort must consider them all at once.
1058   std::vector<InputSection **> ScriptSections;
1059   std::vector<InputSection *> Sections;
1060   for (BaseCommand *Base : Commands)
1061     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1062       for (InputSection *&IS : ISD->Sections) {
1063         ScriptSections.push_back(&IS);
1064         Sections.push_back(IS);
1065       }
1066 
1067   if ((Sec->Flags & SHF_LINK_ORDER)) {
1068     std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
1069     for (int I = 0, N = Sections.size(); I < N; ++I)
1070       *ScriptSections[I] = Sections[I];
1071 
1072     // We must preserve the link order dependency of sections with the
1073     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
1074     // need to translate the InputSection sh_link to the OutputSection sh_link,
1075     // all InputSections in the OutputSection have the same dependency.
1076     if (auto *D = Sections.front()->getLinkOrderDep())
1077       Sec->Link = D->getParent()->SectionIndex;
1078   }
1079 
1080   uint32_t Type = Sec->Type;
1081   if (Type == SHT_GROUP) {
1082     finalizeShtGroup<ELFT>(Sec, Sections);
1083     return;
1084   }
1085 
1086   if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
1087     return;
1088 
1089   InputSection *First = Sections[0];
1090   if (isa<SyntheticSection>(First))
1091     return;
1092 
1093   Sec->Link = InX::SymTab->getParent()->SectionIndex;
1094   // sh_info for SHT_REL[A] sections should contain the section header index of
1095   // the section to which the relocation applies.
1096   InputSectionBase *S = First->getRelocatedSection();
1097   Sec->Info = S->getOutputSection()->SectionIndex;
1098   Sec->Flags |= SHF_INFO_LINK;
1099 }
1100 
1101 // Compress section contents if this section contains debug info.
1102 template <class ELFT> void OutputSectionCommand::maybeCompress() {
1103   typedef typename ELFT::Chdr Elf_Chdr;
1104 
1105   // Compress only DWARF debug sections.
1106   if (!Config->CompressDebugSections || (Sec->Flags & SHF_ALLOC) ||
1107       !Name.startswith(".debug_"))
1108     return;
1109 
1110   // Create a section header.
1111   Sec->ZDebugHeader.resize(sizeof(Elf_Chdr));
1112   auto *Hdr = reinterpret_cast<Elf_Chdr *>(Sec->ZDebugHeader.data());
1113   Hdr->ch_type = ELFCOMPRESS_ZLIB;
1114   Hdr->ch_size = Sec->Size;
1115   Hdr->ch_addralign = Sec->Alignment;
1116 
1117   // Write section contents to a temporary buffer and compress it.
1118   std::vector<uint8_t> Buf(Sec->Size);
1119   writeTo<ELFT>(Buf.data());
1120   if (Error E = zlib::compress(toStringRef(Buf), Sec->CompressedData))
1121     fatal("compress failed: " + llvm::toString(std::move(E)));
1122 
1123   // Update section headers.
1124   Sec->Size = sizeof(Elf_Chdr) + Sec->CompressedData.size();
1125   Sec->Flags |= SHF_COMPRESSED;
1126 }
1127 
1128 template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
1129   if (Sec->Type == SHT_NOBITS)
1130     return;
1131 
1132   Sec->Loc = Buf;
1133 
1134   // If -compress-debug-section is specified and if this is a debug seciton,
1135   // we've already compressed section contents. If that's the case,
1136   // just write it down.
1137   if (!Sec->CompressedData.empty()) {
1138     memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1139     memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1140            Sec->CompressedData.size());
1141     return;
1142   }
1143 
1144   // Write leading padding.
1145   std::vector<InputSection *> Sections;
1146   for (BaseCommand *Cmd : Commands)
1147     if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
1148       for (InputSection *IS : ISD->Sections)
1149         if (IS->Live)
1150           Sections.push_back(IS);
1151   uint32_t Filler = getFiller();
1152   if (Filler)
1153     fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1154 
1155   parallelForEachN(0, Sections.size(), [=](size_t I) {
1156     InputSection *IS = Sections[I];
1157     IS->writeTo<ELFT>(Buf);
1158 
1159     // Fill gaps between sections.
1160     if (Filler) {
1161       uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1162       uint8_t *End;
1163       if (I + 1 == Sections.size())
1164         End = Buf + Sec->Size;
1165       else
1166         End = Buf + Sections[I + 1]->OutSecOff;
1167       fill(Start, End - Start, Filler);
1168     }
1169   });
1170 
1171   // Linker scripts may have BYTE()-family commands with which you
1172   // can write arbitrary bytes to the output. Process them if any.
1173   for (BaseCommand *Base : Commands)
1174     if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1175       writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
1176 }
1177 
1178 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
1179   if (S == ".")
1180     return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr, Loc};
1181   if (SymbolBody *B = findSymbol(S)) {
1182     if (auto *D = dyn_cast<DefinedRegular>(B))
1183       return {D->Section, D->Value, Loc};
1184     if (auto *C = dyn_cast<DefinedCommon>(B))
1185       return {InX::Common, C->Offset, Loc};
1186   }
1187   error(Loc + ": symbol not found: " + S);
1188   return 0;
1189 }
1190 
1191 bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
1192 
1193 static const size_t NoPhdr = -1;
1194 
1195 // Returns indices of ELF headers containing specific section. Each index is a
1196 // zero based number of ELF header listed within PHDRS {} script block.
1197 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSectionCommand *Cmd) {
1198   std::vector<size_t> Ret;
1199   for (StringRef PhdrName : Cmd->Phdrs) {
1200     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
1201     if (Index != NoPhdr)
1202       Ret.push_back(Index);
1203   }
1204   return Ret;
1205 }
1206 
1207 // Returns the index of the segment named PhdrName if found otherwise
1208 // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
1209 // (which can be used to explicitly specify that a section isn't assigned to a
1210 // segment) then error.
1211 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
1212   size_t I = 0;
1213   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1214     if (Cmd.Name == PhdrName)
1215       return I;
1216     ++I;
1217   }
1218   if (PhdrName != "NONE")
1219     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1220   return NoPhdr;
1221 }
1222 
1223 template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1224 template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1225 template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1226 template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);
1227 
1228 template void OutputSectionCommand::maybeCompress<ELF32LE>();
1229 template void OutputSectionCommand::maybeCompress<ELF32BE>();
1230 template void OutputSectionCommand::maybeCompress<ELF64LE>();
1231 template void OutputSectionCommand::maybeCompress<ELF64BE>();
1232 
1233 template void OutputSectionCommand::finalize<ELF32LE>();
1234 template void OutputSectionCommand::finalize<ELF32BE>();
1235 template void OutputSectionCommand::finalize<ELF64LE>();
1236 template void OutputSectionCommand::finalize<ELF64BE>();
1237