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 // It parses a linker script and write the result to Config or ScriptConfig
12 // objects.
13 //
14 // If SECTIONS command is used, a ScriptConfig contains an AST
15 // of the command which will later be consumed by createSections() and
16 // assignAddresses().
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "LinkerScript.h"
21 #include "Config.h"
22 #include "Driver.h"
23 #include "InputSection.h"
24 #include "Memory.h"
25 #include "OutputSections.h"
26 #include "ScriptParser.h"
27 #include "Strings.h"
28 #include "SymbolTable.h"
29 #include "Symbols.h"
30 #include "Target.h"
31 #include "Writer.h"
32 #include "llvm/ADT/StringSwitch.h"
33 #include "llvm/Support/ELF.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 
38 using namespace llvm;
39 using namespace llvm::ELF;
40 using namespace llvm::object;
41 using namespace llvm::support::endian;
42 using namespace lld;
43 using namespace lld::elf;
44 
45 LinkerScriptBase *elf::ScriptBase;
46 ScriptConfiguration *elf::ScriptConfig;
47 
48 template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
49   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, nullptr,
51                                             STB_GLOBAL, STT_NOTYPE, 0);
52   Cmd->Sym = Sym->body();
53 
54   // If we have no SECTIONS then we don't have '.' and don't call
55   // assignAddresses(). We calculate symbol value immediately in this case.
56   if (!ScriptConfig->HasSections)
57     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
58 }
59 
60 template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
61   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
62       Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
63   Cmd->Sym = Sym->body();
64 }
65 
66 template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
67   if (Cmd->Expression.IsAbsolute())
68     addRegular<ELFT>(Cmd);
69   else
70     addSynthetic<ELFT>(Cmd);
71 }
72 // If a symbol was in PROVIDE(), we need to define it only when
73 // it is an undefined symbol.
74 template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
75   if (Cmd->Name == ".")
76     return false;
77   if (!Cmd->Provide)
78     return true;
79   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
80   return B && B->isUndefined();
81 }
82 
83 bool SymbolAssignment::classof(const BaseCommand *C) {
84   return C->Kind == AssignmentKind;
85 }
86 
87 bool OutputSectionCommand::classof(const BaseCommand *C) {
88   return C->Kind == OutputSectionKind;
89 }
90 
91 bool InputSectionDescription::classof(const BaseCommand *C) {
92   return C->Kind == InputSectionKind;
93 }
94 
95 bool AssertCommand::classof(const BaseCommand *C) {
96   return C->Kind == AssertKind;
97 }
98 
99 bool BytesDataCommand::classof(const BaseCommand *C) {
100   return C->Kind == BytesDataKind;
101 }
102 
103 template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
104   return !S || !S->Live;
105 }
106 
107 template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
108 template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
109 
110 template <class ELFT>
111 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
112   for (InputSectionDescription *ID : Opt.KeptSections) {
113     StringRef Filename = S->getFile()->getName();
114     if (!ID->FileRe.match(sys::path::filename(Filename)))
115       continue;
116 
117     for (SectionPattern &P : ID->SectionPatterns)
118       if (P.SectionRe.match(S->Name))
119         return true;
120   }
121   return false;
122 }
123 
124 static bool comparePriority(InputSectionData *A, InputSectionData *B) {
125   return getPriority(A->Name) < getPriority(B->Name);
126 }
127 
128 static bool compareName(InputSectionData *A, InputSectionData *B) {
129   return A->Name < B->Name;
130 }
131 
132 static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
133   // ">" is not a mistake. Larger alignments are placed before smaller
134   // alignments in order to reduce the amount of padding necessary.
135   // This is compatible with GNU.
136   return A->Alignment > B->Alignment;
137 }
138 
139 static std::function<bool(InputSectionData *, InputSectionData *)>
140 getComparator(SortSectionPolicy K) {
141   switch (K) {
142   case SortSectionPolicy::Alignment:
143     return compareAlignment;
144   case SortSectionPolicy::Name:
145     return compareName;
146   case SortSectionPolicy::Priority:
147     return comparePriority;
148   default:
149     llvm_unreachable("unknown sort policy");
150   }
151 }
152 
153 template <class ELFT>
154 static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
155                              ConstraintKind Kind) {
156   if (Kind == ConstraintKind::NoConstraint)
157     return true;
158   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
159     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
160     return Sec->Flags & SHF_WRITE;
161   });
162   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
163          (!IsRW && Kind == ConstraintKind::ReadOnly);
164 }
165 
166 static void sortSections(InputSectionData **Begin, InputSectionData **End,
167                          SortSectionPolicy K) {
168   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
169     std::stable_sort(Begin, End, getComparator(K));
170 }
171 
172 // Compute and remember which sections the InputSectionDescription matches.
173 template <class ELFT>
174 void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
175   // Collects all sections that satisfy constraints of I
176   // and attach them to I.
177   for (SectionPattern &Pat : I->SectionPatterns) {
178     size_t SizeBefore = I->Sections.size();
179     for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
180       StringRef Filename = sys::path::filename(F->getName());
181       if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
182         continue;
183 
184       for (InputSectionBase<ELFT> *S : F->getSections())
185         if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
186           I->Sections.push_back(S);
187       if (Pat.SectionRe.match("COMMON"))
188         I->Sections.push_back(InputSection<ELFT>::CommonInputSection);
189     }
190 
191     // Sort sections as instructed by SORT-family commands and --sort-section
192     // option. Because SORT-family commands can be nested at most two depth
193     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
194     // line option is respected even if a SORT command is given, the exact
195     // behavior we have here is a bit complicated. Here are the rules.
196     //
197     // 1. If two SORT commands are given, --sort-section is ignored.
198     // 2. If one SORT command is given, and if it is not SORT_NONE,
199     //    --sort-section is handled as an inner SORT command.
200     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
201     // 4. If no SORT command is given, sort according to --sort-section.
202     InputSectionData **Begin = I->Sections.data() + SizeBefore;
203     InputSectionData **End = I->Sections.data() + I->Sections.size();
204     if (Pat.SortOuter != SortSectionPolicy::None) {
205       if (Pat.SortInner == SortSectionPolicy::Default)
206         sortSections(Begin, End, Config->SortSection);
207       else
208         sortSections(Begin, End, Pat.SortInner);
209       sortSections(Begin, End, Pat.SortOuter);
210     }
211   }
212 
213   // We do not add duplicate input sections, so mark them with a dummy output
214   // section for now.
215   for (InputSectionData *S : I->Sections) {
216     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
217     S2->OutSec = (OutputSectionBase<ELFT> *)-1;
218   }
219 }
220 
221 template <class ELFT>
222 void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
223   for (InputSectionBase<ELFT> *S : V) {
224     S->Live = false;
225     reportDiscarded(S);
226   }
227 }
228 
229 template <class ELFT>
230 std::vector<InputSectionBase<ELFT> *>
231 LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
232   std::vector<InputSectionBase<ELFT> *> Ret;
233 
234   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
235     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
236     if (!Cmd)
237       continue;
238     computeInputSections(Cmd);
239     for (InputSectionData *S : Cmd->Sections)
240       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
241   }
242 
243   // After we created final list we should now set OutSec pointer to null,
244   // instead of -1. Otherwise we may get a crash when writing relocs, in
245   // case section is discarded by linker script
246   for (InputSectionBase<ELFT> *S : Ret)
247     S->OutSec = nullptr;
248 
249   return Ret;
250 }
251 
252 template <class ELFT>
253 static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
254                                             StringRef OutsecName) {
255   // When using linker script the merge rules are different.
256   // Unfortunately, linker scripts are name based. This means that expressions
257   // like *(.foo*) can refer to multiple input sections that would normally be
258   // placed in different output sections. We cannot put them in different
259   // output sections or we would produce wrong results for
260   // start = .; *(.foo.*) end = .; *(.bar)
261   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
262   // another. The problem is that there is no way to layout those output
263   // sections such that the .foo sections are the only thing between the
264   // start and end symbols.
265 
266   // An extra annoyance is that we cannot simply disable merging of the contents
267   // of SHF_MERGE sections, but our implementation requires one output section
268   // per "kind" (string or not, which size/aligment).
269   // Fortunately, creating symbols in the middle of a merge section is not
270   // supported by bfd or gold, so we can just create multiple section in that
271   // case.
272   typedef typename ELFT::uint uintX_t;
273   uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
274 
275   uintX_t Alignment = 0;
276   if (isa<MergeInputSection<ELFT>>(C))
277     Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
278 
279   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
280 }
281 
282 template <class ELFT>
283 void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
284                                     InputSectionBase<ELFT> *Sec,
285                                     StringRef Name) {
286   OutputSectionBase<ELFT> *OutSec;
287   bool IsNew;
288   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
289   if (IsNew)
290     OutputSections->push_back(OutSec);
291   OutSec->addSection(Sec);
292 }
293 
294 template <class ELFT>
295 void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
296 
297   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
298     auto Iter = Opt.Commands.begin() + I;
299     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
300     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
301       if (shouldDefine<ELFT>(Cmd))
302         addSymbol<ELFT>(Cmd);
303       continue;
304     }
305     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
306       // If we don't have SECTIONS then output sections have already been
307       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
308       // will not be called, so ASSERT should be evaluated now.
309       if (!Opt.HasSections)
310         Cmd->Expression(0);
311       continue;
312     }
313 
314     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
315       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
316 
317       if (Cmd->Name == "/DISCARD/") {
318         discard(V);
319         continue;
320       }
321 
322       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
323         for (InputSectionBase<ELFT> *S : V)
324           S->OutSec = nullptr;
325         Opt.Commands.erase(Iter);
326         --I;
327         continue;
328       }
329 
330       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
331         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
332           if (shouldDefine<ELFT>(OutCmd))
333             addSymbol<ELFT>(OutCmd);
334 
335       if (V.empty())
336         continue;
337 
338       for (InputSectionBase<ELFT> *Sec : V) {
339         addSection(Factory, Sec, Cmd->Name);
340         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
341           Sec->Alignment = Subalign;
342       }
343     }
344   }
345 }
346 
347 template <class ELFT>
348 void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
349   processCommands(Factory);
350   // Add orphan sections.
351   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
352     for (InputSectionBase<ELFT> *S : F->getSections())
353       if (!isDiscarded(S) && !S->OutSec)
354         addSection(Factory, S, getOutputSectionName(S->Name));
355 }
356 
357 // Sets value of a section-defined symbol. Two kinds of
358 // symbols are processed: synthetic symbols, whose value
359 // is an offset from beginning of section and regular
360 // symbols whose value is absolute.
361 template <class ELFT>
362 static void assignSectionSymbol(SymbolAssignment *Cmd,
363                                 OutputSectionBase<ELFT> *Sec,
364                                 typename ELFT::uint Value) {
365   if (!Cmd->Sym)
366     return;
367 
368   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
369     Body->Section = Sec;
370     Body->Value = Cmd->Expression(Value) - Sec->getVA();
371     return;
372   }
373   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
374   Body->Value = Cmd->Expression(Value);
375 }
376 
377 template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
378   return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
379 }
380 
381 template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
382   if (!AlreadyOutputIS.insert(S).second)
383     return;
384   bool IsTbss = isTbss(CurOutSec);
385 
386   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
387   Pos = alignTo(Pos, S->Alignment);
388   S->OutSecOff = Pos - CurOutSec->getVA();
389   Pos += S->getSize();
390 
391   // Update output section size after adding each section. This is so that
392   // SIZEOF works correctly in the case below:
393   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
394   CurOutSec->setSize(Pos - CurOutSec->getVA());
395 
396   if (IsTbss)
397     ThreadBssOffset = Pos - Dot;
398   else
399     Dot = Pos;
400 }
401 
402 template <class ELFT> void LinkerScript<ELFT>::flush() {
403   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
404     return;
405   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
406     for (InputSection<ELFT> *I : OutSec->Sections)
407       output(I);
408   } else {
409     Dot += CurOutSec->getSize();
410   }
411 }
412 
413 template <class ELFT>
414 void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
415   if (CurOutSec == Sec)
416     return;
417   if (AlreadyOutputOS.count(Sec))
418     return;
419 
420   flush();
421   CurOutSec = Sec;
422 
423   Dot = alignTo(Dot, CurOutSec->getAlignment());
424   CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
425 
426   // If neither AT nor AT> is specified for an allocatable section, the linker
427   // will set the LMA such that the difference between VMA and LMA for the
428   // section is the same as the preceding output section in the same region
429   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
430   CurOutSec->setLMAOffset(LMAOffset);
431 }
432 
433 template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
434   // This handles the assignments to symbol or to a location counter (.)
435   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
436     if (AssignCmd->Name == ".") {
437       // Update to location counter means update to section size.
438       Dot = AssignCmd->Expression(Dot);
439       CurOutSec->setSize(Dot - CurOutSec->getVA());
440       return;
441     }
442     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
443     return;
444   }
445 
446   // Handle BYTE(), SHORT(), LONG(), or QUAD().
447   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
448     DataCmd->Offset = Dot - CurOutSec->getVA();
449     Dot += DataCmd->Size;
450     CurOutSec->setSize(Dot - CurOutSec->getVA());
451     return;
452   }
453 
454   // It handles single input section description command,
455   // calculates and assigns the offsets for each section and also
456   // updates the output section size.
457   auto &ICmd = cast<InputSectionDescription>(Base);
458   for (InputSectionData *ID : ICmd.Sections) {
459     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
460     switchTo(IB->OutSec);
461     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
462       output(I);
463     else
464       flush();
465   }
466 }
467 
468 template <class ELFT>
469 static std::vector<OutputSectionBase<ELFT> *>
470 findSections(StringRef Name,
471              const std::vector<OutputSectionBase<ELFT> *> &Sections) {
472   std::vector<OutputSectionBase<ELFT> *> Ret;
473   for (OutputSectionBase<ELFT> *Sec : Sections)
474     if (Sec->getName() == Name)
475       Ret.push_back(Sec);
476   return Ret;
477 }
478 
479 template <class ELFT>
480 void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
481   if (Cmd->LMAExpr)
482     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
483   std::vector<OutputSectionBase<ELFT> *> Sections =
484       findSections(Cmd->Name, *OutputSections);
485   if (Sections.empty())
486     return;
487   switchTo(Sections[0]);
488   // Find the last section output location. We will output orphan sections
489   // there so that end symbols point to the correct location.
490   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
491                         [](const std::unique_ptr<BaseCommand> &Cmd) {
492                           return !isa<SymbolAssignment>(*Cmd);
493                         })
494                .base();
495   for (auto I = Cmd->Commands.begin(); I != E; ++I)
496     process(**I);
497   for (OutputSectionBase<ELFT> *Base : Sections)
498     switchTo(Base);
499   flush();
500   std::for_each(E, Cmd->Commands.end(),
501                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
502 }
503 
504 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
505   // It is common practice to use very generic linker scripts. So for any
506   // given run some of the output sections in the script will be empty.
507   // We could create corresponding empty output sections, but that would
508   // clutter the output.
509   // We instead remove trivially empty sections. The bfd linker seems even
510   // more aggressive at removing them.
511   auto Pos = std::remove_if(
512       Opt.Commands.begin(), Opt.Commands.end(),
513       [&](const std::unique_ptr<BaseCommand> &Base) {
514         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
515         if (!Cmd)
516           return false;
517         std::vector<OutputSectionBase<ELFT> *> Secs =
518             findSections(Cmd->Name, *OutputSections);
519         if (!Secs.empty())
520           return false;
521         for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
522           if (!isa<InputSectionDescription>(I.get()))
523             return false;
524         return true;
525       });
526   Opt.Commands.erase(Pos, Opt.Commands.end());
527 
528   // If the output section contains only symbol assignments, create a
529   // corresponding output section. The bfd linker seems to only create them if
530   // '.' is assigned to, but creating these section should not have any bad
531   // consequeces and gives us a section to put the symbol in.
532   uintX_t Flags = SHF_ALLOC;
533   uint32_t Type = 0;
534   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
535     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
536     if (!Cmd)
537       continue;
538     std::vector<OutputSectionBase<ELFT> *> Secs =
539         findSections(Cmd->Name, *OutputSections);
540     if (!Secs.empty()) {
541       Flags = Secs[0]->getFlags();
542       Type = Secs[0]->getType();
543       continue;
544     }
545 
546     auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
547     Out<ELFT>::Pool.emplace_back(OutSec);
548     OutputSections->push_back(OutSec);
549   }
550 }
551 
552 // When placing orphan sections, we want to place them after symbol assignments
553 // so that an orphan after
554 //   begin_foo = .;
555 //   foo : { *(foo) }
556 //   end_foo = .;
557 // doesn't break the intended meaning of the begin/end symbols.
558 // We don't want to go over sections since Writer<ELFT>::sortSections is the
559 // one in charge of deciding the order of the sections.
560 // We don't want to go over alignments, since doing so in
561 //  rx_sec : { *(rx_sec) }
562 //  . = ALIGN(0x1000);
563 //  /* The RW PT_LOAD starts here*/
564 //  rw_sec : { *(rw_sec) }
565 // would mean that the RW PT_LOAD would become unaligned.
566 static bool shouldSkip(const BaseCommand &Cmd) {
567   if (isa<OutputSectionCommand>(Cmd))
568     return false;
569   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
570   if (!Assign)
571     return true;
572   return Assign->Name != ".";
573 }
574 
575 template <class ELFT>
576 void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
577   // Orphan sections are sections present in the input files which
578   // are not explicitly placed into the output file by the linker script.
579   // We place orphan sections at end of file.
580   // Other linkers places them using some heuristics as described in
581   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
582 
583   // The OutputSections are already in the correct order.
584   // This loops creates or moves commands as needed so that they are in the
585   // correct order.
586   int CmdIndex = 0;
587   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
588     StringRef Name = Sec->getName();
589 
590     // Find the last spot where we can insert a command and still get the
591     // correct result.
592     auto CmdIter = Opt.Commands.begin() + CmdIndex;
593     auto E = Opt.Commands.end();
594     while (CmdIter != E && shouldSkip(**CmdIter)) {
595       ++CmdIter;
596       ++CmdIndex;
597     }
598 
599     auto Pos =
600         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
601           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
602           return Cmd && Cmd->Name == Name;
603         });
604     if (Pos == E) {
605       Opt.Commands.insert(CmdIter,
606                           llvm::make_unique<OutputSectionCommand>(Name));
607       ++CmdIndex;
608       continue;
609     }
610 
611     // Continue from where we found it.
612     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
613     continue;
614   }
615 
616   // Assign addresses as instructed by linker script SECTIONS sub-commands.
617   Dot = 0;
618 
619   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
620     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
621       if (Cmd->Name == ".") {
622         Dot = Cmd->Expression(Dot);
623       } else if (Cmd->Sym) {
624         assignSectionSymbol(Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0],
625                             Dot);
626       }
627       continue;
628     }
629 
630     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
631       Cmd->Expression(Dot);
632       continue;
633     }
634 
635     auto *Cmd = cast<OutputSectionCommand>(Base.get());
636 
637     if (Cmd->AddrExpr)
638       Dot = Cmd->AddrExpr(Dot);
639 
640     assignOffsets(Cmd);
641   }
642 
643   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
644   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
645     if (Sec->getFlags() & SHF_ALLOC)
646       MinVA = std::min(MinVA, Sec->getVA());
647     else
648       Sec->setVA(0);
649   }
650 
651   uintX_t HeaderSize = getHeaderSize();
652   auto FirstPTLoad =
653       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
654         return E.H.p_type == PT_LOAD;
655       });
656 
657   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
658     // If linker script specifies program headers and first PT_LOAD doesn't
659     // have both PHDRS and FILEHDR attributes then do nothing
660     if (!Opt.PhdrsCommands.empty()) {
661       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
662       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
663           !Opt.PhdrsCommands[SegNum].HasFilehdr)
664         return;
665     }
666     // ELF and Program headers need to be right before the first section in
667     // memory. Set their addresses accordingly.
668     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
669     Out<ELFT>::ElfHeader->setVA(MinVA);
670     Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
671     FirstPTLoad->First = Out<ELFT>::ElfHeader;
672     if (!FirstPTLoad->Last)
673       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
674   } else if (!FirstPTLoad->First) {
675     // Sometimes the very first PT_LOAD segment can be empty.
676     // This happens if (all conditions met):
677     //  - Linker script is used
678     //  - First section in ELF image is not RO
679     //  - Not enough space for program headers.
680     // The code below removes empty PT_LOAD segment and updates
681     // program headers size.
682     Phdrs.erase(FirstPTLoad);
683     Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
684                                        Phdrs.size());
685   }
686 }
687 
688 // Creates program headers as instructed by PHDRS linker script command.
689 template <class ELFT>
690 std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
691   std::vector<PhdrEntry<ELFT>> Ret;
692 
693   // Process PHDRS and FILEHDR keywords because they are not
694   // real output sections and cannot be added in the following loop.
695   std::vector<size_t> DefPhdrIds;
696   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
697     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
698     PhdrEntry<ELFT> &Phdr = Ret.back();
699 
700     if (Cmd.HasFilehdr)
701       Phdr.add(Out<ELFT>::ElfHeader);
702     if (Cmd.HasPhdrs)
703       Phdr.add(Out<ELFT>::ProgramHeaders);
704 
705     if (Cmd.LMAExpr) {
706       Phdr.H.p_paddr = Cmd.LMAExpr(0);
707       Phdr.HasLMA = true;
708     }
709 
710     // If output section command doesn't specify any segments,
711     // and we haven't previously assigned any section to segment,
712     // then we simply assign section to the very first load segment.
713     // Below is an example of such linker script:
714     // PHDRS { seg PT_LOAD; }
715     // SECTIONS { .aaa : { *(.aaa) } }
716     if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
717       DefPhdrIds.push_back(Ret.size() - 1);
718   }
719 
720   // Add output sections to program headers.
721   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
722     if (!(Sec->getFlags() & SHF_ALLOC))
723       break;
724 
725     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
726     if (PhdrIds.empty())
727       PhdrIds = std::move(DefPhdrIds);
728 
729     // Assign headers specified by linker script
730     for (size_t Id : PhdrIds) {
731       Ret[Id].add(Sec);
732       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
733         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
734     }
735     DefPhdrIds = std::move(PhdrIds);
736   }
737   return Ret;
738 }
739 
740 template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
741   // Ignore .interp section in case we have PHDRS specification
742   // and PT_INTERP isn't listed.
743   return !Opt.PhdrsCommands.empty() &&
744          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
745            return Cmd.Type == PT_INTERP;
746          }) == Opt.PhdrsCommands.end();
747 }
748 
749 template <class ELFT>
750 ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
751   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
752     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
753       if (Cmd->Name == Name)
754         return Cmd->Filler;
755   return {};
756 }
757 
758 template <class ELFT>
759 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
760   const endianness E = ELFT::TargetEndianness;
761 
762   switch (Size) {
763   case 1:
764     *Buf = (uint8_t)Data;
765     break;
766   case 2:
767     write16<E>(Buf, Data);
768     break;
769   case 4:
770     write32<E>(Buf, Data);
771     break;
772   case 8:
773     write64<E>(Buf, Data);
774     break;
775   default:
776     llvm_unreachable("unsupported Size argument");
777   }
778 }
779 
780 template <class ELFT>
781 void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
782   int I = getSectionIndex(Name);
783   if (I == INT_MAX)
784     return;
785 
786   OutputSectionCommand *Cmd =
787       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
788   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
789     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
790       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
791 }
792 
793 template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
794   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
795     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
796       if (Cmd->LMAExpr && Cmd->Name == Name)
797         return true;
798   return false;
799 }
800 
801 // Returns the index of the given section name in linker script
802 // SECTIONS commands. Sections are laid out as the same order as they
803 // were in the script. If a given name did not appear in the script,
804 // it returns INT_MAX, so that it will be laid out at end of file.
805 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
806   int I = 0;
807   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
808     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
809       if (Cmd->Name == Name)
810         return I;
811     ++I;
812   }
813   return INT_MAX;
814 }
815 
816 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
817   return !Opt.PhdrsCommands.empty();
818 }
819 
820 template <class ELFT>
821 uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
822   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
823     if (Sec->getName() == Name)
824       return Sec->getVA();
825   error("undefined section " + Name);
826   return 0;
827 }
828 
829 template <class ELFT>
830 uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
831   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
832     if (Sec->getName() == Name)
833       return Sec->getLMA();
834   error("undefined section " + Name);
835   return 0;
836 }
837 
838 template <class ELFT>
839 uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
840   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
841     if (Sec->getName() == Name)
842       return Sec->getSize();
843   error("undefined section " + Name);
844   return 0;
845 }
846 
847 template <class ELFT>
848 uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
849   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
850     if (Sec->getName() == Name)
851       return Sec->getAlignment();
852   error("undefined section " + Name);
853   return 0;
854 }
855 
856 template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
857   return elf::getHeaderSize<ELFT>();
858 }
859 
860 template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
861   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
862     return B->getVA<ELFT>();
863   error("symbol not found: " + S);
864   return 0;
865 }
866 
867 template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
868   return Symtab<ELFT>::X->find(S) != nullptr;
869 }
870 
871 template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
872   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
873   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
874   return DR && !DR->Section;
875 }
876 
877 // Returns indices of ELF headers containing specific section, identified
878 // by Name. Each index is a zero based number of ELF header listed within
879 // PHDRS {} script block.
880 template <class ELFT>
881 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
882   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
883     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
884     if (!Cmd || Cmd->Name != SectionName)
885       continue;
886 
887     std::vector<size_t> Ret;
888     for (StringRef PhdrName : Cmd->Phdrs)
889       Ret.push_back(getPhdrIndex(PhdrName));
890     return Ret;
891   }
892   return {};
893 }
894 
895 template <class ELFT>
896 size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
897   size_t I = 0;
898   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
899     if (Cmd.Name == PhdrName)
900       return I;
901     ++I;
902   }
903   error("section header '" + PhdrName + "' is not listed in PHDRS");
904   return 0;
905 }
906 
907 class elf::ScriptParser : public ScriptParserBase {
908   typedef void (ScriptParser::*Handler)();
909 
910 public:
911   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
912 
913   void readLinkerScript();
914   void readVersionScript();
915 
916 private:
917   void addFile(StringRef Path);
918 
919   void readAsNeeded();
920   void readEntry();
921   void readExtern();
922   void readGroup();
923   void readInclude();
924   void readOutput();
925   void readOutputArch();
926   void readOutputFormat();
927   void readPhdrs();
928   void readSearchDir();
929   void readSections();
930   void readVersion();
931   void readVersionScriptCommand();
932 
933   SymbolAssignment *readAssignment(StringRef Name);
934   BytesDataCommand *readBytesDataCommand(StringRef Tok);
935   std::vector<uint8_t> readFill();
936   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
937   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
938   std::vector<StringRef> readOutputSectionPhdrs();
939   InputSectionDescription *readInputSectionDescription(StringRef Tok);
940   Regex readFilePatterns();
941   std::vector<SectionPattern> readInputSectionsList();
942   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
943   unsigned readPhdrType();
944   SortSectionPolicy readSortKind();
945   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
946   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
947   void readSort();
948   Expr readAssert();
949 
950   Expr readExpr();
951   Expr readExpr1(Expr Lhs, int MinPrec);
952   StringRef readParenLiteral();
953   Expr readPrimary();
954   Expr readTernary(Expr Cond);
955   Expr readParenExpr();
956 
957   // For parsing version script.
958   void readExtern(std::vector<SymbolVersion> *Globals);
959   void readVersionDeclaration(StringRef VerStr);
960   void readGlobal(StringRef VerStr);
961   void readLocal();
962 
963   ScriptConfiguration &Opt = *ScriptConfig;
964   bool IsUnderSysroot;
965 };
966 
967 void ScriptParser::readVersionScript() {
968   readVersionScriptCommand();
969   if (!atEOF())
970     setError("EOF expected, but got " + next());
971 }
972 
973 void ScriptParser::readVersionScriptCommand() {
974   if (consume("{")) {
975     readVersionDeclaration("");
976     return;
977   }
978 
979   while (!atEOF() && !Error && peek() != "}") {
980     StringRef VerStr = next();
981     if (VerStr == "{") {
982       setError("anonymous version definition is used in "
983                "combination with other version definitions");
984       return;
985     }
986     expect("{");
987     readVersionDeclaration(VerStr);
988   }
989 }
990 
991 void ScriptParser::readVersion() {
992   expect("{");
993   readVersionScriptCommand();
994   expect("}");
995 }
996 
997 void ScriptParser::readLinkerScript() {
998   while (!atEOF()) {
999     StringRef Tok = next();
1000     if (Tok == ";")
1001       continue;
1002 
1003     if (Tok == "ASSERT") {
1004       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1005     } else if (Tok == "ENTRY") {
1006       readEntry();
1007     } else if (Tok == "EXTERN") {
1008       readExtern();
1009     } else if (Tok == "GROUP" || Tok == "INPUT") {
1010       readGroup();
1011     } else if (Tok == "INCLUDE") {
1012       readInclude();
1013     } else if (Tok == "OUTPUT") {
1014       readOutput();
1015     } else if (Tok == "OUTPUT_ARCH") {
1016       readOutputArch();
1017     } else if (Tok == "OUTPUT_FORMAT") {
1018       readOutputFormat();
1019     } else if (Tok == "PHDRS") {
1020       readPhdrs();
1021     } else if (Tok == "SEARCH_DIR") {
1022       readSearchDir();
1023     } else if (Tok == "SECTIONS") {
1024       readSections();
1025     } else if (Tok == "VERSION") {
1026       readVersion();
1027     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
1028       Opt.Commands.emplace_back(Cmd);
1029     } else {
1030       setError("unknown directive: " + Tok);
1031     }
1032   }
1033 }
1034 
1035 void ScriptParser::addFile(StringRef S) {
1036   if (IsUnderSysroot && S.startswith("/")) {
1037     SmallString<128> PathData;
1038     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
1039     if (sys::fs::exists(Path)) {
1040       Driver->addFile(Saver.save(Path));
1041       return;
1042     }
1043   }
1044 
1045   if (sys::path::is_absolute(S)) {
1046     Driver->addFile(S);
1047   } else if (S.startswith("=")) {
1048     if (Config->Sysroot.empty())
1049       Driver->addFile(S.substr(1));
1050     else
1051       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1052   } else if (S.startswith("-l")) {
1053     Driver->addLibrary(S.substr(2));
1054   } else if (sys::fs::exists(S)) {
1055     Driver->addFile(S);
1056   } else {
1057     std::string Path = findFromSearchPaths(S);
1058     if (Path.empty())
1059       setError("unable to find " + S);
1060     else
1061       Driver->addFile(Saver.save(Path));
1062   }
1063 }
1064 
1065 void ScriptParser::readAsNeeded() {
1066   expect("(");
1067   bool Orig = Config->AsNeeded;
1068   Config->AsNeeded = true;
1069   while (!Error && !consume(")"))
1070     addFile(unquote(next()));
1071   Config->AsNeeded = Orig;
1072 }
1073 
1074 void ScriptParser::readEntry() {
1075   // -e <symbol> takes predecence over ENTRY(<symbol>).
1076   expect("(");
1077   StringRef Tok = next();
1078   if (Config->Entry.empty())
1079     Config->Entry = Tok;
1080   expect(")");
1081 }
1082 
1083 void ScriptParser::readExtern() {
1084   expect("(");
1085   while (!Error && !consume(")"))
1086     Config->Undefined.push_back(next());
1087 }
1088 
1089 void ScriptParser::readGroup() {
1090   expect("(");
1091   while (!Error && !consume(")")) {
1092     StringRef Tok = next();
1093     if (Tok == "AS_NEEDED")
1094       readAsNeeded();
1095     else
1096       addFile(unquote(Tok));
1097   }
1098 }
1099 
1100 void ScriptParser::readInclude() {
1101   StringRef Tok = next();
1102   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1103   if (!MBOrErr) {
1104     setError("cannot open " + Tok);
1105     return;
1106   }
1107   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1108   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1109   std::vector<StringRef> V = tokenize(S);
1110   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
1111 }
1112 
1113 void ScriptParser::readOutput() {
1114   // -o <file> takes predecence over OUTPUT(<file>).
1115   expect("(");
1116   StringRef Tok = next();
1117   if (Config->OutputFile.empty())
1118     Config->OutputFile = unquote(Tok);
1119   expect(")");
1120 }
1121 
1122 void ScriptParser::readOutputArch() {
1123   // Error checking only for now.
1124   expect("(");
1125   skip();
1126   expect(")");
1127 }
1128 
1129 void ScriptParser::readOutputFormat() {
1130   // Error checking only for now.
1131   expect("(");
1132   skip();
1133   StringRef Tok = next();
1134   if (Tok == ")")
1135     return;
1136   if (Tok != ",") {
1137     setError("unexpected token: " + Tok);
1138     return;
1139   }
1140   skip();
1141   expect(",");
1142   skip();
1143   expect(")");
1144 }
1145 
1146 void ScriptParser::readPhdrs() {
1147   expect("{");
1148   while (!Error && !consume("}")) {
1149     StringRef Tok = next();
1150     Opt.PhdrsCommands.push_back(
1151         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1152     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1153 
1154     PhdrCmd.Type = readPhdrType();
1155     do {
1156       Tok = next();
1157       if (Tok == ";")
1158         break;
1159       if (Tok == "FILEHDR")
1160         PhdrCmd.HasFilehdr = true;
1161       else if (Tok == "PHDRS")
1162         PhdrCmd.HasPhdrs = true;
1163       else if (Tok == "AT")
1164         PhdrCmd.LMAExpr = readParenExpr();
1165       else if (Tok == "FLAGS") {
1166         expect("(");
1167         // Passing 0 for the value of dot is a bit of a hack. It means that
1168         // we accept expressions like ".|1".
1169         PhdrCmd.Flags = readExpr()(0);
1170         expect(")");
1171       } else
1172         setError("unexpected header attribute: " + Tok);
1173     } while (!Error);
1174   }
1175 }
1176 
1177 void ScriptParser::readSearchDir() {
1178   expect("(");
1179   StringRef Tok = next();
1180   if (!Config->Nostdlib)
1181     Config->SearchPaths.push_back(unquote(Tok));
1182   expect(")");
1183 }
1184 
1185 void ScriptParser::readSections() {
1186   Opt.HasSections = true;
1187   expect("{");
1188   while (!Error && !consume("}")) {
1189     StringRef Tok = next();
1190     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1191     if (!Cmd) {
1192       if (Tok == "ASSERT")
1193         Cmd = new AssertCommand(readAssert());
1194       else
1195         Cmd = readOutputSectionDescription(Tok);
1196     }
1197     Opt.Commands.emplace_back(Cmd);
1198   }
1199 }
1200 
1201 static int precedence(StringRef Op) {
1202   return StringSwitch<int>(Op)
1203       .Cases("*", "/", 5)
1204       .Cases("+", "-", 4)
1205       .Cases("<<", ">>", 3)
1206       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
1207       .Cases("&", "|", 1)
1208       .Default(-1);
1209 }
1210 
1211 Regex ScriptParser::readFilePatterns() {
1212   std::vector<StringRef> V;
1213   while (!Error && !consume(")"))
1214     V.push_back(next());
1215   return compileGlobPatterns(V);
1216 }
1217 
1218 SortSectionPolicy ScriptParser::readSortKind() {
1219   if (consume("SORT") || consume("SORT_BY_NAME"))
1220     return SortSectionPolicy::Name;
1221   if (consume("SORT_BY_ALIGNMENT"))
1222     return SortSectionPolicy::Alignment;
1223   if (consume("SORT_BY_INIT_PRIORITY"))
1224     return SortSectionPolicy::Priority;
1225   if (consume("SORT_NONE"))
1226     return SortSectionPolicy::None;
1227   return SortSectionPolicy::Default;
1228 }
1229 
1230 // Method reads a list of sequence of excluded files and section globs given in
1231 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1232 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1233 // The semantics of that is next:
1234 // * Include .foo.1 from every file.
1235 // * Include .foo.2 from every file but a.o
1236 // * Include .foo.3 from every file but b.o
1237 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1238   std::vector<SectionPattern> Ret;
1239   while (!Error && peek() != ")") {
1240     Regex ExcludeFileRe;
1241     if (consume("EXCLUDE_FILE")) {
1242       expect("(");
1243       ExcludeFileRe = readFilePatterns();
1244     }
1245 
1246     std::vector<StringRef> V;
1247     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1248       V.push_back(next());
1249 
1250     if (!V.empty())
1251       Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
1252     else
1253       setError("section pattern is expected");
1254   }
1255   return Ret;
1256 }
1257 
1258 // Section pattern grammar can have complex expressions, for example:
1259 // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1260 // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1261 // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1262 // This methods handles wrapping sequences of excluded files and section globs
1263 // into SORT() if that needed and reads them all.
1264 InputSectionDescription *
1265 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1266   auto *Cmd = new InputSectionDescription(FilePattern);
1267   expect("(");
1268   while (!HasError && !consume(")")) {
1269     SortSectionPolicy Outer = readSortKind();
1270     SortSectionPolicy Inner = SortSectionPolicy::Default;
1271     std::vector<SectionPattern> V;
1272     if (Outer != SortSectionPolicy::Default) {
1273       expect("(");
1274       Inner = readSortKind();
1275       if (Inner != SortSectionPolicy::Default) {
1276         expect("(");
1277         V = readInputSectionsList();
1278         expect(")");
1279       } else {
1280         V = readInputSectionsList();
1281       }
1282       expect(")");
1283     } else {
1284       V = readInputSectionsList();
1285     }
1286 
1287     for (SectionPattern &Pat : V) {
1288       Pat.SortInner = Inner;
1289       Pat.SortOuter = Outer;
1290     }
1291 
1292     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1293   }
1294   return Cmd;
1295 }
1296 
1297 InputSectionDescription *
1298 ScriptParser::readInputSectionDescription(StringRef Tok) {
1299   // Input section wildcard can be surrounded by KEEP.
1300   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1301   if (Tok == "KEEP") {
1302     expect("(");
1303     StringRef FilePattern = next();
1304     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1305     expect(")");
1306     Opt.KeptSections.push_back(Cmd);
1307     return Cmd;
1308   }
1309   return readInputSectionRules(Tok);
1310 }
1311 
1312 void ScriptParser::readSort() {
1313   expect("(");
1314   expect("CONSTRUCTORS");
1315   expect(")");
1316 }
1317 
1318 Expr ScriptParser::readAssert() {
1319   expect("(");
1320   Expr E = readExpr();
1321   expect(",");
1322   StringRef Msg = unquote(next());
1323   expect(")");
1324   return [=](uint64_t Dot) {
1325     uint64_t V = E(Dot);
1326     if (!V)
1327       error(Msg);
1328     return V;
1329   };
1330 }
1331 
1332 // Reads a FILL(expr) command. We handle the FILL command as an
1333 // alias for =fillexp section attribute, which is different from
1334 // what GNU linkers do.
1335 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1336 std::vector<uint8_t> ScriptParser::readFill() {
1337   expect("(");
1338   std::vector<uint8_t> V = readOutputSectionFiller(next());
1339   expect(")");
1340   expect(";");
1341   return V;
1342 }
1343 
1344 OutputSectionCommand *
1345 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1346   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1347 
1348   // Read an address expression.
1349   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1350   if (peek() != ":")
1351     Cmd->AddrExpr = readExpr();
1352 
1353   expect(":");
1354 
1355   if (consume("AT"))
1356     Cmd->LMAExpr = readParenExpr();
1357   if (consume("ALIGN"))
1358     Cmd->AlignExpr = readParenExpr();
1359   if (consume("SUBALIGN"))
1360     Cmd->SubalignExpr = readParenExpr();
1361 
1362   // Parse constraints.
1363   if (consume("ONLY_IF_RO"))
1364     Cmd->Constraint = ConstraintKind::ReadOnly;
1365   if (consume("ONLY_IF_RW"))
1366     Cmd->Constraint = ConstraintKind::ReadWrite;
1367   expect("{");
1368 
1369   while (!Error && !consume("}")) {
1370     StringRef Tok = next();
1371     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1372       Cmd->Commands.emplace_back(Assignment);
1373     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1374       Cmd->Commands.emplace_back(Data);
1375     else if (Tok == "FILL")
1376       Cmd->Filler = readFill();
1377     else if (Tok == "SORT")
1378       readSort();
1379     else if (peek() == "(")
1380       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1381     else
1382       setError("unknown command " + Tok);
1383   }
1384   Cmd->Phdrs = readOutputSectionPhdrs();
1385 
1386   if (consume("="))
1387     Cmd->Filler = readOutputSectionFiller(next());
1388   else if (peek().startswith("="))
1389     Cmd->Filler = readOutputSectionFiller(next().drop_front());
1390 
1391   return Cmd;
1392 }
1393 
1394 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1395 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1396 //
1397 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1398 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1399 // as 32-bit big-endian values. We will do the same as ld.gold does
1400 // because it's simpler than what ld.bfd does.
1401 std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1402   uint32_t V;
1403   if (Tok.getAsInteger(0, V)) {
1404     setError("invalid filler expression: " + Tok);
1405     return {};
1406   }
1407   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
1408 }
1409 
1410 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1411   expect("(");
1412   SymbolAssignment *Cmd = readAssignment(next());
1413   Cmd->Provide = Provide;
1414   Cmd->Hidden = Hidden;
1415   expect(")");
1416   expect(";");
1417   return Cmd;
1418 }
1419 
1420 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1421   SymbolAssignment *Cmd = nullptr;
1422   if (peek() == "=" || peek() == "+=") {
1423     Cmd = readAssignment(Tok);
1424     expect(";");
1425   } else if (Tok == "PROVIDE") {
1426     Cmd = readProvideHidden(true, false);
1427   } else if (Tok == "HIDDEN") {
1428     Cmd = readProvideHidden(false, true);
1429   } else if (Tok == "PROVIDE_HIDDEN") {
1430     Cmd = readProvideHidden(true, true);
1431   }
1432   return Cmd;
1433 }
1434 
1435 static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1436   if (S == ".")
1437     return Dot;
1438   return ScriptBase->getSymbolValue(S);
1439 }
1440 
1441 static bool isAbsolute(StringRef S) {
1442   if (S == ".")
1443     return false;
1444   return ScriptBase->isAbsolute(S);
1445 }
1446 
1447 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1448   StringRef Op = next();
1449   Expr E;
1450   assert(Op == "=" || Op == "+=");
1451   if (consume("ABSOLUTE")) {
1452     // The RHS may be something like "ABSOLUTE(.) & 0xff".
1453     // Call readExpr1 to read the whole expression.
1454     E = readExpr1(readParenExpr(), 0);
1455     E.IsAbsolute = []() { return true; };
1456   } else {
1457     E = readExpr();
1458   }
1459   if (Op == "+=")
1460     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1461   return new SymbolAssignment(Name, E);
1462 }
1463 
1464 // This is an operator-precedence parser to parse a linker
1465 // script expression.
1466 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1467 
1468 static Expr combine(StringRef Op, Expr L, Expr R) {
1469   if (Op == "*")
1470     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1471   if (Op == "/") {
1472     return [=](uint64_t Dot) -> uint64_t {
1473       uint64_t RHS = R(Dot);
1474       if (RHS == 0) {
1475         error("division by zero");
1476         return 0;
1477       }
1478       return L(Dot) / RHS;
1479     };
1480   }
1481   if (Op == "+")
1482     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1483             [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
1484   if (Op == "-")
1485     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1486   if (Op == "<<")
1487     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1488   if (Op == ">>")
1489     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
1490   if (Op == "<")
1491     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1492   if (Op == ">")
1493     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1494   if (Op == ">=")
1495     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1496   if (Op == "<=")
1497     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1498   if (Op == "==")
1499     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1500   if (Op == "!=")
1501     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1502   if (Op == "&")
1503     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1504   if (Op == "|")
1505     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
1506   llvm_unreachable("invalid operator");
1507 }
1508 
1509 // This is a part of the operator-precedence parser. This function
1510 // assumes that the remaining token stream starts with an operator.
1511 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1512   while (!atEOF() && !Error) {
1513     // Read an operator and an expression.
1514     StringRef Op1 = peek();
1515     if (Op1 == "?")
1516       return readTernary(Lhs);
1517     if (precedence(Op1) < MinPrec)
1518       break;
1519     skip();
1520     Expr Rhs = readPrimary();
1521 
1522     // Evaluate the remaining part of the expression first if the
1523     // next operator has greater precedence than the previous one.
1524     // For example, if we have read "+" and "3", and if the next
1525     // operator is "*", then we'll evaluate 3 * ... part first.
1526     while (!atEOF()) {
1527       StringRef Op2 = peek();
1528       if (precedence(Op2) <= precedence(Op1))
1529         break;
1530       Rhs = readExpr1(Rhs, precedence(Op2));
1531     }
1532 
1533     Lhs = combine(Op1, Lhs, Rhs);
1534   }
1535   return Lhs;
1536 }
1537 
1538 uint64_t static getConstant(StringRef S) {
1539   if (S == "COMMONPAGESIZE")
1540     return Target->PageSize;
1541   if (S == "MAXPAGESIZE")
1542     return Config->MaxPageSize;
1543   error("unknown constant: " + S);
1544   return 0;
1545 }
1546 
1547 // Parses Tok as an integer. Returns true if successful.
1548 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1549 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1550 // "M" (mega) prefixes.
1551 static bool readInteger(StringRef Tok, uint64_t &Result) {
1552   if (Tok.startswith("-")) {
1553     if (!readInteger(Tok.substr(1), Result))
1554       return false;
1555     Result = -Result;
1556     return true;
1557   }
1558   if (Tok.startswith_lower("0x"))
1559     return !Tok.substr(2).getAsInteger(16, Result);
1560   if (Tok.endswith_lower("H"))
1561     return !Tok.drop_back().getAsInteger(16, Result);
1562 
1563   int Suffix = 1;
1564   if (Tok.endswith_lower("K")) {
1565     Suffix = 1024;
1566     Tok = Tok.drop_back();
1567   } else if (Tok.endswith_lower("M")) {
1568     Suffix = 1024 * 1024;
1569     Tok = Tok.drop_back();
1570   }
1571   if (Tok.getAsInteger(10, Result))
1572     return false;
1573   Result *= Suffix;
1574   return true;
1575 }
1576 
1577 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1578   int Size = StringSwitch<unsigned>(Tok)
1579                  .Case("BYTE", 1)
1580                  .Case("SHORT", 2)
1581                  .Case("LONG", 4)
1582                  .Case("QUAD", 8)
1583                  .Default(-1);
1584   if (Size == -1)
1585     return nullptr;
1586 
1587   expect("(");
1588   uint64_t Val = 0;
1589   StringRef S = next();
1590   if (!readInteger(S, Val))
1591     setError("unexpected value: " + S);
1592   expect(")");
1593   return new BytesDataCommand(Val, Size);
1594 }
1595 
1596 StringRef ScriptParser::readParenLiteral() {
1597   expect("(");
1598   StringRef Tok = next();
1599   expect(")");
1600   return Tok;
1601 }
1602 
1603 Expr ScriptParser::readPrimary() {
1604   if (peek() == "(")
1605     return readParenExpr();
1606 
1607   StringRef Tok = next();
1608 
1609   if (Tok == "~") {
1610     Expr E = readPrimary();
1611     return [=](uint64_t Dot) { return ~E(Dot); };
1612   }
1613   if (Tok == "-") {
1614     Expr E = readPrimary();
1615     return [=](uint64_t Dot) { return -E(Dot); };
1616   }
1617 
1618   // Built-in functions are parsed here.
1619   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1620   if (Tok == "ADDR") {
1621     StringRef Name = readParenLiteral();
1622     return
1623         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
1624   }
1625   if (Tok == "LOADADDR") {
1626     StringRef Name = readParenLiteral();
1627     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1628   }
1629   if (Tok == "ASSERT")
1630     return readAssert();
1631   if (Tok == "ALIGN") {
1632     Expr E = readParenExpr();
1633     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1634   }
1635   if (Tok == "CONSTANT") {
1636     StringRef Name = readParenLiteral();
1637     return [=](uint64_t Dot) { return getConstant(Name); };
1638   }
1639   if (Tok == "DEFINED") {
1640     expect("(");
1641     StringRef Tok = next();
1642     expect(")");
1643     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1644   }
1645   if (Tok == "SEGMENT_START") {
1646     expect("(");
1647     skip();
1648     expect(",");
1649     Expr E = readExpr();
1650     expect(")");
1651     return [=](uint64_t Dot) { return E(Dot); };
1652   }
1653   if (Tok == "DATA_SEGMENT_ALIGN") {
1654     expect("(");
1655     Expr E = readExpr();
1656     expect(",");
1657     readExpr();
1658     expect(")");
1659     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1660   }
1661   if (Tok == "DATA_SEGMENT_END") {
1662     expect("(");
1663     expect(".");
1664     expect(")");
1665     return [](uint64_t Dot) { return Dot; };
1666   }
1667   // GNU linkers implements more complicated logic to handle
1668   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1669   // the next page boundary for simplicity.
1670   if (Tok == "DATA_SEGMENT_RELRO_END") {
1671     expect("(");
1672     readExpr();
1673     expect(",");
1674     readExpr();
1675     expect(")");
1676     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1677   }
1678   if (Tok == "SIZEOF") {
1679     StringRef Name = readParenLiteral();
1680     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
1681   }
1682   if (Tok == "ALIGNOF") {
1683     StringRef Name = readParenLiteral();
1684     return
1685         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1686   }
1687   if (Tok == "SIZEOF_HEADERS")
1688     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1689 
1690   // Tok is a literal number.
1691   uint64_t V;
1692   if (readInteger(Tok, V))
1693     return [=](uint64_t Dot) { return V; };
1694 
1695   // Tok is a symbol name.
1696   if (Tok != "." && !isValidCIdentifier(Tok))
1697     setError("malformed number: " + Tok);
1698   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1699           [=]() { return isAbsolute(Tok); }};
1700 }
1701 
1702 Expr ScriptParser::readTernary(Expr Cond) {
1703   skip();
1704   Expr L = readExpr();
1705   expect(":");
1706   Expr R = readExpr();
1707   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1708 }
1709 
1710 Expr ScriptParser::readParenExpr() {
1711   expect("(");
1712   Expr E = readExpr();
1713   expect(")");
1714   return E;
1715 }
1716 
1717 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1718   std::vector<StringRef> Phdrs;
1719   while (!Error && peek().startswith(":")) {
1720     StringRef Tok = next();
1721     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1722     if (Tok.empty()) {
1723       setError("section header name is empty");
1724       break;
1725     }
1726     Phdrs.push_back(Tok);
1727   }
1728   return Phdrs;
1729 }
1730 
1731 // Read a program header type name. The next token must be a
1732 // name of a program header type or a constant (e.g. "0x3").
1733 unsigned ScriptParser::readPhdrType() {
1734   StringRef Tok = next();
1735   uint64_t Val;
1736   if (readInteger(Tok, Val))
1737     return Val;
1738 
1739   unsigned Ret = StringSwitch<unsigned>(Tok)
1740                      .Case("PT_NULL", PT_NULL)
1741                      .Case("PT_LOAD", PT_LOAD)
1742                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1743                      .Case("PT_INTERP", PT_INTERP)
1744                      .Case("PT_NOTE", PT_NOTE)
1745                      .Case("PT_SHLIB", PT_SHLIB)
1746                      .Case("PT_PHDR", PT_PHDR)
1747                      .Case("PT_TLS", PT_TLS)
1748                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1749                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1750                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1751                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1752                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1753                      .Default(-1);
1754 
1755   if (Ret == (unsigned)-1) {
1756     setError("invalid program header type: " + Tok);
1757     return PT_NULL;
1758   }
1759   return Ret;
1760 }
1761 
1762 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1763   // Identifiers start at 2 because 0 and 1 are reserved
1764   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1765   size_t VersionId = Config->VersionDefinitions.size() + 2;
1766   Config->VersionDefinitions.push_back({VerStr, VersionId});
1767 
1768   if (consume("global:") || peek() != "local:")
1769     readGlobal(VerStr);
1770   if (consume("local:"))
1771     readLocal();
1772   expect("}");
1773 
1774   // Each version may have a parent version. For example, "Ver2" defined as
1775   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1776   // version hierarchy is, probably against your instinct, purely for human; the
1777   // runtime doesn't care about them at all. In LLD, we simply skip the token.
1778   if (!VerStr.empty() && peek() != ";")
1779     skip();
1780   expect(";");
1781 }
1782 
1783 void ScriptParser::readLocal() {
1784   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1785   expect("*");
1786   expect(";");
1787 }
1788 
1789 void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1790   expect("\"C++\"");
1791   expect("{");
1792 
1793   for (;;) {
1794     if (peek() == "}" || Error)
1795       break;
1796     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1797     Globals->push_back({unquote(next()), true, HasWildcard});
1798     expect(";");
1799   }
1800 
1801   expect("}");
1802   expect(";");
1803 }
1804 
1805 void ScriptParser::readGlobal(StringRef VerStr) {
1806   std::vector<SymbolVersion> *Globals;
1807   if (VerStr.empty())
1808     Globals = &Config->VersionScriptGlobals;
1809   else
1810     Globals = &Config->VersionDefinitions.back().Globals;
1811 
1812   for (;;) {
1813     if (consume("extern"))
1814       readExtern(Globals);
1815 
1816     StringRef Cur = peek();
1817     if (Cur == "}" || Cur == "local:" || Error)
1818       return;
1819     skip();
1820     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
1821     expect(";");
1822   }
1823 }
1824 
1825 static bool isUnderSysroot(StringRef Path) {
1826   if (Config->Sysroot == "")
1827     return false;
1828   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1829     if (sys::fs::equivalent(Config->Sysroot, Path))
1830       return true;
1831   return false;
1832 }
1833 
1834 void elf::readLinkerScript(MemoryBufferRef MB) {
1835   StringRef Path = MB.getBufferIdentifier();
1836   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1837 }
1838 
1839 void elf::readVersionScript(MemoryBufferRef MB) {
1840   ScriptParser(MB.getBuffer(), false).readVersionScript();
1841 }
1842 
1843 template class elf::LinkerScript<ELF32LE>;
1844 template class elf::LinkerScript<ELF32BE>;
1845 template class elf::LinkerScript<ELF64LE>;
1846 template class elf::LinkerScript<ELF64BE>;
1847