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