1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===//
2f7c5fbb1SRui Ueyama //
3f7c5fbb1SRui Ueyama //                             The LLVM Linker
4f7c5fbb1SRui Ueyama //
5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source
6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details.
7f7c5fbb1SRui Ueyama //
8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
9f7c5fbb1SRui Ueyama //
10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script.
11f7c5fbb1SRui Ueyama //
12f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
13f7c5fbb1SRui Ueyama 
14717677afSRui Ueyama #include "LinkerScript.h"
15f7c5fbb1SRui Ueyama #include "Config.h"
161ebc8ed7SRui Ueyama #include "InputSection.h"
179381eb10SRui Ueyama #include "Memory.h"
18652852c5SGeorge Rimar #include "OutputSections.h"
1993c9af42SRui Ueyama #include "Strings.h"
20f7c5fbb1SRui Ueyama #include "SymbolTable.h"
2155518e7dSRui Ueyama #include "Symbols.h"
223fb5a6dcSGeorge Rimar #include "SyntheticSections.h"
2355b169bfSRafael Espindola #include "Target.h"
2455b169bfSRafael Espindola #include "Threads.h"
25bbe38602SEugene Leviant #include "Writer.h"
2622886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h"
2722886a28SEugene Zelenko #include "llvm/ADT/StringRef.h"
28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
2922886a28SEugene Zelenko #include "llvm/Support/Casting.h"
3022886a28SEugene Zelenko #include "llvm/Support/Endian.h"
3122886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
32f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
33f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
3422886a28SEugene Zelenko #include <algorithm>
3522886a28SEugene Zelenko #include <cassert>
3622886a28SEugene Zelenko #include <cstddef>
3722886a28SEugene Zelenko #include <cstdint>
3822886a28SEugene Zelenko #include <iterator>
3922886a28SEugene Zelenko #include <limits>
4022886a28SEugene Zelenko #include <string>
4122886a28SEugene Zelenko #include <vector>
42f7c5fbb1SRui Ueyama 
43f7c5fbb1SRui Ueyama using namespace llvm;
44652852c5SGeorge Rimar using namespace llvm::ELF;
451ebc8ed7SRui Ueyama using namespace llvm::object;
46e38cbab5SGeorge Rimar using namespace llvm::support::endian;
47f7c5fbb1SRui Ueyama using namespace lld;
48e0df00b9SRafael Espindola using namespace lld::elf;
49f7c5fbb1SRui Ueyama 
50a34da938SRui Ueyama LinkerScript *elf::Script;
51a34da938SRui Ueyama 
525d0ea70aSGeorge Rimar static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
535d0ea70aSGeorge Rimar   if (OutputSection *OS = InputSec->getOutputSection())
545d0ea70aSGeorge Rimar     return OS->Addr;
555d0ea70aSGeorge Rimar   error(Loc + ": unable to evaluate expression: input section " +
565d0ea70aSGeorge Rimar         InputSec->Name + " has no output section assigned");
575d0ea70aSGeorge Rimar   return 0;
58608cf670SGeorge Rimar }
595d0ea70aSGeorge Rimar 
605d0ea70aSGeorge Rimar uint64_t ExprValue::getValue() const {
615d0ea70aSGeorge Rimar   if (Sec)
625d0ea70aSGeorge Rimar     return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
635d0ea70aSGeorge Rimar                    Alignment);
643c6de1a6SPetr Hosek   return alignTo(Val, Alignment);
6572dc195dSRafael Espindola }
6672dc195dSRafael Espindola 
677ba5f47eSRafael Espindola uint64_t ExprValue::getSecAddr() const {
687ba5f47eSRafael Espindola   if (Sec)
695d0ea70aSGeorge Rimar     return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
707ba5f47eSRafael Espindola   return 0;
717ba5f47eSRafael Espindola }
727ba5f47eSRafael Espindola 
73a6acd23cSRafael Espindola uint64_t ExprValue::getSectionOffset() const {
748b250344SRafael Espindola   // If the alignment is trivial, we don't have to compute the full
758b250344SRafael Espindola   // value to know the offset. This allows this function to succeed in
768b250344SRafael Espindola   // cases where the output section is not yet known.
778b250344SRafael Espindola   if (Alignment == 1)
788b250344SRafael Espindola     return Val;
79a6acd23cSRafael Espindola   return getValue() - getSecAddr();
80a6acd23cSRafael Espindola }
81a6acd23cSRafael Espindola 
82a5e8dd35SRafael Espindola static SymbolBody *addRegular(SymbolAssignment *Cmd) {
835e51f7d2SPetr Hosek   Symbol *Sym;
843dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
85244ef981SRafael Espindola   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
86244ef981SRafael Espindola                                               /*CanOmitFromDynSym*/ false,
875e51f7d2SPetr Hosek                                               /*File*/ nullptr);
885e51f7d2SPetr Hosek   Sym->Binding = STB_GLOBAL;
8972dc195dSRafael Espindola   ExprValue Value = Cmd->Expression();
9072dc195dSRafael Espindola   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
9101aa795fSGeorge Rimar 
9201aa795fSGeorge Rimar   // We want to set symbol values early if we can. This allows us to use symbols
9301aa795fSGeorge Rimar   // as variables in linker scripts. Doing so allows us to write expressions
9401aa795fSGeorge Rimar   // like this: `alignment = 16; . = ALIGN(., alignment)`
95e4bad83eSRafael Espindola   uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
966e93d054SRafael Espindola   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
976e93d054SRafael Espindola                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
988f1f3c40SMeador Inge   return Sym->body();
99ceabe80eSEugene Leviant }
100ceabe80eSEugene Leviant 
1018c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
1028c022ca7SRafael Espindola                                                  StringRef Location) {
1038c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
1048c022ca7SRafael Espindola   OutputSection *Sec;
1058c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
10605c4f67cSRafael Espindola     // There was a forward reference.
1078c022ca7SRafael Espindola     Sec = SecRef;
10805c4f67cSRafael Espindola   } else {
1098c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
1108c022ca7SRafael Espindola     if (!SecRef)
1118c022ca7SRafael Espindola       SecRef = Sec;
11205c4f67cSRafael Espindola   }
1138c022ca7SRafael Espindola   Sec->Location = Location;
1148c022ca7SRafael Espindola   return Sec;
115851dc1e8SGeorge Rimar }
116851dc1e8SGeorge Rimar 
1178c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
1188c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
11905c4f67cSRafael Espindola   if (!CmdRef)
1208c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
12105c4f67cSRafael Espindola   return CmdRef;
122d83ce1b4SGeorge Rimar }
123d83ce1b4SGeorge Rimar 
124b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
12572dc195dSRafael Espindola   uint64_t Val = E().getValue();
1268c804d97SGeorge Rimar   if (Val < Dot && InSec)
1272ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
128906e9a18SPeter Smith           CurAddressState->OutSec->Name);
1294cd7352cSRafael Espindola   Dot = Val;
1304cd7352cSRafael Espindola   // Update to location counter means update to section size.
1314cd7352cSRafael Espindola   if (InSec)
132906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
133679828ffSRafael Espindola }
134679828ffSRafael Espindola 
135679828ffSRafael Espindola // Sets value of a symbol. Two kinds of symbols are processed: synthetic
136679828ffSRafael Espindola // symbols, whose value is an offset from beginning of section and regular
137679828ffSRafael Espindola // symbols whose value is absolute.
138b8dd23f5SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
139679828ffSRafael Espindola   if (Cmd->Name == ".") {
1402ee2d2dcSGeorge Rimar     setDot(Cmd->Expression, Cmd->Location, InSec);
1414cd7352cSRafael Espindola     return;
1424cd7352cSRafael Espindola   }
1434cd7352cSRafael Espindola 
144b2b70975SGeorge Rimar   if (!Cmd->Sym)
1458f1f3c40SMeador Inge     return;
1468f1f3c40SMeador Inge 
1475616adf6SRafael Espindola   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
14872dc195dSRafael Espindola   ExprValue V = Cmd->Expression();
14972dc195dSRafael Espindola   if (V.isAbsolute()) {
15072dc195dSRafael Espindola     Sym->Value = V.getValue();
1519be24cf5SRafael Espindola     Sym->Section = nullptr;
15272dc195dSRafael Espindola   } else {
15372dc195dSRafael Espindola     Sym->Section = V.Sec;
154a6acd23cSRafael Espindola     Sym->Value = V.getSectionOffset();
155ea590d91SRafael Espindola   }
1568f1f3c40SMeador Inge }
1578f1f3c40SMeador Inge 
158b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1591602421cSRui Ueyama   if (Cmd->Name == ".")
1608f1f3c40SMeador Inge     return;
1618f1f3c40SMeador Inge 
1628f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1638f1f3c40SMeador Inge   // it is a referenced undefined symbol.
164244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1658f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1668f1f3c40SMeador Inge     return;
1678f1f3c40SMeador Inge 
168a5e8dd35SRafael Espindola   Cmd->Sym = addRegular(Cmd);
169ceabe80eSEugene Leviant }
170ceabe80eSEugene Leviant 
171076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
172076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
173076fe157SGeorge Rimar }
174076fe157SGeorge Rimar 
175eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
176eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
177eea3114fSGeorge Rimar }
178eea3114fSGeorge Rimar 
179eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
180eefa758eSGeorge Rimar   return C->Kind == AssertKind;
181eefa758eSGeorge Rimar }
182eefa758eSGeorge Rimar 
183e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
184e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
185e38cbab5SGeorge Rimar }
186e38cbab5SGeorge Rimar 
1871e30f07cSDmitry Mikulin static std::string filename(InputFile *File) {
1881e30f07cSDmitry Mikulin   if (!File)
189e0be2901SRui Ueyama     return "";
1901e30f07cSDmitry Mikulin   if (File->ArchiveName.empty())
1911e30f07cSDmitry Mikulin     return File->getName();
1921e30f07cSDmitry Mikulin   return (File->ArchiveName + "(" + File->getName() + ")").str();
193e0be2901SRui Ueyama }
194e0be2901SRui Ueyama 
195b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
196f300ca21SDmitry Mikulin   for (InputSectionDescription *ID : Opt.KeptSections) {
1971e30f07cSDmitry Mikulin     std::string Filename = filename(S->File);
198f300ca21SDmitry Mikulin     if (ID->FilePat.match(Filename))
199cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
200f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
201eea3114fSGeorge Rimar           return true;
202f300ca21SDmitry Mikulin   }
203eea3114fSGeorge Rimar   return false;
204eea3114fSGeorge Rimar }
205eea3114fSGeorge Rimar 
206ea93fe00SRui Ueyama // A helper function for the SORT() command.
207c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
208be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
209be394db3SGeorge Rimar   switch (K) {
210be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
211ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
212ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
213ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
214ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
215ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
216ea93fe00SRui Ueyama     };
217be394db3SGeorge Rimar   case SortSectionPolicy::Name:
218ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
219ea93fe00SRui Ueyama       return A->Name < B->Name;
220ea93fe00SRui Ueyama     };
221be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
222ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
223ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
224ea93fe00SRui Ueyama     };
225be394db3SGeorge Rimar   default:
226be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
227be394db3SGeorge Rimar   }
228742c3836SRui Ueyama }
2290702c4e8SGeorge Rimar 
230ea93fe00SRui Ueyama // A helper function for the SORT() command.
231b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
23206ae6836SGeorge Rimar                              ConstraintKind Kind) {
2338f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2348f66df92SGeorge Rimar     return true;
2352c7171bfSRui Ueyama 
2362c7171bfSRui Ueyama   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
2372c7171bfSRui Ueyama     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
23806ae6836SGeorge Rimar   });
2392c7171bfSRui Ueyama 
240e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
241e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
24206ae6836SGeorge Rimar }
24306ae6836SGeorge Rimar 
2446a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End,
245ee924709SRui Ueyama                          SortSectionPolicy K) {
246ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
24707171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
248ee924709SRui Ueyama }
249ee924709SRui Ueyama 
250d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
251d6bcde38SGeorge Rimar   if (Config->SymbolOrderingFile.empty())
252d6bcde38SGeorge Rimar     return;
253696a7f9aSGeorge Rimar   static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder();
254d6bcde38SGeorge Rimar   MutableArrayRef<InputSection *> In(Begin, End - Begin);
255d6bcde38SGeorge Rimar   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
256d6bcde38SGeorge Rimar }
257d6bcde38SGeorge Rimar 
258d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2596a1aa8d9SRafael Espindola std::vector<InputSection *>
26072e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2616a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2628c6a5aafSRui Ueyama 
26372e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
26472e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
26572e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
26672e107f3SRui Ueyama 
26772e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
26872e107f3SRui Ueyama       if (Sec->Assigned)
2698c6a5aafSRui Ueyama         continue;
27072e107f3SRui Ueyama 
271e39709b2SRafael Espindola       if (!Sec->Live) {
272e39709b2SRafael Espindola         reportDiscarded(Sec);
273e39709b2SRafael Espindola         continue;
274e39709b2SRafael Espindola       }
275e39709b2SRafael Espindola 
276908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
277908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
278908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
27972e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
280908a3d34SRafael Espindola         continue;
2818c6a5aafSRui Ueyama 
2821e30f07cSDmitry Mikulin       std::string Filename = filename(Sec->File);
28372e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
28472e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
28572e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
286e0be2901SRui Ueyama         continue;
28772e107f3SRui Ueyama 
2886a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
28972e107f3SRui Ueyama       Sec->Assigned = true;
290f94efdddSRui Ueyama     }
291d3190795SRafael Espindola 
292ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
293ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
294ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
295ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
296ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
297ee924709SRui Ueyama     //
298ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
299ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
300ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
301ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
302ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
303d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
304d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
3056a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
3066a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
307d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
308d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
309d6bcde38SGeorge Rimar       sortBySymbolOrder(Begin, End);
310d6bcde38SGeorge Rimar       continue;
311d6bcde38SGeorge Rimar     }
31207171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
31307171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
31407171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
315ee924709SRui Ueyama       else
31607171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
31707171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
31807171f21SGeorge Rimar     }
319ee924709SRui Ueyama   }
32072e107f3SRui Ueyama   return Ret;
321be94e1b6SRafael Espindola }
322be94e1b6SRafael Espindola 
323b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
324b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
325be94e1b6SRafael Espindola     S->Live = false;
3261e30f07cSDmitry Mikulin     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
3271e30f07cSDmitry Mikulin         S == InX::DynStrTab)
3282af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
329647c1685SGeorge Rimar     discard(S->DependentSections);
330be94e1b6SRafael Espindola   }
331be94e1b6SRafael Espindola }
332be94e1b6SRafael Espindola 
333b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3348c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
335b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
336e7f912cdSRui Ueyama 
3378f99f73cSRui Ueyama   for (BaseCommand *Base : OutCmd.Commands) {
3388f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3397c3ff2ebSRafael Espindola     if (!Cmd)
3400b9ce6a4SRui Ueyama       continue;
34172e107f3SRui Ueyama 
34272e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
343e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3440b9ce6a4SRui Ueyama   }
345e71a3f8aSRafael Espindola 
3460b9ce6a4SRui Ueyama   return Ret;
3470b9ce6a4SRui Ueyama }
3480b9ce6a4SRui Ueyama 
349b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3505616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3515616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3525616adf6SRafael Espindola   // section values are:
3535616adf6SRafael Espindola   // * SHN_UNDEF
3545616adf6SRafael Espindola   // * SHN_ABS
3555616adf6SRafael Espindola   // * Any value meaning a regular section.
3565616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3575616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3585616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3595616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3605616adf6SRafael Espindola   Aether->SectionIndex = 1;
361906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
362c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
363c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
364c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
365c1ace40bSPeter Smith   // script parser.
366906e9a18SPeter Smith   CurAddressState = State.get();
367906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
36849592cf6SRafael Espindola   Dot = 0;
3695616adf6SRafael Espindola 
37092a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3710b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
37292a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3734cd7352cSRafael Espindola       addSymbol(Cmd);
3742ab5f73dSRui Ueyama       continue;
3752ab5f73dSRui Ueyama     }
3760b1b695aSRui Ueyama 
3778c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3788c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3797bd37870SRafael Espindola 
3800b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3810b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3828c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3837bd37870SRafael Espindola         discard(V);
38448c3f1ceSRui Ueyama         continue;
38548c3f1ceSRui Ueyama       }
3860b9ce6a4SRui Ueyama 
3870b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3880b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3890b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
39007d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3910b1b695aSRui Ueyama       //
3920b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
39307d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3948c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
395b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
396f94efdddSRui Ueyama           S->Assigned = false;
39792a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
39807d7c42cSGeorge Rimar         --I;
3997c3ff2ebSRafael Espindola         continue;
4007c3ff2ebSRafael Espindola       }
4017c3ff2ebSRafael Espindola 
4020b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
4030b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
4048c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
4058f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4064cd7352cSRafael Espindola           addSymbol(OutCmd);
4077c3ff2ebSRafael Espindola 
4080b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4090b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4100b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4118c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4128c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
413b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4140b1b695aSRui Ueyama           S->Alignment = Subalign;
41520d03194SEugene Leviant       }
4160b1b695aSRui Ueyama 
4170b1b695aSRui Ueyama       // Add input sections to an output section.
418d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4190e2bfb1eSRui Ueyama         Sec->addSection(cast<InputSection>(S));
420c54d5b16SRui Ueyama 
421660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
422660c9ab9SRafael Espindola       Sec->SectionIndex = I;
4238c022ca7SRafael Espindola       if (Sec->Noload)
424fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
42548c3f1ceSRui Ueyama     }
4264aa2ef5bSRafael Espindola   }
427c1ace40bSPeter Smith   CurAddressState = nullptr;
428db24d9c3SGeorge Rimar }
429e63d81bdSEugene Leviant 
43002ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
431cbfe9e94SPeter Smith   // Define start address
432761f0b66SRui Ueyama   uint64_t StartAddr = UINT64_MAX;
433cbfe9e94SPeter Smith 
434c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
435c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
436c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
437c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
438c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
439c60b4510SPeter Smith 
440f5db0b36SRui Ueyama   auto Expr = [=] {
441f5db0b36SRui Ueyama     return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
442f5db0b36SRui Ueyama   };
4438c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
444f5db0b36SRui Ueyama                       make<SymbolAssignment>(".", Expr, ""));
445cbfe9e94SPeter Smith }
446cbfe9e94SPeter Smith 
447d2f225fdSRui Ueyama static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
448d2f225fdSRui Ueyama                                  StringRef Name) {
449d2f225fdSRui Ueyama   for (BaseCommand *Base : Vec)
450d2f225fdSRui Ueyama     if (auto *Sec = dyn_cast<OutputSection>(Base))
451d2f225fdSRui Ueyama       if (Sec->Name == Name)
452d2f225fdSRui Ueyama         return Sec;
453d2f225fdSRui Ueyama   return nullptr;
454d2f225fdSRui Ueyama }
455d2f225fdSRui Ueyama 
4560b1b695aSRui Ueyama // Add sections that didn't match any sections command.
457b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
458d2f225fdSRui Ueyama   unsigned End = Opt.Commands.size();
459d2f225fdSRui Ueyama 
4604f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
461db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4624f013bb3SRafael Espindola       continue;
463d2f225fdSRui Ueyama 
4644f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
465347c70d7SGeorge Rimar     log(toString(S) + " is being placed in '" + Name + "'");
466d2f225fdSRui Ueyama 
467d2f225fdSRui Ueyama     if (OutputSection *Sec = findByName(
468d2f225fdSRui Ueyama             makeArrayRef(Opt.Commands).slice(0, End), Name)) {
4690e2bfb1eSRui Ueyama       Sec->addSection(cast<InputSection>(S));
470c54d5b16SRui Ueyama       continue;
471660c9ab9SRafael Espindola     }
472c54d5b16SRui Ueyama 
473c54d5b16SRui Ueyama     if (OutputSection *OS = Factory.addInputSec(S, Name))
474c54d5b16SRui Ueyama       Script->Opt.Commands.push_back(OS);
475c54d5b16SRui Ueyama     assert(S->getOutputSection()->SectionIndex == INT_MAX);
476d7faa916SRafael Espindola   }
4774f013bb3SRafael Espindola }
478e63d81bdSEugene Leviant 
4797c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
480906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
481906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
482906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4837c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4847c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4857c4eafa3SRafael Espindola 
4867c4eafa3SRafael Espindola   if (IsTbss)
487906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4887c4eafa3SRafael Espindola   else
4897c4eafa3SRafael Espindola     Dot = End;
4907c4eafa3SRafael Espindola   return End;
491a940e539SRafael Espindola }
492a940e539SRafael Espindola 
493b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
494f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4957c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
496906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
497d3190795SRafael Espindola 
498d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
499d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
500d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
501906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
502d3190795SRafael Espindola 
503b889744eSMeador Inge   // If there is a memory region associated with this input section, then
504b889744eSMeador Inge   // place the section in that region and update the region index.
505906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
506906e9a18SPeter Smith     uint64_t &CurOffset =
507906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
508f694d33fSGeorge Rimar     CurOffset += Pos - Before;
509906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
510906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
511906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
512906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
513906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
514906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
515b889744eSMeador Inge     }
516b889744eSMeador Inge   }
5172de509c3SRui Ueyama }
518ceabe80eSEugene Leviant 
519b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
520906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
521d3190795SRafael Espindola     return;
522d3190795SRafael Espindola 
523906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
524906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
525906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
526b71d6f7aSEugene Leviant 
527b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
528b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
529b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
530b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
531906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
532906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
533d3190795SRafael Espindola }
534d3190795SRafael Espindola 
535b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5362e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5372e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5382e081a4fSRui Ueyama     assignSymbol(Cmd, true);
539d3190795SRafael Espindola     return;
54097403d15SEugene Leviant   }
541e38cbab5SGeorge Rimar 
542e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5432e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
544906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5452e081a4fSRui Ueyama     Dot += Cmd->Size;
546906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
547e38cbab5SGeorge Rimar     return;
548e38cbab5SGeorge Rimar   }
549e38cbab5SGeorge Rimar 
5502e081a4fSRui Ueyama   // Handle ASSERT().
5512e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5522e081a4fSRui Ueyama     Cmd->Expression();
553b2d99d6aSMeador Inge     return;
554b2d99d6aSMeador Inge   }
555b2d99d6aSMeador Inge 
5562e081a4fSRui Ueyama   // Handle a single input section description command.
5572e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
558e38cbab5SGeorge Rimar   // updates the output section size.
5592e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
560a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5613fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5623fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5633fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5643fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5652e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5662e081a4fSRui Ueyama       if (S->empty())
5673fb5a6dcSGeorge Rimar         continue;
5683fb5a6dcSGeorge Rimar 
5692e081a4fSRui Ueyama     if (!Sec->Live)
57078ef645fSGeorge Rimar       continue;
571906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
572a85e8ddaSRafael Espindola     output(Sec);
573ceabe80eSEugene Leviant   }
574ceabe80eSEugene Leviant }
575ceabe80eSEugene Leviant 
576b889744eSMeador Inge // This function searches for a memory region to place the given output
577b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
578b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5798c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
580b889744eSMeador Inge   // If a memory region name was specified in the output section command,
581b889744eSMeador Inge   // then try to find that region first.
5828c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5838c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
584b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
5855f37541cSGeorge Rimar       return It->second;
5868c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
587b889744eSMeador Inge     return nullptr;
588b889744eSMeador Inge   }
589b889744eSMeador Inge 
590d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
591d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
592d7c5400fSRui Ueyama   // anything for memory regions.
593cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
594b889744eSMeador Inge     return nullptr;
595b889744eSMeador Inge 
596b889744eSMeador Inge   // See if a region can be found by matching section flags.
5972e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
5985f37541cSGeorge Rimar     MemoryRegion *M = Pair.second;
5995f37541cSGeorge Rimar     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
6005f37541cSGeorge Rimar       return M;
601b889744eSMeador Inge   }
602b889744eSMeador Inge 
603b889744eSMeador Inge   // Otherwise, no suitable region was found.
604b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
605b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
606b889744eSMeador Inge   return nullptr;
607b889744eSMeador Inge }
608b889744eSMeador Inge 
6090b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6100b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6118c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
612dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
613dece2808SRafael Espindola     Dot = 0;
6148c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6158c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
616679828ffSRafael Espindola 
617c2dffe3aSGeorge Rimar   CurAddressState->MemRegion = Sec->MemRegion;
618c2dffe3aSGeorge Rimar   if (CurAddressState->MemRegion)
619c2dffe3aSGeorge Rimar     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
620c2dffe3aSGeorge Rimar 
6218c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6220c1c8085SGeorge Rimar     uint64_t D = Dot;
6238c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6245784e96fSEugene Leviant   }
6255784e96fSEugene Leviant 
626b889744eSMeador Inge   switchTo(Sec);
6270b1b695aSRui Ueyama 
628d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
629d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
630906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
631d86a4e50SGeorge Rimar     return;
632d86a4e50SGeorge Rimar 
6338c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
634de8d9897SRafael Espindola     process(*C);
635d3190795SRafael Espindola }
636d3190795SRafael Espindola 
637b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6386d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6396d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6406d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6416d38e4dbSRafael Espindola   // clutter the output.
6426d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6436d38e4dbSRafael Espindola   // more aggressive at removing them.
64460608a8aSGeorge Rimar   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
6458c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6468c022ca7SRafael Espindola       return !Sec->Live;
6470b1b695aSRui Ueyama     return false;
6486d38e4dbSRafael Espindola   });
64907fe6129SRafael Espindola }
65007fe6129SRafael Espindola 
6518c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6528f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6538f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6546a53737cSRafael Espindola       return false;
6556a53737cSRafael Espindola   return true;
6566a53737cSRafael Espindola }
6576d38e4dbSRafael Espindola 
658b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6599546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6609546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6619546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6629546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6630c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
664660c9ab9SRafael Espindola 
6658962db91SGeorge Rimar   for (BaseCommand * Cmd : Opt.Commands) {
6668962db91SGeorge Rimar     auto *Sec = dyn_cast<OutputSection>(Cmd);
6678c022ca7SRafael Espindola     if (!Sec)
6689546fffbSRafael Espindola       continue;
6698c022ca7SRafael Espindola     if (Sec->Live) {
6702b074553SRafael Espindola       Flags = Sec->Flags;
6719546fffbSRafael Espindola       continue;
6729546fffbSRafael Espindola     }
6739546fffbSRafael Espindola 
6748c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6756a53737cSRafael Espindola       continue;
6766a53737cSRafael Espindola 
6778c022ca7SRafael Espindola     Sec->Live = true;
6788c022ca7SRafael Espindola     Sec->Flags = Flags;
6799546fffbSRafael Espindola   }
680f7a17448SRafael Espindola }
681f7a17448SRafael Espindola 
682b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
683feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
684d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6858c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
686ba45584cSGeorge Rimar       if (!Sec->Live)
687ba45584cSGeorge Rimar         continue;
6888c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
689d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6908c022ca7SRafael Espindola       if (Sec->AlignExpr)
691*8befefb2SRui Ueyama         Sec->Alignment =
692*8befefb2SRui Ueyama             std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
693d1960dc0SRafael Espindola     }
694d1960dc0SRafael Espindola   }
695feed7506SRafael Espindola 
696f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
697f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
698f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
699f7a17448SRafael Espindola   // Below is an example of such linker script:
700f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
701f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
702f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
703f7a17448SRafael Espindola   auto FirstPtLoad =
704f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
705f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
706f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
707f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
708f7a17448SRafael Espindola 
709f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
710f7a17448SRafael Espindola   // explicitly specify them.
7118f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7128c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7138c022ca7SRafael Espindola     if (!Sec)
714f7a17448SRafael Espindola       continue;
7158f99f73cSRui Ueyama 
7168c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
717a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
718a020d348SAndrew Ng       // headers to sections that are allocated.
7198c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7208c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
721a020d348SAndrew Ng     } else {
7228c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
723f7a17448SRafael Espindola     }
724a020d348SAndrew Ng   }
7259546fffbSRafael Espindola }
7269546fffbSRafael Espindola 
727582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) {
728582ede89SGeorge Rimar   for (OutputSection *Sec : OutputSections)
729582ede89SGeorge Rimar     if (Sec->PtLoad == Load)
730582ede89SGeorge Rimar       return Sec;
731582ede89SGeorge Rimar   return nullptr;
732582ede89SGeorge Rimar }
733582ede89SGeorge Rimar 
734b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections,
735b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier.
736b93c5b9fSPetr Hosek //
737b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first
738b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers
739b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not
740b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common
741b93c5b9fSPetr Hosek // in embedded systems.
742b93c5b9fSPetr Hosek //
743b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the
744b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
745aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7465aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7478c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7485aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7495aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7505aedebffSPeter Smith 
751aa354187SGeorge Rimar   auto It = llvm::find_if(
752aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
753aa354187SGeorge Rimar   if (It == Phdrs.end())
754d971e703SGeorge Rimar     return;
755aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
75602ed7575SRafael Espindola 
75702ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
758b93c5b9fSPetr Hosek   // When linker script with SECTIONS is being used, don't output headers
759b93c5b9fSPetr Hosek   // unless there's a space for them.
760b93c5b9fSPetr Hosek   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
761b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
7621f0fe88aSRafael Espindola     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
76302ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
76402ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
765d971e703SGeorge Rimar     return;
76602ed7575SRafael Espindola   }
76702ed7575SRafael Espindola 
768582ede89SGeorge Rimar   Out::ElfHeader->PtLoad = nullptr;
769582ede89SGeorge Rimar   Out::ProgramHeaders->PtLoad = nullptr;
7706823c5f0SGeorge Rimar   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
77102ed7575SRafael Espindola 
77260608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
77360608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
77402ed7575SRafael Espindola }
77502ed7575SRafael Espindola 
776906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
777906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
7785f37541cSGeorge Rimar     const MemoryRegion *MR = MRI.second;
779906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
780906e9a18SPeter Smith   }
781906e9a18SPeter Smith }
782906e9a18SPeter Smith 
7835aedebffSPeter Smith void LinkerScript::assignAddresses() {
7847c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
785be607334SRafael Espindola   Dot = 0;
786906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
787c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
788c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
789c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
790c1ace40bSPeter Smith   // script parser.
791906e9a18SPeter Smith   CurAddressState = State.get();
79272dc195dSRafael Espindola   ErrorOnMissingSection = true;
79306f4743aSRafael Espindola   switchTo(Aether);
79406f4743aSRafael Espindola 
7958f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7968f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
797d379f735SRui Ueyama       assignSymbol(Cmd, false);
79805ef4cffSRui Ueyama       continue;
799652852c5SGeorge Rimar     }
800652852c5SGeorge Rimar 
8018f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
8024595df94SRafael Espindola       Cmd->Expression();
803eefa758eSGeorge Rimar       continue;
804eefa758eSGeorge Rimar     }
805eefa758eSGeorge Rimar 
8068c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
807a14b13d8SGeorge Rimar   }
808c1ace40bSPeter Smith   CurAddressState = nullptr;
809fb8978fcSDima Stepanov }
810652852c5SGeorge Rimar 
811464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
812aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
813aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
814bbe38602SEugene Leviant 
815464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
816464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
817bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
818aa354187SGeorge Rimar     PhdrEntry *Phdr =
819aa354187SGeorge Rimar         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
820bbe38602SEugene Leviant 
821bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
822aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
823bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
824aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
82556b21c86SEugene Leviant 
82656b21c86SEugene Leviant     if (Cmd.LMAExpr) {
827aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
828aa354187SGeorge Rimar       Phdr->HasLMA = true;
82956b21c86SEugene Leviant     }
830aa354187SGeorge Rimar     Ret.push_back(Phdr);
831bbe38602SEugene Leviant   }
832bbe38602SEugene Leviant 
833464daadcSRui Ueyama   // Add output sections to program headers.
8348c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
835bbe38602SEugene Leviant     // Assign headers specified by linker script
8368c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
837aa354187SGeorge Rimar       Ret[Id]->add(Sec);
838865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
839aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
840bbe38602SEugene Leviant     }
841bbe38602SEugene Leviant   }
842edebbdf1SRui Ueyama   return Ret;
843bbe38602SEugene Leviant }
844bbe38602SEugene Leviant 
845b8dd23f5SRui Ueyama bool LinkerScript::ignoreInterpSection() {
846f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
847f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
848e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
849e31d9886SRui Ueyama     return false;
850e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
851e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
852e31d9886SRui Ueyama       return false;
853e31d9886SRui Ueyama   return true;
854f9bc3bd2SEugene Leviant }
855f9bc3bd2SEugene Leviant 
856b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8577e5b0a59SGeorge Rimar   if (S == ".") {
8587e5b0a59SGeorge Rimar     if (CurAddressState)
8597e5b0a59SGeorge Rimar       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
8607e5b0a59SGeorge Rimar               Loc};
8617e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8627e5b0a59SGeorge Rimar     return 0;
8637e5b0a59SGeorge Rimar   }
864244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
86572dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
86641c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
86730f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
86867df57a2SRafael Espindola       return {C->Section, 0, Loc};
86972dc195dSRafael Espindola   }
870f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
871884e786dSGeorge Rimar   return 0;
872884e786dSGeorge Rimar }
873884e786dSGeorge Rimar 
874244ef981SRafael Espindola bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
875f34f45fdSGeorge Rimar 
8766e9f98c1SAndrew Ng static const size_t NoPhdr = -1;
8776e9f98c1SAndrew Ng 
8782c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8792c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8808c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
88129c5a2a9SRui Ueyama   std::vector<size_t> Ret;
8826e9f98c1SAndrew Ng   for (StringRef PhdrName : Cmd->Phdrs) {
8836e9f98c1SAndrew Ng     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
8846e9f98c1SAndrew Ng     if (Index != NoPhdr)
8856e9f98c1SAndrew Ng       Ret.push_back(Index);
8866e9f98c1SAndrew Ng   }
88729c5a2a9SRui Ueyama   return Ret;
888bbe38602SEugene Leviant }
889bbe38602SEugene Leviant 
8906e9f98c1SAndrew Ng // Returns the index of the segment named PhdrName if found otherwise
8916e9f98c1SAndrew Ng // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
8926e9f98c1SAndrew Ng // (which can be used to explicitly specify that a section isn't assigned to a
8936e9f98c1SAndrew Ng // segment) then error.
894b8dd23f5SRui Ueyama size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
89529c5a2a9SRui Ueyama   size_t I = 0;
89629c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
89729c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
89829c5a2a9SRui Ueyama       return I;
89929c5a2a9SRui Ueyama     ++I;
90029c5a2a9SRui Ueyama   }
9016e9f98c1SAndrew Ng   if (PhdrName != "NONE")
9022a942c4bSEugene Leviant     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
9036e9f98c1SAndrew Ng   return NoPhdr;
90429c5a2a9SRui Ueyama }
905