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