1 //===- LinkerScript.cpp ---------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the parser/evaluator of the linker script.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LinkerScript.h"
15 #include "Config.h"
16 #include "InputSection.h"
17 #include "Memory.h"
18 #include "OutputSections.h"
19 #include "Strings.h"
20 #include "SymbolTable.h"
21 #include "Symbols.h"
22 #include "SyntheticSections.h"
23 #include "Target.h"
24 #include "Threads.h"
25 #include "Writer.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/BinaryFormat/ELF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Endian.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Path.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstddef>
37 #include <cstdint>
38 #include <iterator>
39 #include <limits>
40 #include <string>
41 #include <vector>
42 
43 using namespace llvm;
44 using namespace llvm::ELF;
45 using namespace llvm::object;
46 using namespace llvm::support::endian;
47 using namespace lld;
48 using namespace lld::elf;
49 
50 LinkerScript *elf::Script;
51 
52 static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
53   if (OutputSection *OS = InputSec->getOutputSection())
54     return OS->Addr;
55   error(Loc + ": unable to evaluate expression: input section " +
56         InputSec->Name + " has no output section assigned");
57   return 0;
58 }
59 
60 uint64_t ExprValue::getValue() const {
61   if (Sec)
62     return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
63                    Alignment);
64   return alignTo(Val, Alignment);
65 }
66 
67 uint64_t ExprValue::getSecAddr() const {
68   if (Sec)
69     return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
70   return 0;
71 }
72 
73 uint64_t ExprValue::getSectionOffset() const {
74   return getValue() - getSecAddr();
75 }
76 
77 static SymbolBody *addRegular(SymbolAssignment *Cmd) {
78   Symbol *Sym;
79   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
80   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
81                                               /*CanOmitFromDynSym*/ false,
82                                               /*File*/ nullptr);
83   Sym->Binding = STB_GLOBAL;
84   ExprValue Value = Cmd->Expression();
85   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
86 
87   // We want to set symbol values early if we can. This allows us to use symbols
88   // as variables in linker scripts. Doing so allows us to write expressions
89   // like this: `alignment = 16; . = ALIGN(., alignment)`
90   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
91   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
92                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
93   return Sym->body();
94 }
95 
96 OutputSection *LinkerScript::createOutputSection(StringRef Name,
97                                                  StringRef Location) {
98   OutputSection *&SecRef = NameToOutputSection[Name];
99   OutputSection *Sec;
100   if (SecRef && SecRef->Location.empty()) {
101     // There was a forward reference.
102     Sec = SecRef;
103   } else {
104     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
105     if (!SecRef)
106       SecRef = Sec;
107   }
108   Sec->Location = Location;
109   return Sec;
110 }
111 
112 OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
113   OutputSection *&CmdRef = NameToOutputSection[Name];
114   if (!CmdRef)
115     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
116   return CmdRef;
117 }
118 
119 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
120   uint64_t Val = E().getValue();
121   if (Val < Dot && InSec)
122     error(Loc + ": unable to move location counter backward for: " +
123           CurAddressState->OutSec->Name);
124   Dot = Val;
125   // Update to location counter means update to section size.
126   if (InSec)
127     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
128 }
129 
130 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
131 // symbols, whose value is an offset from beginning of section and regular
132 // symbols whose value is absolute.
133 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
134   if (Cmd->Name == ".") {
135     setDot(Cmd->Expression, Cmd->Location, InSec);
136     return;
137   }
138 
139   if (!Cmd->Sym)
140     return;
141 
142   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
143   ExprValue V = Cmd->Expression();
144   if (V.isAbsolute()) {
145     Sym->Value = V.getValue();
146   } else {
147     Sym->Section = V.Sec;
148     Sym->Value = V.getSectionOffset();
149   }
150 }
151 
152 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
153   if (Cmd->Name == ".")
154     return;
155 
156   // If a symbol was in PROVIDE(), we need to define it only when
157   // it is a referenced undefined symbol.
158   SymbolBody *B = Symtab->find(Cmd->Name);
159   if (Cmd->Provide && (!B || B->isDefined()))
160     return;
161 
162   Cmd->Sym = addRegular(Cmd);
163 }
164 
165 bool SymbolAssignment::classof(const BaseCommand *C) {
166   return C->Kind == AssignmentKind;
167 }
168 
169 bool InputSectionDescription::classof(const BaseCommand *C) {
170   return C->Kind == InputSectionKind;
171 }
172 
173 bool AssertCommand::classof(const BaseCommand *C) {
174   return C->Kind == AssertKind;
175 }
176 
177 bool BytesDataCommand::classof(const BaseCommand *C) {
178   return C->Kind == BytesDataKind;
179 }
180 
181 static std::string filename(InputFile *File) {
182   if (!File)
183     return "";
184   if (File->ArchiveName.empty())
185     return File->getName();
186   return (File->ArchiveName + "(" + File->getName() + ")").str();
187 }
188 
189 bool LinkerScript::shouldKeep(InputSectionBase *S) {
190   for (InputSectionDescription *ID : Opt.KeptSections) {
191     std::string Filename = filename(S->File);
192     if (ID->FilePat.match(Filename))
193       for (SectionPattern &P : ID->SectionPatterns)
194         if (P.SectionPat.match(S->Name))
195           return true;
196   }
197   return false;
198 }
199 
200 // A helper function for the SORT() command.
201 static std::function<bool(InputSectionBase *, InputSectionBase *)>
202 getComparator(SortSectionPolicy K) {
203   switch (K) {
204   case SortSectionPolicy::Alignment:
205     return [](InputSectionBase *A, InputSectionBase *B) {
206       // ">" is not a mistake. Sections with larger alignments are placed
207       // before sections with smaller alignments in order to reduce the
208       // amount of padding necessary. This is compatible with GNU.
209       return A->Alignment > B->Alignment;
210     };
211   case SortSectionPolicy::Name:
212     return [](InputSectionBase *A, InputSectionBase *B) {
213       return A->Name < B->Name;
214     };
215   case SortSectionPolicy::Priority:
216     return [](InputSectionBase *A, InputSectionBase *B) {
217       return getPriority(A->Name) < getPriority(B->Name);
218     };
219   default:
220     llvm_unreachable("unknown sort policy");
221   }
222 }
223 
224 // A helper function for the SORT() command.
225 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
226                              ConstraintKind Kind) {
227   if (Kind == ConstraintKind::NoConstraint)
228     return true;
229 
230   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
231     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
232   });
233 
234   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
235          (!IsRW && Kind == ConstraintKind::ReadOnly);
236 }
237 
238 static void sortSections(InputSection **Begin, InputSection **End,
239                          SortSectionPolicy K) {
240   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
241     std::stable_sort(Begin, End, getComparator(K));
242 }
243 
244 static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
245   if (Config->SymbolOrderingFile.empty())
246     return;
247   static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder();
248   MutableArrayRef<InputSection *> In(Begin, End - Begin);
249   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
250 }
251 
252 // Compute and remember which sections the InputSectionDescription matches.
253 std::vector<InputSection *>
254 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
255   std::vector<InputSection *> Ret;
256 
257   // Collects all sections that satisfy constraints of Cmd.
258   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
259     size_t SizeBefore = Ret.size();
260 
261     for (InputSectionBase *Sec : InputSections) {
262       if (Sec->Assigned)
263         continue;
264 
265       if (!Sec->Live) {
266         reportDiscarded(Sec);
267         continue;
268       }
269 
270       // For -emit-relocs we have to ignore entries like
271       //   .rela.dyn : { *(.rela.data) }
272       // which are common because they are in the default bfd script.
273       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
274         continue;
275 
276       std::string Filename = filename(Sec->File);
277       if (!Cmd->FilePat.match(Filename) ||
278           Pat.ExcludedFilePat.match(Filename) ||
279           !Pat.SectionPat.match(Sec->Name))
280         continue;
281 
282       Ret.push_back(cast<InputSection>(Sec));
283       Sec->Assigned = true;
284     }
285 
286     // Sort sections as instructed by SORT-family commands and --sort-section
287     // option. Because SORT-family commands can be nested at most two depth
288     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
289     // line option is respected even if a SORT command is given, the exact
290     // behavior we have here is a bit complicated. Here are the rules.
291     //
292     // 1. If two SORT commands are given, --sort-section is ignored.
293     // 2. If one SORT command is given, and if it is not SORT_NONE,
294     //    --sort-section is handled as an inner SORT command.
295     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
296     // 4. If no SORT command is given, sort according to --sort-section.
297     // 5. If no SORT commands are given and --sort-section is not specified,
298     //    apply sorting provided by --symbol-ordering-file if any exist.
299     InputSection **Begin = Ret.data() + SizeBefore;
300     InputSection **End = Ret.data() + Ret.size();
301     if (Pat.SortOuter == SortSectionPolicy::Default &&
302         Config->SortSection == SortSectionPolicy::Default) {
303       sortBySymbolOrder(Begin, End);
304       continue;
305     }
306     if (Pat.SortOuter != SortSectionPolicy::None) {
307       if (Pat.SortInner == SortSectionPolicy::Default)
308         sortSections(Begin, End, Config->SortSection);
309       else
310         sortSections(Begin, End, Pat.SortInner);
311       sortSections(Begin, End, Pat.SortOuter);
312     }
313   }
314   return Ret;
315 }
316 
317 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
318   for (InputSectionBase *S : V) {
319     S->Live = false;
320     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
321         S == InX::DynStrTab)
322       error("discarding " + S->Name + " section is not allowed");
323     discard(S->DependentSections);
324   }
325 }
326 
327 std::vector<InputSectionBase *>
328 LinkerScript::createInputSectionList(OutputSection &OutCmd) {
329   std::vector<InputSectionBase *> Ret;
330 
331   for (BaseCommand *Base : OutCmd.Commands) {
332     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
333     if (!Cmd)
334       continue;
335 
336     Cmd->Sections = computeInputSections(Cmd);
337     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
338   }
339 
340   return Ret;
341 }
342 
343 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
344   // A symbol can be assigned before any section is mentioned in the linker
345   // script. In an DSO, the symbol values are addresses, so the only important
346   // section values are:
347   // * SHN_UNDEF
348   // * SHN_ABS
349   // * Any value meaning a regular section.
350   // To handle that, create a dummy aether section that fills the void before
351   // the linker scripts switches to another section. It has an index of one
352   // which will map to whatever the first actual section is.
353   Aether = make<OutputSection>("", 0, SHF_ALLOC);
354   Aether->SectionIndex = 1;
355   auto State = make_unique<AddressState>(Opt);
356   // CurAddressState captures the local AddressState and makes it accessible
357   // deliberately. This is needed as there are some cases where we cannot just
358   // thread the current state through to a lambda function created by the
359   // script parser.
360   CurAddressState = State.get();
361   CurAddressState->OutSec = Aether;
362   Dot = 0;
363 
364   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
365     // Handle symbol assignments outside of any output section.
366     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
367       addSymbol(Cmd);
368       continue;
369     }
370 
371     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
372       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
373 
374       // The output section name `/DISCARD/' is special.
375       // Any input section assigned to it is discarded.
376       if (Sec->Name == "/DISCARD/") {
377         discard(V);
378         continue;
379       }
380 
381       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
382       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
383       // sections satisfy a given constraint. If not, a directive is handled
384       // as if it wasn't present from the beginning.
385       //
386       // Because we'll iterate over Commands many more times, the easiest
387       // way to "make it as if it wasn't present" is to just remove it.
388       if (!matchConstraints(V, Sec->Constraint)) {
389         for (InputSectionBase *S : V)
390           S->Assigned = false;
391         Opt.Commands.erase(Opt.Commands.begin() + I);
392         --I;
393         continue;
394       }
395 
396       // A directive may contain symbol definitions like this:
397       // ".foo : { ...; bar = .; }". Handle them.
398       for (BaseCommand *Base : Sec->Commands)
399         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
400           addSymbol(OutCmd);
401 
402       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
403       // is given, input sections are aligned to that value, whether the
404       // given value is larger or smaller than the original section alignment.
405       if (Sec->SubalignExpr) {
406         uint32_t Subalign = Sec->SubalignExpr().getValue();
407         for (InputSectionBase *S : V)
408           S->Alignment = Subalign;
409       }
410 
411       // Add input sections to an output section.
412       for (InputSectionBase *S : V)
413         Factory.addInputSec(S, Sec->Name, Sec);
414       assert(Sec->SectionIndex == INT_MAX);
415       Sec->SectionIndex = I;
416       if (Sec->Noload)
417         Sec->Type = SHT_NOBITS;
418     }
419   }
420   CurAddressState = nullptr;
421 }
422 
423 void LinkerScript::fabricateDefaultCommands() {
424   // Define start address
425   uint64_t StartAddr = -1;
426 
427   // The Sections with -T<section> have been sorted in order of ascending
428   // address. We must lower StartAddr if the lowest -T<section address> as
429   // calls to setDot() must be monotonically increasing.
430   for (auto &KV : Config->SectionStartMap)
431     StartAddr = std::min(StartAddr, KV.second);
432 
433   Opt.Commands.insert(Opt.Commands.begin(),
434                       make<SymbolAssignment>(".",
435                                              [=] {
436                                                return std::min(
437                                                    StartAddr,
438                                                    Config->ImageBase +
439                                                        elf::getHeaderSize());
440                                              },
441                                              ""));
442 }
443 
444 // Add sections that didn't match any sections command.
445 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
446   unsigned NumCommands = Opt.Commands.size();
447   for (InputSectionBase *S : InputSections) {
448     if (!S->Live || S->Parent)
449       continue;
450     StringRef Name = getOutputSectionName(S->Name);
451     auto End = Opt.Commands.begin() + NumCommands;
452     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
453       if (auto *Sec = dyn_cast<OutputSection>(Base))
454         return Sec->Name == Name;
455       return false;
456     });
457     if (I == End) {
458       Factory.addInputSec(S, Name);
459       assert(S->getOutputSection()->SectionIndex == INT_MAX);
460     } else {
461       OutputSection *Sec = cast<OutputSection>(*I);
462       Factory.addInputSec(S, Name, Sec);
463       unsigned Index = std::distance(Opt.Commands.begin(), I);
464       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
465       Sec->SectionIndex = Index;
466     }
467   }
468 }
469 
470 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
471   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
472                 CurAddressState->OutSec->Type == SHT_NOBITS;
473   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
474   Start = alignTo(Start, Align);
475   uint64_t End = Start + Size;
476 
477   if (IsTbss)
478     CurAddressState->ThreadBssOffset = End - Dot;
479   else
480     Dot = End;
481   return End;
482 }
483 
484 void LinkerScript::output(InputSection *S) {
485   uint64_t Before = advance(0, 1);
486   uint64_t Pos = advance(S->getSize(), S->Alignment);
487   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
488 
489   // Update output section size after adding each section. This is so that
490   // SIZEOF works correctly in the case below:
491   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
492   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
493 
494   // If there is a memory region associated with this input section, then
495   // place the section in that region and update the region index.
496   if (CurAddressState->MemRegion) {
497     uint64_t &CurOffset =
498         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
499     CurOffset += Pos - Before;
500     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
501     if (CurSize > CurAddressState->MemRegion->Length) {
502       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
503       error("section '" + CurAddressState->OutSec->Name +
504             "' will not fit in region '" + CurAddressState->MemRegion->Name +
505             "': overflowed by " + Twine(OverflowAmt) + " bytes");
506     }
507   }
508 }
509 
510 void LinkerScript::switchTo(OutputSection *Sec) {
511   if (CurAddressState->OutSec == Sec)
512     return;
513 
514   CurAddressState->OutSec = Sec;
515   CurAddressState->OutSec->Addr =
516       advance(0, CurAddressState->OutSec->Alignment);
517 
518   // If neither AT nor AT> is specified for an allocatable section, the linker
519   // will set the LMA such that the difference between VMA and LMA for the
520   // section is the same as the preceding output section in the same region
521   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
522   if (CurAddressState->LMAOffset)
523     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
524 }
525 
526 void LinkerScript::process(BaseCommand &Base) {
527   // This handles the assignments to symbol or to the dot.
528   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
529     assignSymbol(Cmd, true);
530     return;
531   }
532 
533   // Handle BYTE(), SHORT(), LONG(), or QUAD().
534   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
535     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
536     Dot += Cmd->Size;
537     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
538     return;
539   }
540 
541   // Handle ASSERT().
542   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
543     Cmd->Expression();
544     return;
545   }
546 
547   // Handle a single input section description command.
548   // It calculates and assigns the offsets for each section and also
549   // updates the output section size.
550   auto &Cmd = cast<InputSectionDescription>(Base);
551   for (InputSection *Sec : Cmd.Sections) {
552     // We tentatively added all synthetic sections at the beginning and removed
553     // empty ones afterwards (because there is no way to know whether they were
554     // going be empty or not other than actually running linker scripts.)
555     // We need to ignore remains of empty sections.
556     if (auto *S = dyn_cast<SyntheticSection>(Sec))
557       if (S->empty())
558         continue;
559 
560     if (!Sec->Live)
561       continue;
562     assert(CurAddressState->OutSec == Sec->getParent());
563     output(Sec);
564   }
565 }
566 
567 // This function searches for a memory region to place the given output
568 // section in. If found, a pointer to the appropriate memory region is
569 // returned. Otherwise, a nullptr is returned.
570 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
571   // If a memory region name was specified in the output section command,
572   // then try to find that region first.
573   if (!Sec->MemoryRegionName.empty()) {
574     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
575     if (It != Opt.MemoryRegions.end())
576       return It->second;
577     error("memory region '" + Sec->MemoryRegionName + "' not declared");
578     return nullptr;
579   }
580 
581   // If at least one memory region is defined, all sections must
582   // belong to some memory region. Otherwise, we don't need to do
583   // anything for memory regions.
584   if (Opt.MemoryRegions.empty())
585     return nullptr;
586 
587   // See if a region can be found by matching section flags.
588   for (auto &Pair : Opt.MemoryRegions) {
589     MemoryRegion *M = Pair.second;
590     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
591       return M;
592   }
593 
594   // Otherwise, no suitable region was found.
595   if (Sec->Flags & SHF_ALLOC)
596     error("no memory region specified for section '" + Sec->Name + "'");
597   return nullptr;
598 }
599 
600 // This function assigns offsets to input sections and an output section
601 // for a single sections command (e.g. ".text { *(.text); }").
602 void LinkerScript::assignOffsets(OutputSection *Sec) {
603   if (!(Sec->Flags & SHF_ALLOC))
604     Dot = 0;
605   else if (Sec->AddrExpr)
606     setDot(Sec->AddrExpr, Sec->Location, false);
607 
608   CurAddressState->MemRegion = Sec->MemRegion;
609   if (CurAddressState->MemRegion)
610     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
611 
612   if (Sec->LMAExpr) {
613     uint64_t D = Dot;
614     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
615   }
616 
617   switchTo(Sec);
618 
619   // We do not support custom layout for compressed debug sectons.
620   // At this point we already know their size and have compressed content.
621   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
622     return;
623 
624   for (BaseCommand *C : Sec->Commands)
625     process(*C);
626 }
627 
628 void LinkerScript::removeEmptyCommands() {
629   // It is common practice to use very generic linker scripts. So for any
630   // given run some of the output sections in the script will be empty.
631   // We could create corresponding empty output sections, but that would
632   // clutter the output.
633   // We instead remove trivially empty sections. The bfd linker seems even
634   // more aggressive at removing them.
635   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
636     if (auto *Sec = dyn_cast<OutputSection>(Base))
637       return !Sec->Live;
638     return false;
639   });
640 }
641 
642 static bool isAllSectionDescription(const OutputSection &Cmd) {
643   for (BaseCommand *Base : Cmd.Commands)
644     if (!isa<InputSectionDescription>(*Base))
645       return false;
646   return true;
647 }
648 
649 void LinkerScript::adjustSectionsBeforeSorting() {
650   // If the output section contains only symbol assignments, create a
651   // corresponding output section. The bfd linker seems to only create them if
652   // '.' is assigned to, but creating these section should not have any bad
653   // consequeces and gives us a section to put the symbol in.
654   uint64_t Flags = SHF_ALLOC;
655 
656   for (BaseCommand * Cmd : Opt.Commands) {
657     auto *Sec = dyn_cast<OutputSection>(Cmd);
658     if (!Sec)
659       continue;
660     if (Sec->Live) {
661       Flags = Sec->Flags;
662       continue;
663     }
664 
665     if (isAllSectionDescription(*Sec))
666       continue;
667 
668     Sec->Live = true;
669     Sec->Flags = Flags;
670   }
671 }
672 
673 void LinkerScript::adjustSectionsAfterSorting() {
674   // Try and find an appropriate memory region to assign offsets in.
675   for (BaseCommand *Base : Opt.Commands) {
676     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
677       Sec->MemRegion = findMemoryRegion(Sec);
678       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
679       if (Sec->AlignExpr)
680         Sec->updateAlignment(Sec->AlignExpr().getValue());
681     }
682   }
683 
684   // If output section command doesn't specify any segments,
685   // and we haven't previously assigned any section to segment,
686   // then we simply assign section to the very first load segment.
687   // Below is an example of such linker script:
688   // PHDRS { seg PT_LOAD; }
689   // SECTIONS { .aaa : { *(.aaa) } }
690   std::vector<StringRef> DefPhdrs;
691   auto FirstPtLoad =
692       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
693                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
694   if (FirstPtLoad != Opt.PhdrsCommands.end())
695     DefPhdrs.push_back(FirstPtLoad->Name);
696 
697   // Walk the commands and propagate the program headers to commands that don't
698   // explicitly specify them.
699   for (BaseCommand *Base : Opt.Commands) {
700     auto *Sec = dyn_cast<OutputSection>(Base);
701     if (!Sec)
702       continue;
703 
704     if (Sec->Phdrs.empty()) {
705       // To match the bfd linker script behaviour, only propagate program
706       // headers to sections that are allocated.
707       if (Sec->Flags & SHF_ALLOC)
708         Sec->Phdrs = DefPhdrs;
709     } else {
710       DefPhdrs = Sec->Phdrs;
711     }
712   }
713 
714   removeEmptyCommands();
715 }
716 
717 static OutputSection *findFirstSection(PhdrEntry *Load) {
718   for (OutputSection *Sec : OutputSections)
719     if (Sec->PtLoad == Load)
720       return Sec;
721   return nullptr;
722 }
723 
724 // Try to find an address for the file and program headers output sections,
725 // which were unconditionally added to the first PT_LOAD segment earlier.
726 //
727 // When using the default layout, we check if the headers fit below the first
728 // allocated section. When using a linker script, we also check if the headers
729 // are covered by the output section. This allows omitting the headers by not
730 // leaving enough space for them in the linker script; this pattern is common
731 // in embedded systems.
732 //
733 // If there isn't enough space for these sections, we'll remove them from the
734 // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
735 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
736   uint64_t Min = std::numeric_limits<uint64_t>::max();
737   for (OutputSection *Sec : OutputSections)
738     if (Sec->Flags & SHF_ALLOC)
739       Min = std::min<uint64_t>(Min, Sec->Addr);
740 
741   auto It = llvm::find_if(
742       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
743   if (It == Phdrs.end())
744     return;
745   PhdrEntry *FirstPTLoad = *It;
746 
747   uint64_t HeaderSize = getHeaderSize();
748   // When linker script with SECTIONS is being used, don't output headers
749   // unless there's a space for them.
750   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
751   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
752     Min = Opt.HasSections ? Base
753                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
754     Out::ElfHeader->Addr = Min;
755     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
756     return;
757   }
758 
759   Out::ElfHeader->PtLoad = nullptr;
760   Out::ProgramHeaders->PtLoad = nullptr;
761   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
762 
763   llvm::erase_if(Phdrs,
764                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
765 }
766 
767 LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
768   for (auto &MRI : Opt.MemoryRegions) {
769     const MemoryRegion *MR = MRI.second;
770     MemRegionOffset[MR] = MR->Origin;
771   }
772 }
773 
774 void LinkerScript::assignAddresses() {
775   // Assign addresses as instructed by linker script SECTIONS sub-commands.
776   Dot = 0;
777   auto State = make_unique<AddressState>(Opt);
778   // CurAddressState captures the local AddressState and makes it accessible
779   // deliberately. This is needed as there are some cases where we cannot just
780   // thread the current state through to a lambda function created by the
781   // script parser.
782   CurAddressState = State.get();
783   ErrorOnMissingSection = true;
784   switchTo(Aether);
785 
786   for (BaseCommand *Base : Opt.Commands) {
787     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
788       assignSymbol(Cmd, false);
789       continue;
790     }
791 
792     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
793       Cmd->Expression();
794       continue;
795     }
796 
797     assignOffsets(cast<OutputSection>(Base));
798   }
799   CurAddressState = nullptr;
800 }
801 
802 // Creates program headers as instructed by PHDRS linker script command.
803 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
804   std::vector<PhdrEntry *> Ret;
805 
806   // Process PHDRS and FILEHDR keywords because they are not
807   // real output sections and cannot be added in the following loop.
808   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
809     PhdrEntry *Phdr =
810         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
811 
812     if (Cmd.HasFilehdr)
813       Phdr->add(Out::ElfHeader);
814     if (Cmd.HasPhdrs)
815       Phdr->add(Out::ProgramHeaders);
816 
817     if (Cmd.LMAExpr) {
818       Phdr->p_paddr = Cmd.LMAExpr().getValue();
819       Phdr->HasLMA = true;
820     }
821     Ret.push_back(Phdr);
822   }
823 
824   // Add output sections to program headers.
825   for (OutputSection *Sec : OutputSections) {
826     // Assign headers specified by linker script
827     for (size_t Id : getPhdrIndices(Sec)) {
828       Ret[Id]->add(Sec);
829       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
830         Ret[Id]->p_flags |= Sec->getPhdrFlags();
831     }
832   }
833   return Ret;
834 }
835 
836 bool LinkerScript::ignoreInterpSection() {
837   // Ignore .interp section in case we have PHDRS specification
838   // and PT_INTERP isn't listed.
839   if (Opt.PhdrsCommands.empty())
840     return false;
841   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
842     if (Cmd.Type == PT_INTERP)
843       return false;
844   return true;
845 }
846 
847 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
848   if (S == ".") {
849     if (CurAddressState)
850       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
851               Loc};
852     error(Loc + ": unable to get location counter value");
853     return 0;
854   }
855   if (SymbolBody *B = Symtab->find(S)) {
856     if (auto *D = dyn_cast<DefinedRegular>(B))
857       return {D->Section, D->Value, Loc};
858     if (auto *C = dyn_cast<DefinedCommon>(B))
859       return {C->Section, 0, Loc};
860   }
861   error(Loc + ": symbol not found: " + S);
862   return 0;
863 }
864 
865 bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
866 
867 static const size_t NoPhdr = -1;
868 
869 // Returns indices of ELF headers containing specific section. Each index is a
870 // zero based number of ELF header listed within PHDRS {} script block.
871 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
872   std::vector<size_t> Ret;
873   for (StringRef PhdrName : Cmd->Phdrs) {
874     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
875     if (Index != NoPhdr)
876       Ret.push_back(Index);
877   }
878   return Ret;
879 }
880 
881 // Returns the index of the segment named PhdrName if found otherwise
882 // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
883 // (which can be used to explicitly specify that a section isn't assigned to a
884 // segment) then error.
885 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
886   size_t I = 0;
887   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
888     if (Cmd.Name == PhdrName)
889       return I;
890     ++I;
891   }
892   if (PhdrName != "NONE")
893     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
894   return NoPhdr;
895 }
896