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->FilePat.match(sys::path::filename(Filename)))
115       continue;
116 
117     for (SectionPattern &P : ID->SectionPatterns)
118       if (P.SectionPat.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->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
182         continue;
183 
184       for (InputSectionBase<ELFT> *S : F->getSections())
185         if (!isDiscarded(S) && !S->OutSec && Pat.SectionPat.match(S->Name))
186           I->Sections.push_back(S);
187       if (Pat.SectionPat.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 = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
547     OutputSections->push_back(OutSec);
548   }
549 }
550 
551 // When placing orphan sections, we want to place them after symbol assignments
552 // so that an orphan after
553 //   begin_foo = .;
554 //   foo : { *(foo) }
555 //   end_foo = .;
556 // doesn't break the intended meaning of the begin/end symbols.
557 // We don't want to go over sections since Writer<ELFT>::sortSections is the
558 // one in charge of deciding the order of the sections.
559 // We don't want to go over alignments, since doing so in
560 //  rx_sec : { *(rx_sec) }
561 //  . = ALIGN(0x1000);
562 //  /* The RW PT_LOAD starts here*/
563 //  rw_sec : { *(rw_sec) }
564 // would mean that the RW PT_LOAD would become unaligned.
565 static bool shouldSkip(const BaseCommand &Cmd) {
566   if (isa<OutputSectionCommand>(Cmd))
567     return false;
568   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
569   if (!Assign)
570     return true;
571   return Assign->Name != ".";
572 }
573 
574 template <class ELFT>
575 void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
576   // Orphan sections are sections present in the input files which
577   // are not explicitly placed into the output file by the linker script.
578   // We place orphan sections at end of file.
579   // Other linkers places them using some heuristics as described in
580   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
581 
582   // The OutputSections are already in the correct order.
583   // This loops creates or moves commands as needed so that they are in the
584   // correct order.
585   int CmdIndex = 0;
586   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
587     StringRef Name = Sec->getName();
588 
589     // Find the last spot where we can insert a command and still get the
590     // correct result.
591     auto CmdIter = Opt.Commands.begin() + CmdIndex;
592     auto E = Opt.Commands.end();
593     while (CmdIter != E && shouldSkip(**CmdIter)) {
594       ++CmdIter;
595       ++CmdIndex;
596     }
597 
598     auto Pos =
599         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
600           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
601           return Cmd && Cmd->Name == Name;
602         });
603     if (Pos == E) {
604       Opt.Commands.insert(CmdIter,
605                           llvm::make_unique<OutputSectionCommand>(Name));
606       ++CmdIndex;
607       continue;
608     }
609 
610     // Continue from where we found it.
611     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
612     continue;
613   }
614 
615   // Assign addresses as instructed by linker script SECTIONS sub-commands.
616   Dot = 0;
617 
618   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
619     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
620       if (Cmd->Name == ".") {
621         Dot = Cmd->Expression(Dot);
622       } else if (Cmd->Sym) {
623         assignSectionSymbol(Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0],
624                             Dot);
625       }
626       continue;
627     }
628 
629     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
630       Cmd->Expression(Dot);
631       continue;
632     }
633 
634     auto *Cmd = cast<OutputSectionCommand>(Base.get());
635 
636     if (Cmd->AddrExpr)
637       Dot = Cmd->AddrExpr(Dot);
638 
639     assignOffsets(Cmd);
640   }
641 
642   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
643   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
644     if (Sec->getFlags() & SHF_ALLOC)
645       MinVA = std::min(MinVA, Sec->getVA());
646     else
647       Sec->setVA(0);
648   }
649 
650   uintX_t HeaderSize = getHeaderSize();
651   auto FirstPTLoad =
652       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
653         return E.H.p_type == PT_LOAD;
654       });
655 
656   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
657     // If linker script specifies program headers and first PT_LOAD doesn't
658     // have both PHDRS and FILEHDR attributes then do nothing
659     if (!Opt.PhdrsCommands.empty()) {
660       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
661       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
662           !Opt.PhdrsCommands[SegNum].HasFilehdr)
663         return;
664     }
665     // ELF and Program headers need to be right before the first section in
666     // memory. Set their addresses accordingly.
667     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
668     Out<ELFT>::ElfHeader->setVA(MinVA);
669     Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
670     FirstPTLoad->First = Out<ELFT>::ElfHeader;
671     if (!FirstPTLoad->Last)
672       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
673   } else if (!FirstPTLoad->First) {
674     // Sometimes the very first PT_LOAD segment can be empty.
675     // This happens if (all conditions met):
676     //  - Linker script is used
677     //  - First section in ELF image is not RO
678     //  - Not enough space for program headers.
679     // The code below removes empty PT_LOAD segment and updates
680     // program headers size.
681     Phdrs.erase(FirstPTLoad);
682     Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
683                                        Phdrs.size());
684   }
685 }
686 
687 // Creates program headers as instructed by PHDRS linker script command.
688 template <class ELFT>
689 std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
690   std::vector<PhdrEntry<ELFT>> Ret;
691 
692   // Process PHDRS and FILEHDR keywords because they are not
693   // real output sections and cannot be added in the following loop.
694   std::vector<size_t> DefPhdrIds;
695   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
696     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
697     PhdrEntry<ELFT> &Phdr = Ret.back();
698 
699     if (Cmd.HasFilehdr)
700       Phdr.add(Out<ELFT>::ElfHeader);
701     if (Cmd.HasPhdrs)
702       Phdr.add(Out<ELFT>::ProgramHeaders);
703 
704     if (Cmd.LMAExpr) {
705       Phdr.H.p_paddr = Cmd.LMAExpr(0);
706       Phdr.HasLMA = true;
707     }
708 
709     // If output section command doesn't specify any segments,
710     // and we haven't previously assigned any section to segment,
711     // then we simply assign section to the very first load segment.
712     // Below is an example of such linker script:
713     // PHDRS { seg PT_LOAD; }
714     // SECTIONS { .aaa : { *(.aaa) } }
715     if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
716       DefPhdrIds.push_back(Ret.size() - 1);
717   }
718 
719   // Add output sections to program headers.
720   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
721     if (!(Sec->getFlags() & SHF_ALLOC))
722       break;
723 
724     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
725     if (PhdrIds.empty())
726       PhdrIds = std::move(DefPhdrIds);
727 
728     // Assign headers specified by linker script
729     for (size_t Id : PhdrIds) {
730       Ret[Id].add(Sec);
731       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
732         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
733     }
734     DefPhdrIds = std::move(PhdrIds);
735   }
736   return Ret;
737 }
738 
739 template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
740   // Ignore .interp section in case we have PHDRS specification
741   // and PT_INTERP isn't listed.
742   return !Opt.PhdrsCommands.empty() &&
743          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
744            return Cmd.Type == PT_INTERP;
745          }) == Opt.PhdrsCommands.end();
746 }
747 
748 template <class ELFT>
749 ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
750   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
751     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
752       if (Cmd->Name == Name)
753         return Cmd->Filler;
754   return {};
755 }
756 
757 template <class ELFT>
758 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
759   const endianness E = ELFT::TargetEndianness;
760 
761   switch (Size) {
762   case 1:
763     *Buf = (uint8_t)Data;
764     break;
765   case 2:
766     write16<E>(Buf, Data);
767     break;
768   case 4:
769     write32<E>(Buf, Data);
770     break;
771   case 8:
772     write64<E>(Buf, Data);
773     break;
774   default:
775     llvm_unreachable("unsupported Size argument");
776   }
777 }
778 
779 template <class ELFT>
780 void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
781   int I = getSectionIndex(Name);
782   if (I == INT_MAX)
783     return;
784 
785   OutputSectionCommand *Cmd =
786       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
787   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
788     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
789       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
790 }
791 
792 template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
793   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
794     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
795       if (Cmd->LMAExpr && Cmd->Name == Name)
796         return true;
797   return false;
798 }
799 
800 // Returns the index of the given section name in linker script
801 // SECTIONS commands. Sections are laid out as the same order as they
802 // were in the script. If a given name did not appear in the script,
803 // it returns INT_MAX, so that it will be laid out at end of file.
804 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
805   int I = 0;
806   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
807     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
808       if (Cmd->Name == Name)
809         return I;
810     ++I;
811   }
812   return INT_MAX;
813 }
814 
815 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
816   return !Opt.PhdrsCommands.empty();
817 }
818 
819 template <class ELFT>
820 uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
821   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
822     if (Sec->getName() == Name)
823       return Sec->getVA();
824   error("undefined section " + Name);
825   return 0;
826 }
827 
828 template <class ELFT>
829 uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
830   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
831     if (Sec->getName() == Name)
832       return Sec->getLMA();
833   error("undefined section " + Name);
834   return 0;
835 }
836 
837 template <class ELFT>
838 uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
839   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
840     if (Sec->getName() == Name)
841       return Sec->getSize();
842   error("undefined section " + Name);
843   return 0;
844 }
845 
846 template <class ELFT>
847 uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
848   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
849     if (Sec->getName() == Name)
850       return Sec->getAlignment();
851   error("undefined section " + Name);
852   return 0;
853 }
854 
855 template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
856   return elf::getHeaderSize<ELFT>();
857 }
858 
859 template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
860   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
861     return B->getVA<ELFT>();
862   error("symbol not found: " + S);
863   return 0;
864 }
865 
866 template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
867   return Symtab<ELFT>::X->find(S) != nullptr;
868 }
869 
870 template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
871   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
872   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
873   return DR && !DR->Section;
874 }
875 
876 // Returns indices of ELF headers containing specific section, identified
877 // by Name. Each index is a zero based number of ELF header listed within
878 // PHDRS {} script block.
879 template <class ELFT>
880 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
881   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
882     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
883     if (!Cmd || Cmd->Name != SectionName)
884       continue;
885 
886     std::vector<size_t> Ret;
887     for (StringRef PhdrName : Cmd->Phdrs)
888       Ret.push_back(getPhdrIndex(PhdrName));
889     return Ret;
890   }
891   return {};
892 }
893 
894 template <class ELFT>
895 size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
896   size_t I = 0;
897   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
898     if (Cmd.Name == PhdrName)
899       return I;
900     ++I;
901   }
902   error("section header '" + PhdrName + "' is not listed in PHDRS");
903   return 0;
904 }
905 
906 class elf::ScriptParser : public ScriptParserBase {
907   typedef void (ScriptParser::*Handler)();
908 
909 public:
910   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
911 
912   void readLinkerScript();
913   void readVersionScript();
914 
915 private:
916   void addFile(StringRef Path);
917 
918   void readAsNeeded();
919   void readEntry();
920   void readExtern();
921   void readGroup();
922   void readInclude();
923   void readOutput();
924   void readOutputArch();
925   void readOutputFormat();
926   void readPhdrs();
927   void readSearchDir();
928   void readSections();
929   void readVersion();
930   void readVersionScriptCommand();
931 
932   SymbolAssignment *readAssignment(StringRef Name);
933   BytesDataCommand *readBytesDataCommand(StringRef Tok);
934   std::vector<uint8_t> readFill();
935   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
936   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
937   std::vector<StringRef> readOutputSectionPhdrs();
938   InputSectionDescription *readInputSectionDescription(StringRef Tok);
939   StringMatcher readFilePatterns();
940   std::vector<SectionPattern> readInputSectionsList();
941   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
942   unsigned readPhdrType();
943   SortSectionPolicy readSortKind();
944   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
945   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
946   void readSort();
947   Expr readAssert();
948 
949   Expr readExpr();
950   Expr readExpr1(Expr Lhs, int MinPrec);
951   StringRef readParenLiteral();
952   Expr readPrimary();
953   Expr readTernary(Expr Cond);
954   Expr readParenExpr();
955 
956   // For parsing version script.
957   void readExtern(std::vector<SymbolVersion> *Globals);
958   void readVersionDeclaration(StringRef VerStr);
959   void readGlobal(StringRef VerStr);
960   void readLocal();
961 
962   ScriptConfiguration &Opt = *ScriptConfig;
963   bool IsUnderSysroot;
964 };
965 
966 void ScriptParser::readVersionScript() {
967   readVersionScriptCommand();
968   if (!atEOF())
969     setError("EOF expected, but got " + next());
970 }
971 
972 void ScriptParser::readVersionScriptCommand() {
973   if (consume("{")) {
974     readVersionDeclaration("");
975     return;
976   }
977 
978   while (!atEOF() && !Error && peek() != "}") {
979     StringRef VerStr = next();
980     if (VerStr == "{") {
981       setError("anonymous version definition is used in "
982                "combination with other version definitions");
983       return;
984     }
985     expect("{");
986     readVersionDeclaration(VerStr);
987   }
988 }
989 
990 void ScriptParser::readVersion() {
991   expect("{");
992   readVersionScriptCommand();
993   expect("}");
994 }
995 
996 void ScriptParser::readLinkerScript() {
997   while (!atEOF()) {
998     StringRef Tok = next();
999     if (Tok == ";")
1000       continue;
1001 
1002     if (Tok == "ASSERT") {
1003       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1004     } else if (Tok == "ENTRY") {
1005       readEntry();
1006     } else if (Tok == "EXTERN") {
1007       readExtern();
1008     } else if (Tok == "GROUP" || Tok == "INPUT") {
1009       readGroup();
1010     } else if (Tok == "INCLUDE") {
1011       readInclude();
1012     } else if (Tok == "OUTPUT") {
1013       readOutput();
1014     } else if (Tok == "OUTPUT_ARCH") {
1015       readOutputArch();
1016     } else if (Tok == "OUTPUT_FORMAT") {
1017       readOutputFormat();
1018     } else if (Tok == "PHDRS") {
1019       readPhdrs();
1020     } else if (Tok == "SEARCH_DIR") {
1021       readSearchDir();
1022     } else if (Tok == "SECTIONS") {
1023       readSections();
1024     } else if (Tok == "VERSION") {
1025       readVersion();
1026     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
1027       Opt.Commands.emplace_back(Cmd);
1028     } else {
1029       setError("unknown directive: " + Tok);
1030     }
1031   }
1032 }
1033 
1034 void ScriptParser::addFile(StringRef S) {
1035   if (IsUnderSysroot && S.startswith("/")) {
1036     SmallString<128> PathData;
1037     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
1038     if (sys::fs::exists(Path)) {
1039       Driver->addFile(Saver.save(Path));
1040       return;
1041     }
1042   }
1043 
1044   if (sys::path::is_absolute(S)) {
1045     Driver->addFile(S);
1046   } else if (S.startswith("=")) {
1047     if (Config->Sysroot.empty())
1048       Driver->addFile(S.substr(1));
1049     else
1050       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1051   } else if (S.startswith("-l")) {
1052     Driver->addLibrary(S.substr(2));
1053   } else if (sys::fs::exists(S)) {
1054     Driver->addFile(S);
1055   } else {
1056     std::string Path = findFromSearchPaths(S);
1057     if (Path.empty())
1058       setError("unable to find " + S);
1059     else
1060       Driver->addFile(Saver.save(Path));
1061   }
1062 }
1063 
1064 void ScriptParser::readAsNeeded() {
1065   expect("(");
1066   bool Orig = Config->AsNeeded;
1067   Config->AsNeeded = true;
1068   while (!Error && !consume(")"))
1069     addFile(unquote(next()));
1070   Config->AsNeeded = Orig;
1071 }
1072 
1073 void ScriptParser::readEntry() {
1074   // -e <symbol> takes predecence over ENTRY(<symbol>).
1075   expect("(");
1076   StringRef Tok = next();
1077   if (Config->Entry.empty())
1078     Config->Entry = Tok;
1079   expect(")");
1080 }
1081 
1082 void ScriptParser::readExtern() {
1083   expect("(");
1084   while (!Error && !consume(")"))
1085     Config->Undefined.push_back(next());
1086 }
1087 
1088 void ScriptParser::readGroup() {
1089   expect("(");
1090   while (!Error && !consume(")")) {
1091     StringRef Tok = next();
1092     if (Tok == "AS_NEEDED")
1093       readAsNeeded();
1094     else
1095       addFile(unquote(Tok));
1096   }
1097 }
1098 
1099 void ScriptParser::readInclude() {
1100   StringRef Tok = next();
1101   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1102   if (!MBOrErr) {
1103     setError("cannot open " + Tok);
1104     return;
1105   }
1106   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1107   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1108   std::vector<StringRef> V = tokenize(S);
1109   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
1110 }
1111 
1112 void ScriptParser::readOutput() {
1113   // -o <file> takes predecence over OUTPUT(<file>).
1114   expect("(");
1115   StringRef Tok = next();
1116   if (Config->OutputFile.empty())
1117     Config->OutputFile = unquote(Tok);
1118   expect(")");
1119 }
1120 
1121 void ScriptParser::readOutputArch() {
1122   // Error checking only for now.
1123   expect("(");
1124   skip();
1125   expect(")");
1126 }
1127 
1128 void ScriptParser::readOutputFormat() {
1129   // Error checking only for now.
1130   expect("(");
1131   skip();
1132   StringRef Tok = next();
1133   if (Tok == ")")
1134     return;
1135   if (Tok != ",") {
1136     setError("unexpected token: " + Tok);
1137     return;
1138   }
1139   skip();
1140   expect(",");
1141   skip();
1142   expect(")");
1143 }
1144 
1145 void ScriptParser::readPhdrs() {
1146   expect("{");
1147   while (!Error && !consume("}")) {
1148     StringRef Tok = next();
1149     Opt.PhdrsCommands.push_back(
1150         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1151     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1152 
1153     PhdrCmd.Type = readPhdrType();
1154     do {
1155       Tok = next();
1156       if (Tok == ";")
1157         break;
1158       if (Tok == "FILEHDR")
1159         PhdrCmd.HasFilehdr = true;
1160       else if (Tok == "PHDRS")
1161         PhdrCmd.HasPhdrs = true;
1162       else if (Tok == "AT")
1163         PhdrCmd.LMAExpr = readParenExpr();
1164       else if (Tok == "FLAGS") {
1165         expect("(");
1166         // Passing 0 for the value of dot is a bit of a hack. It means that
1167         // we accept expressions like ".|1".
1168         PhdrCmd.Flags = readExpr()(0);
1169         expect(")");
1170       } else
1171         setError("unexpected header attribute: " + Tok);
1172     } while (!Error);
1173   }
1174 }
1175 
1176 void ScriptParser::readSearchDir() {
1177   expect("(");
1178   StringRef Tok = next();
1179   if (!Config->Nostdlib)
1180     Config->SearchPaths.push_back(unquote(Tok));
1181   expect(")");
1182 }
1183 
1184 void ScriptParser::readSections() {
1185   Opt.HasSections = true;
1186   expect("{");
1187   while (!Error && !consume("}")) {
1188     StringRef Tok = next();
1189     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1190     if (!Cmd) {
1191       if (Tok == "ASSERT")
1192         Cmd = new AssertCommand(readAssert());
1193       else
1194         Cmd = readOutputSectionDescription(Tok);
1195     }
1196     Opt.Commands.emplace_back(Cmd);
1197   }
1198 }
1199 
1200 static int precedence(StringRef Op) {
1201   return StringSwitch<int>(Op)
1202       .Cases("*", "/", 5)
1203       .Cases("+", "-", 4)
1204       .Cases("<<", ">>", 3)
1205       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
1206       .Cases("&", "|", 1)
1207       .Default(-1);
1208 }
1209 
1210 StringMatcher ScriptParser::readFilePatterns() {
1211   std::vector<StringRef> V;
1212   while (!Error && !consume(")"))
1213     V.push_back(next());
1214   return StringMatcher(V);
1215 }
1216 
1217 SortSectionPolicy ScriptParser::readSortKind() {
1218   if (consume("SORT") || consume("SORT_BY_NAME"))
1219     return SortSectionPolicy::Name;
1220   if (consume("SORT_BY_ALIGNMENT"))
1221     return SortSectionPolicy::Alignment;
1222   if (consume("SORT_BY_INIT_PRIORITY"))
1223     return SortSectionPolicy::Priority;
1224   if (consume("SORT_NONE"))
1225     return SortSectionPolicy::None;
1226   return SortSectionPolicy::Default;
1227 }
1228 
1229 // Method reads a list of sequence of excluded files and section globs given in
1230 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1231 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1232 // The semantics of that is next:
1233 // * Include .foo.1 from every file.
1234 // * Include .foo.2 from every file but a.o
1235 // * Include .foo.3 from every file but b.o
1236 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1237   std::vector<SectionPattern> Ret;
1238   while (!Error && peek() != ")") {
1239     StringMatcher ExcludeFilePat;
1240     if (consume("EXCLUDE_FILE")) {
1241       expect("(");
1242       ExcludeFilePat = readFilePatterns();
1243     }
1244 
1245     std::vector<StringRef> V;
1246     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1247       V.push_back(next());
1248 
1249     if (!V.empty())
1250       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1251     else
1252       setError("section pattern is expected");
1253   }
1254   return Ret;
1255 }
1256 
1257 // Section pattern grammar can have complex expressions, for example:
1258 // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1259 // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1260 // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1261 // This methods handles wrapping sequences of excluded files and section globs
1262 // into SORT() if that needed and reads them all.
1263 InputSectionDescription *
1264 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1265   auto *Cmd = new InputSectionDescription(FilePattern);
1266   expect("(");
1267   while (!HasError && !consume(")")) {
1268     SortSectionPolicy Outer = readSortKind();
1269     SortSectionPolicy Inner = SortSectionPolicy::Default;
1270     std::vector<SectionPattern> V;
1271     if (Outer != SortSectionPolicy::Default) {
1272       expect("(");
1273       Inner = readSortKind();
1274       if (Inner != SortSectionPolicy::Default) {
1275         expect("(");
1276         V = readInputSectionsList();
1277         expect(")");
1278       } else {
1279         V = readInputSectionsList();
1280       }
1281       expect(")");
1282     } else {
1283       V = readInputSectionsList();
1284     }
1285 
1286     for (SectionPattern &Pat : V) {
1287       Pat.SortInner = Inner;
1288       Pat.SortOuter = Outer;
1289     }
1290 
1291     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1292   }
1293   return Cmd;
1294 }
1295 
1296 InputSectionDescription *
1297 ScriptParser::readInputSectionDescription(StringRef Tok) {
1298   // Input section wildcard can be surrounded by KEEP.
1299   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1300   if (Tok == "KEEP") {
1301     expect("(");
1302     StringRef FilePattern = next();
1303     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1304     expect(")");
1305     Opt.KeptSections.push_back(Cmd);
1306     return Cmd;
1307   }
1308   return readInputSectionRules(Tok);
1309 }
1310 
1311 void ScriptParser::readSort() {
1312   expect("(");
1313   expect("CONSTRUCTORS");
1314   expect(")");
1315 }
1316 
1317 Expr ScriptParser::readAssert() {
1318   expect("(");
1319   Expr E = readExpr();
1320   expect(",");
1321   StringRef Msg = unquote(next());
1322   expect(")");
1323   return [=](uint64_t Dot) {
1324     uint64_t V = E(Dot);
1325     if (!V)
1326       error(Msg);
1327     return V;
1328   };
1329 }
1330 
1331 // Reads a FILL(expr) command. We handle the FILL command as an
1332 // alias for =fillexp section attribute, which is different from
1333 // what GNU linkers do.
1334 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1335 std::vector<uint8_t> ScriptParser::readFill() {
1336   expect("(");
1337   std::vector<uint8_t> V = readOutputSectionFiller(next());
1338   expect(")");
1339   expect(";");
1340   return V;
1341 }
1342 
1343 OutputSectionCommand *
1344 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1345   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1346 
1347   // Read an address expression.
1348   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1349   if (peek() != ":")
1350     Cmd->AddrExpr = readExpr();
1351 
1352   expect(":");
1353 
1354   if (consume("AT"))
1355     Cmd->LMAExpr = readParenExpr();
1356   if (consume("ALIGN"))
1357     Cmd->AlignExpr = readParenExpr();
1358   if (consume("SUBALIGN"))
1359     Cmd->SubalignExpr = readParenExpr();
1360 
1361   // Parse constraints.
1362   if (consume("ONLY_IF_RO"))
1363     Cmd->Constraint = ConstraintKind::ReadOnly;
1364   if (consume("ONLY_IF_RW"))
1365     Cmd->Constraint = ConstraintKind::ReadWrite;
1366   expect("{");
1367 
1368   while (!Error && !consume("}")) {
1369     StringRef Tok = next();
1370     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1371       Cmd->Commands.emplace_back(Assignment);
1372     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1373       Cmd->Commands.emplace_back(Data);
1374     else if (Tok == "FILL")
1375       Cmd->Filler = readFill();
1376     else if (Tok == "SORT")
1377       readSort();
1378     else if (peek() == "(")
1379       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1380     else
1381       setError("unknown command " + Tok);
1382   }
1383   Cmd->Phdrs = readOutputSectionPhdrs();
1384 
1385   if (consume("="))
1386     Cmd->Filler = readOutputSectionFiller(next());
1387   else if (peek().startswith("="))
1388     Cmd->Filler = readOutputSectionFiller(next().drop_front());
1389 
1390   return Cmd;
1391 }
1392 
1393 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1394 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1395 //
1396 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1397 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1398 // as 32-bit big-endian values. We will do the same as ld.gold does
1399 // because it's simpler than what ld.bfd does.
1400 std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1401   uint32_t V;
1402   if (Tok.getAsInteger(0, V)) {
1403     setError("invalid filler expression: " + Tok);
1404     return {};
1405   }
1406   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
1407 }
1408 
1409 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1410   expect("(");
1411   SymbolAssignment *Cmd = readAssignment(next());
1412   Cmd->Provide = Provide;
1413   Cmd->Hidden = Hidden;
1414   expect(")");
1415   expect(";");
1416   return Cmd;
1417 }
1418 
1419 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1420   SymbolAssignment *Cmd = nullptr;
1421   if (peek() == "=" || peek() == "+=") {
1422     Cmd = readAssignment(Tok);
1423     expect(";");
1424   } else if (Tok == "PROVIDE") {
1425     Cmd = readProvideHidden(true, false);
1426   } else if (Tok == "HIDDEN") {
1427     Cmd = readProvideHidden(false, true);
1428   } else if (Tok == "PROVIDE_HIDDEN") {
1429     Cmd = readProvideHidden(true, true);
1430   }
1431   return Cmd;
1432 }
1433 
1434 static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1435   if (S == ".")
1436     return Dot;
1437   return ScriptBase->getSymbolValue(S);
1438 }
1439 
1440 static bool isAbsolute(StringRef S) {
1441   if (S == ".")
1442     return false;
1443   return ScriptBase->isAbsolute(S);
1444 }
1445 
1446 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1447   StringRef Op = next();
1448   Expr E;
1449   assert(Op == "=" || Op == "+=");
1450   if (consume("ABSOLUTE")) {
1451     // The RHS may be something like "ABSOLUTE(.) & 0xff".
1452     // Call readExpr1 to read the whole expression.
1453     E = readExpr1(readParenExpr(), 0);
1454     E.IsAbsolute = []() { return true; };
1455   } else {
1456     E = readExpr();
1457   }
1458   if (Op == "+=")
1459     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1460   return new SymbolAssignment(Name, E);
1461 }
1462 
1463 // This is an operator-precedence parser to parse a linker
1464 // script expression.
1465 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1466 
1467 static Expr combine(StringRef Op, Expr L, Expr R) {
1468   if (Op == "*")
1469     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1470   if (Op == "/") {
1471     return [=](uint64_t Dot) -> uint64_t {
1472       uint64_t RHS = R(Dot);
1473       if (RHS == 0) {
1474         error("division by zero");
1475         return 0;
1476       }
1477       return L(Dot) / RHS;
1478     };
1479   }
1480   if (Op == "+")
1481     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1482             [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
1483   if (Op == "-")
1484     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1485   if (Op == "<<")
1486     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1487   if (Op == ">>")
1488     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
1489   if (Op == "<")
1490     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1491   if (Op == ">")
1492     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1493   if (Op == ">=")
1494     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1495   if (Op == "<=")
1496     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1497   if (Op == "==")
1498     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1499   if (Op == "!=")
1500     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1501   if (Op == "&")
1502     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1503   if (Op == "|")
1504     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
1505   llvm_unreachable("invalid operator");
1506 }
1507 
1508 // This is a part of the operator-precedence parser. This function
1509 // assumes that the remaining token stream starts with an operator.
1510 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1511   while (!atEOF() && !Error) {
1512     // Read an operator and an expression.
1513     StringRef Op1 = peek();
1514     if (Op1 == "?")
1515       return readTernary(Lhs);
1516     if (precedence(Op1) < MinPrec)
1517       break;
1518     skip();
1519     Expr Rhs = readPrimary();
1520 
1521     // Evaluate the remaining part of the expression first if the
1522     // next operator has greater precedence than the previous one.
1523     // For example, if we have read "+" and "3", and if the next
1524     // operator is "*", then we'll evaluate 3 * ... part first.
1525     while (!atEOF()) {
1526       StringRef Op2 = peek();
1527       if (precedence(Op2) <= precedence(Op1))
1528         break;
1529       Rhs = readExpr1(Rhs, precedence(Op2));
1530     }
1531 
1532     Lhs = combine(Op1, Lhs, Rhs);
1533   }
1534   return Lhs;
1535 }
1536 
1537 uint64_t static getConstant(StringRef S) {
1538   if (S == "COMMONPAGESIZE")
1539     return Target->PageSize;
1540   if (S == "MAXPAGESIZE")
1541     return Config->MaxPageSize;
1542   error("unknown constant: " + S);
1543   return 0;
1544 }
1545 
1546 // Parses Tok as an integer. Returns true if successful.
1547 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1548 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1549 // "M" (mega) prefixes.
1550 static bool readInteger(StringRef Tok, uint64_t &Result) {
1551   if (Tok.startswith("-")) {
1552     if (!readInteger(Tok.substr(1), Result))
1553       return false;
1554     Result = -Result;
1555     return true;
1556   }
1557   if (Tok.startswith_lower("0x"))
1558     return !Tok.substr(2).getAsInteger(16, Result);
1559   if (Tok.endswith_lower("H"))
1560     return !Tok.drop_back().getAsInteger(16, Result);
1561 
1562   int Suffix = 1;
1563   if (Tok.endswith_lower("K")) {
1564     Suffix = 1024;
1565     Tok = Tok.drop_back();
1566   } else if (Tok.endswith_lower("M")) {
1567     Suffix = 1024 * 1024;
1568     Tok = Tok.drop_back();
1569   }
1570   if (Tok.getAsInteger(10, Result))
1571     return false;
1572   Result *= Suffix;
1573   return true;
1574 }
1575 
1576 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1577   int Size = StringSwitch<unsigned>(Tok)
1578                  .Case("BYTE", 1)
1579                  .Case("SHORT", 2)
1580                  .Case("LONG", 4)
1581                  .Case("QUAD", 8)
1582                  .Default(-1);
1583   if (Size == -1)
1584     return nullptr;
1585 
1586   expect("(");
1587   uint64_t Val = 0;
1588   StringRef S = next();
1589   if (!readInteger(S, Val))
1590     setError("unexpected value: " + S);
1591   expect(")");
1592   return new BytesDataCommand(Val, Size);
1593 }
1594 
1595 StringRef ScriptParser::readParenLiteral() {
1596   expect("(");
1597   StringRef Tok = next();
1598   expect(")");
1599   return Tok;
1600 }
1601 
1602 Expr ScriptParser::readPrimary() {
1603   if (peek() == "(")
1604     return readParenExpr();
1605 
1606   StringRef Tok = next();
1607 
1608   if (Tok == "~") {
1609     Expr E = readPrimary();
1610     return [=](uint64_t Dot) { return ~E(Dot); };
1611   }
1612   if (Tok == "-") {
1613     Expr E = readPrimary();
1614     return [=](uint64_t Dot) { return -E(Dot); };
1615   }
1616 
1617   // Built-in functions are parsed here.
1618   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1619   if (Tok == "ADDR") {
1620     StringRef Name = readParenLiteral();
1621     return
1622         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
1623   }
1624   if (Tok == "LOADADDR") {
1625     StringRef Name = readParenLiteral();
1626     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1627   }
1628   if (Tok == "ASSERT")
1629     return readAssert();
1630   if (Tok == "ALIGN") {
1631     Expr E = readParenExpr();
1632     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1633   }
1634   if (Tok == "CONSTANT") {
1635     StringRef Name = readParenLiteral();
1636     return [=](uint64_t Dot) { return getConstant(Name); };
1637   }
1638   if (Tok == "DEFINED") {
1639     expect("(");
1640     StringRef Tok = next();
1641     expect(")");
1642     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1643   }
1644   if (Tok == "SEGMENT_START") {
1645     expect("(");
1646     skip();
1647     expect(",");
1648     Expr E = readExpr();
1649     expect(")");
1650     return [=](uint64_t Dot) { return E(Dot); };
1651   }
1652   if (Tok == "DATA_SEGMENT_ALIGN") {
1653     expect("(");
1654     Expr E = readExpr();
1655     expect(",");
1656     readExpr();
1657     expect(")");
1658     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1659   }
1660   if (Tok == "DATA_SEGMENT_END") {
1661     expect("(");
1662     expect(".");
1663     expect(")");
1664     return [](uint64_t Dot) { return Dot; };
1665   }
1666   // GNU linkers implements more complicated logic to handle
1667   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1668   // the next page boundary for simplicity.
1669   if (Tok == "DATA_SEGMENT_RELRO_END") {
1670     expect("(");
1671     readExpr();
1672     expect(",");
1673     readExpr();
1674     expect(")");
1675     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1676   }
1677   if (Tok == "SIZEOF") {
1678     StringRef Name = readParenLiteral();
1679     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
1680   }
1681   if (Tok == "ALIGNOF") {
1682     StringRef Name = readParenLiteral();
1683     return
1684         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1685   }
1686   if (Tok == "SIZEOF_HEADERS")
1687     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1688 
1689   // Tok is a literal number.
1690   uint64_t V;
1691   if (readInteger(Tok, V))
1692     return [=](uint64_t Dot) { return V; };
1693 
1694   // Tok is a symbol name.
1695   if (Tok != "." && !isValidCIdentifier(Tok))
1696     setError("malformed number: " + Tok);
1697   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1698           [=]() { return isAbsolute(Tok); }};
1699 }
1700 
1701 Expr ScriptParser::readTernary(Expr Cond) {
1702   skip();
1703   Expr L = readExpr();
1704   expect(":");
1705   Expr R = readExpr();
1706   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1707 }
1708 
1709 Expr ScriptParser::readParenExpr() {
1710   expect("(");
1711   Expr E = readExpr();
1712   expect(")");
1713   return E;
1714 }
1715 
1716 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1717   std::vector<StringRef> Phdrs;
1718   while (!Error && peek().startswith(":")) {
1719     StringRef Tok = next();
1720     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1721     if (Tok.empty()) {
1722       setError("section header name is empty");
1723       break;
1724     }
1725     Phdrs.push_back(Tok);
1726   }
1727   return Phdrs;
1728 }
1729 
1730 // Read a program header type name. The next token must be a
1731 // name of a program header type or a constant (e.g. "0x3").
1732 unsigned ScriptParser::readPhdrType() {
1733   StringRef Tok = next();
1734   uint64_t Val;
1735   if (readInteger(Tok, Val))
1736     return Val;
1737 
1738   unsigned Ret = StringSwitch<unsigned>(Tok)
1739                      .Case("PT_NULL", PT_NULL)
1740                      .Case("PT_LOAD", PT_LOAD)
1741                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1742                      .Case("PT_INTERP", PT_INTERP)
1743                      .Case("PT_NOTE", PT_NOTE)
1744                      .Case("PT_SHLIB", PT_SHLIB)
1745                      .Case("PT_PHDR", PT_PHDR)
1746                      .Case("PT_TLS", PT_TLS)
1747                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1748                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1749                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1750                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1751                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1752                      .Default(-1);
1753 
1754   if (Ret == (unsigned)-1) {
1755     setError("invalid program header type: " + Tok);
1756     return PT_NULL;
1757   }
1758   return Ret;
1759 }
1760 
1761 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1762   // Identifiers start at 2 because 0 and 1 are reserved
1763   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1764   size_t VersionId = Config->VersionDefinitions.size() + 2;
1765   Config->VersionDefinitions.push_back({VerStr, VersionId});
1766 
1767   if (consume("global:") || peek() != "local:")
1768     readGlobal(VerStr);
1769   if (consume("local:"))
1770     readLocal();
1771   expect("}");
1772 
1773   // Each version may have a parent version. For example, "Ver2" defined as
1774   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1775   // version hierarchy is, probably against your instinct, purely for human; the
1776   // runtime doesn't care about them at all. In LLD, we simply skip the token.
1777   if (!VerStr.empty() && peek() != ";")
1778     skip();
1779   expect(";");
1780 }
1781 
1782 void ScriptParser::readLocal() {
1783   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1784   expect("*");
1785   expect(";");
1786 }
1787 
1788 void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1789   expect("\"C++\"");
1790   expect("{");
1791 
1792   for (;;) {
1793     if (peek() == "}" || Error)
1794       break;
1795     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1796     Globals->push_back({unquote(next()), true, HasWildcard});
1797     expect(";");
1798   }
1799 
1800   expect("}");
1801   expect(";");
1802 }
1803 
1804 void ScriptParser::readGlobal(StringRef VerStr) {
1805   std::vector<SymbolVersion> *Globals;
1806   if (VerStr.empty())
1807     Globals = &Config->VersionScriptGlobals;
1808   else
1809     Globals = &Config->VersionDefinitions.back().Globals;
1810 
1811   for (;;) {
1812     if (consume("extern"))
1813       readExtern(Globals);
1814 
1815     StringRef Cur = peek();
1816     if (Cur == "}" || Cur == "local:" || Error)
1817       return;
1818     skip();
1819     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
1820     expect(";");
1821   }
1822 }
1823 
1824 static bool isUnderSysroot(StringRef Path) {
1825   if (Config->Sysroot == "")
1826     return false;
1827   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1828     if (sys::fs::equivalent(Config->Sysroot, Path))
1829       return true;
1830   return false;
1831 }
1832 
1833 void elf::readLinkerScript(MemoryBufferRef MB) {
1834   StringRef Path = MB.getBufferIdentifier();
1835   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1836 }
1837 
1838 void elf::readVersionScript(MemoryBufferRef MB) {
1839   ScriptParser(MB.getBuffer(), false).readVersionScript();
1840 }
1841 
1842 template class elf::LinkerScript<ELF32LE>;
1843 template class elf::LinkerScript<ELF32BE>;
1844 template class elf::LinkerScript<ELF64LE>;
1845 template class elf::LinkerScript<ELF64BE>;
1846