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 
5272dc195dSRafael Espindola uint64_t ExprValue::getValue() const {
53608cf670SGeorge Rimar   if (Sec) {
54d54c5665SRafael Espindola     if (OutputSection *OS = Sec->getOutputSection())
55d54c5665SRafael Espindola       return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment);
5641c7ab4aSGeorge Rimar     error(Loc + ": unable to evaluate expression: input section " + Sec->Name +
57608cf670SGeorge Rimar           " has no output section assigned");
58608cf670SGeorge Rimar   }
593c6de1a6SPetr Hosek   return alignTo(Val, Alignment);
6072dc195dSRafael Espindola }
6172dc195dSRafael Espindola 
627ba5f47eSRafael Espindola uint64_t ExprValue::getSecAddr() const {
637ba5f47eSRafael Espindola   if (Sec)
647ba5f47eSRafael Espindola     return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
657ba5f47eSRafael Espindola   return 0;
667ba5f47eSRafael Espindola }
677ba5f47eSRafael Espindola 
68a5e8dd35SRafael Espindola static SymbolBody *addRegular(SymbolAssignment *Cmd) {
695e51f7d2SPetr Hosek   Symbol *Sym;
703dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
71244ef981SRafael Espindola   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
72244ef981SRafael Espindola                                               /*CanOmitFromDynSym*/ false,
735e51f7d2SPetr Hosek                                               /*File*/ nullptr);
745e51f7d2SPetr Hosek   Sym->Binding = STB_GLOBAL;
7572dc195dSRafael Espindola   ExprValue Value = Cmd->Expression();
7672dc195dSRafael Espindola   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
7701aa795fSGeorge Rimar 
7801aa795fSGeorge Rimar   // We want to set symbol values early if we can. This allows us to use symbols
7901aa795fSGeorge Rimar   // as variables in linker scripts. Doing so allows us to write expressions
8001aa795fSGeorge Rimar   // like this: `alignment = 16; . = ALIGN(., alignment)`
8101aa795fSGeorge Rimar   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
8280474a26SRui Ueyama   replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
8301aa795fSGeorge Rimar                               STT_NOTYPE, SymValue, 0, Sec, nullptr);
848f1f3c40SMeador Inge   return Sym->body();
85ceabe80eSEugene Leviant }
86ceabe80eSEugene Leviant 
878c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
888c022ca7SRafael Espindola                                                  StringRef Location) {
898c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
908c022ca7SRafael Espindola   OutputSection *Sec;
918c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
9205c4f67cSRafael Espindola     // There was a forward reference.
938c022ca7SRafael Espindola     Sec = SecRef;
9405c4f67cSRafael Espindola   } else {
958c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
968c022ca7SRafael Espindola     if (!SecRef)
978c022ca7SRafael Espindola       SecRef = Sec;
9805c4f67cSRafael Espindola   }
998c022ca7SRafael Espindola   Sec->Location = Location;
1008c022ca7SRafael Espindola   return Sec;
101851dc1e8SGeorge Rimar }
102851dc1e8SGeorge Rimar 
1038c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
1048c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
10505c4f67cSRafael Espindola   if (!CmdRef)
1068c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
10705c4f67cSRafael Espindola   return CmdRef;
108d83ce1b4SGeorge Rimar }
109d83ce1b4SGeorge Rimar 
110b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
11172dc195dSRafael Espindola   uint64_t Val = E().getValue();
1128c804d97SGeorge Rimar   if (Val < Dot && InSec)
1132ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
114906e9a18SPeter Smith           CurAddressState->OutSec->Name);
1154cd7352cSRafael Espindola   Dot = Val;
1164cd7352cSRafael Espindola   // Update to location counter means update to section size.
1174cd7352cSRafael Espindola   if (InSec)
118906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
119679828ffSRafael Espindola }
120679828ffSRafael Espindola 
121679828ffSRafael Espindola // Sets value of a symbol. Two kinds of symbols are processed: synthetic
122679828ffSRafael Espindola // symbols, whose value is an offset from beginning of section and regular
123679828ffSRafael Espindola // symbols whose value is absolute.
124b8dd23f5SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
125679828ffSRafael Espindola   if (Cmd->Name == ".") {
1262ee2d2dcSGeorge Rimar     setDot(Cmd->Expression, Cmd->Location, InSec);
1274cd7352cSRafael Espindola     return;
1284cd7352cSRafael Espindola   }
1294cd7352cSRafael Espindola 
130b2b70975SGeorge Rimar   if (!Cmd->Sym)
1318f1f3c40SMeador Inge     return;
1328f1f3c40SMeador Inge 
1335616adf6SRafael Espindola   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
13472dc195dSRafael Espindola   ExprValue V = Cmd->Expression();
13572dc195dSRafael Espindola   if (V.isAbsolute()) {
13672dc195dSRafael Espindola     Sym->Value = V.getValue();
13772dc195dSRafael Espindola   } else {
13872dc195dSRafael Espindola     Sym->Section = V.Sec;
1393c6de1a6SPetr Hosek     Sym->Value = alignTo(V.Val, V.Alignment);
140ea590d91SRafael Espindola   }
1418f1f3c40SMeador Inge }
1428f1f3c40SMeador Inge 
143b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1441602421cSRui Ueyama   if (Cmd->Name == ".")
1458f1f3c40SMeador Inge     return;
1468f1f3c40SMeador Inge 
1478f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1488f1f3c40SMeador Inge   // it is a referenced undefined symbol.
149244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1508f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1518f1f3c40SMeador Inge     return;
1528f1f3c40SMeador Inge 
153a5e8dd35SRafael Espindola   Cmd->Sym = addRegular(Cmd);
154ceabe80eSEugene Leviant }
155ceabe80eSEugene Leviant 
156076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
157076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
158076fe157SGeorge Rimar }
159076fe157SGeorge Rimar 
160eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
161eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
162eea3114fSGeorge Rimar }
163eea3114fSGeorge Rimar 
164eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
165eefa758eSGeorge Rimar   return C->Kind == AssertKind;
166eefa758eSGeorge Rimar }
167eefa758eSGeorge Rimar 
168e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
169e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
170e38cbab5SGeorge Rimar }
171e38cbab5SGeorge Rimar 
172b4c9b81aSRafael Espindola static StringRef basename(InputSectionBase *S) {
173b4c9b81aSRafael Espindola   if (S->File)
174b4c9b81aSRafael Espindola     return sys::path::filename(S->File->getName());
175e0be2901SRui Ueyama   return "";
176e0be2901SRui Ueyama }
177e0be2901SRui Ueyama 
178b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
179e0be2901SRui Ueyama   for (InputSectionDescription *ID : Opt.KeptSections)
180e0be2901SRui Ueyama     if (ID->FilePat.match(basename(S)))
181cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
182f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
183eea3114fSGeorge Rimar           return true;
184eea3114fSGeorge Rimar   return false;
185eea3114fSGeorge Rimar }
186eea3114fSGeorge Rimar 
187ea93fe00SRui Ueyama // A helper function for the SORT() command.
188c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
189be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
190be394db3SGeorge Rimar   switch (K) {
191be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
192ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
193ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
194ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
195ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
196ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
197ea93fe00SRui Ueyama     };
198be394db3SGeorge Rimar   case SortSectionPolicy::Name:
199ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
200ea93fe00SRui Ueyama       return A->Name < B->Name;
201ea93fe00SRui Ueyama     };
202be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
203ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
204ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
205ea93fe00SRui Ueyama     };
206be394db3SGeorge Rimar   default:
207be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
208be394db3SGeorge Rimar   }
209742c3836SRui Ueyama }
2100702c4e8SGeorge Rimar 
211ea93fe00SRui Ueyama // A helper function for the SORT() command.
212b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
21306ae6836SGeorge Rimar                              ConstraintKind Kind) {
2148f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2158f66df92SGeorge Rimar     return true;
2162c7171bfSRui Ueyama 
2172c7171bfSRui Ueyama   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
2182c7171bfSRui Ueyama     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
21906ae6836SGeorge Rimar   });
2202c7171bfSRui Ueyama 
221e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
222e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
22306ae6836SGeorge Rimar }
22406ae6836SGeorge Rimar 
2256a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End,
226ee924709SRui Ueyama                          SortSectionPolicy K) {
227ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
22807171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
229ee924709SRui Ueyama }
230ee924709SRui Ueyama 
231*d6bcde38SGeorge Rimar static llvm::DenseMap<SectionBase *, int> getSectionOrder() {
232*d6bcde38SGeorge Rimar   switch (Config->EKind) {
233*d6bcde38SGeorge Rimar   case ELF32LEKind:
234*d6bcde38SGeorge Rimar     return buildSectionOrder<ELF32LE>();
235*d6bcde38SGeorge Rimar   case ELF32BEKind:
236*d6bcde38SGeorge Rimar     return buildSectionOrder<ELF32BE>();
237*d6bcde38SGeorge Rimar   case ELF64LEKind:
238*d6bcde38SGeorge Rimar     return buildSectionOrder<ELF64LE>();
239*d6bcde38SGeorge Rimar   case ELF64BEKind:
240*d6bcde38SGeorge Rimar     return buildSectionOrder<ELF64BE>();
241*d6bcde38SGeorge Rimar   default:
242*d6bcde38SGeorge Rimar     llvm_unreachable("unknown ELF type");
243*d6bcde38SGeorge Rimar   }
244*d6bcde38SGeorge Rimar }
245*d6bcde38SGeorge Rimar 
246*d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
247*d6bcde38SGeorge Rimar   if (Config->SymbolOrderingFile.empty())
248*d6bcde38SGeorge Rimar     return;
249*d6bcde38SGeorge Rimar   static llvm::DenseMap<SectionBase *, int> Order = getSectionOrder();
250*d6bcde38SGeorge Rimar   MutableArrayRef<InputSection *> In(Begin, End - Begin);
251*d6bcde38SGeorge Rimar   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
252*d6bcde38SGeorge Rimar }
253*d6bcde38SGeorge Rimar 
254d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2556a1aa8d9SRafael Espindola std::vector<InputSection *>
25672e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2576a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2588c6a5aafSRui Ueyama 
25972e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
26072e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
26172e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
26272e107f3SRui Ueyama 
26372e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
26472e107f3SRui Ueyama       if (Sec->Assigned)
2658c6a5aafSRui Ueyama         continue;
26672e107f3SRui Ueyama 
267e39709b2SRafael Espindola       if (!Sec->Live) {
268e39709b2SRafael Espindola         reportDiscarded(Sec);
269e39709b2SRafael Espindola         continue;
270e39709b2SRafael Espindola       }
271e39709b2SRafael Espindola 
272908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
273908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
274908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
27572e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
276908a3d34SRafael Espindola         continue;
2778c6a5aafSRui Ueyama 
27872e107f3SRui Ueyama       StringRef Filename = basename(Sec);
27972e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
28072e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
28172e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
282e0be2901SRui Ueyama         continue;
28372e107f3SRui Ueyama 
2846a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
28572e107f3SRui Ueyama       Sec->Assigned = true;
286f94efdddSRui Ueyama     }
287d3190795SRafael Espindola 
288ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
289ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
290ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
291ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
292ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
293ee924709SRui Ueyama     //
294ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
295ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
296ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
297ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
298ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
299*d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
300*d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
3016a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
3026a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
303*d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
304*d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
305*d6bcde38SGeorge Rimar       sortBySymbolOrder(Begin, End);
306*d6bcde38SGeorge Rimar       continue;
307*d6bcde38SGeorge Rimar     }
30807171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
30907171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
31007171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
311ee924709SRui Ueyama       else
31207171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
31307171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
31407171f21SGeorge Rimar     }
315ee924709SRui Ueyama   }
31672e107f3SRui Ueyama   return Ret;
317be94e1b6SRafael Espindola }
318be94e1b6SRafael Espindola 
319b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
320b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
321be94e1b6SRafael Espindola     S->Live = false;
3224f1fca27SRafael Espindola     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
3234f1fca27SRafael Espindola         S == InX::DynStrTab)
3242af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
325647c1685SGeorge Rimar     discard(S->DependentSections);
326be94e1b6SRafael Espindola   }
327be94e1b6SRafael Espindola }
328be94e1b6SRafael Espindola 
329b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3308c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
331b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
332e7f912cdSRui Ueyama 
3338f99f73cSRui Ueyama   for (BaseCommand *Base : OutCmd.Commands) {
3348f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3357c3ff2ebSRafael Espindola     if (!Cmd)
3360b9ce6a4SRui Ueyama       continue;
33772e107f3SRui Ueyama 
33872e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
339e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3400b9ce6a4SRui Ueyama   }
341e71a3f8aSRafael Espindola 
3420b9ce6a4SRui Ueyama   return Ret;
3430b9ce6a4SRui Ueyama }
3440b9ce6a4SRui Ueyama 
345b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3465616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3475616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3485616adf6SRafael Espindola   // section values are:
3495616adf6SRafael Espindola   // * SHN_UNDEF
3505616adf6SRafael Espindola   // * SHN_ABS
3515616adf6SRafael Espindola   // * Any value meaning a regular section.
3525616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3535616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3545616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3555616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3565616adf6SRafael Espindola   Aether->SectionIndex = 1;
357906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
358c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
359c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
360c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
361c1ace40bSPeter Smith   // script parser.
362906e9a18SPeter Smith   CurAddressState = State.get();
363906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
36449592cf6SRafael Espindola   Dot = 0;
3655616adf6SRafael Espindola 
36692a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3670b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
36892a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3694cd7352cSRafael Espindola       addSymbol(Cmd);
3702ab5f73dSRui Ueyama       continue;
3712ab5f73dSRui Ueyama     }
3720b1b695aSRui Ueyama 
3738c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3748c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3757bd37870SRafael Espindola 
3760b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3770b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3788c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3797bd37870SRafael Espindola         discard(V);
38048c3f1ceSRui Ueyama         continue;
38148c3f1ceSRui Ueyama       }
3820b9ce6a4SRui Ueyama 
3830b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3840b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3850b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
38607d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3870b1b695aSRui Ueyama       //
3880b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
38907d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3908c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
391b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
392f94efdddSRui Ueyama           S->Assigned = false;
39392a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
39407d7c42cSGeorge Rimar         --I;
3957c3ff2ebSRafael Espindola         continue;
3967c3ff2ebSRafael Espindola       }
3977c3ff2ebSRafael Espindola 
3980b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
3990b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
4008c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
4018f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4024cd7352cSRafael Espindola           addSymbol(OutCmd);
4037c3ff2ebSRafael Espindola 
4040b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4050b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4060b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4078c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4088c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
409b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4100b1b695aSRui Ueyama           S->Alignment = Subalign;
41120d03194SEugene Leviant       }
4120b1b695aSRui Ueyama 
4130b1b695aSRui Ueyama       // Add input sections to an output section.
414d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4158c022ca7SRafael Espindola         Factory.addInputSec(S, Sec->Name, Sec);
416660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
417660c9ab9SRafael Espindola       Sec->SectionIndex = I;
4188c022ca7SRafael Espindola       if (Sec->Noload)
419fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
42048c3f1ceSRui Ueyama     }
4214aa2ef5bSRafael Espindola   }
422c1ace40bSPeter Smith   CurAddressState = nullptr;
423db24d9c3SGeorge Rimar }
424e63d81bdSEugene Leviant 
42502ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
426cbfe9e94SPeter Smith   // Define start address
427e76231b6SRafael Espindola   uint64_t StartAddr = -1;
428cbfe9e94SPeter Smith 
429c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
430c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
431c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
432c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
433c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
434c60b4510SPeter Smith 
4358c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
4368c022ca7SRafael Espindola                       make<SymbolAssignment>(".",
437e76231b6SRafael Espindola                                              [=] {
4388c022ca7SRafael Espindola                                                return std::min(
4398c022ca7SRafael Espindola                                                    StartAddr,
4408c022ca7SRafael Espindola                                                    Config->ImageBase +
4418c022ca7SRafael Espindola                                                        elf::getHeaderSize());
442e76231b6SRafael Espindola                                              },
443e76231b6SRafael Espindola                                              ""));
444cbfe9e94SPeter Smith }
445cbfe9e94SPeter Smith 
4460b1b695aSRui Ueyama // Add sections that didn't match any sections command.
447b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
448d7faa916SRafael Espindola   unsigned NumCommands = Opt.Commands.size();
4494f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
450db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4514f013bb3SRafael Espindola       continue;
4524f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
453d7faa916SRafael Espindola     auto End = Opt.Commands.begin() + NumCommands;
454d7faa916SRafael Espindola     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
4558c022ca7SRafael Espindola       if (auto *Sec = dyn_cast<OutputSection>(Base))
4568c022ca7SRafael Espindola         return Sec->Name == Name;
4574f013bb3SRafael Espindola       return false;
4584f013bb3SRafael Espindola     });
459d7faa916SRafael Espindola     if (I == End) {
4604f013bb3SRafael Espindola       Factory.addInputSec(S, Name);
461a2df2f09SRafael Espindola       assert(S->getOutputSection()->SectionIndex == INT_MAX);
462de8d9897SRafael Espindola     } else {
4638c022ca7SRafael Espindola       OutputSection *Sec = cast<OutputSection>(*I);
4648c022ca7SRafael Espindola       Factory.addInputSec(S, Name, Sec);
465660c9ab9SRafael Espindola       unsigned Index = std::distance(Opt.Commands.begin(), I);
466660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
467660c9ab9SRafael Espindola       Sec->SectionIndex = Index;
468660c9ab9SRafael Espindola     }
469d7faa916SRafael Espindola   }
4704f013bb3SRafael Espindola }
471e63d81bdSEugene Leviant 
4727c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
473906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
474906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
475906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4767c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4777c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4787c4eafa3SRafael Espindola 
4797c4eafa3SRafael Espindola   if (IsTbss)
480906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4817c4eafa3SRafael Espindola   else
4827c4eafa3SRafael Espindola     Dot = End;
4837c4eafa3SRafael Espindola   return End;
484a940e539SRafael Espindola }
485a940e539SRafael Espindola 
486b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
487f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4887c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
489906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
490d3190795SRafael Espindola 
491d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
492d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
493d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
494906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
495d3190795SRafael Espindola 
496b889744eSMeador Inge   // If there is a memory region associated with this input section, then
497b889744eSMeador Inge   // place the section in that region and update the region index.
498906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
499906e9a18SPeter Smith     uint64_t &CurOffset =
500906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
501f694d33fSGeorge Rimar     CurOffset += Pos - Before;
502906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
503906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
504906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
505906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
506906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
507906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
508b889744eSMeador Inge     }
509b889744eSMeador Inge   }
5102de509c3SRui Ueyama }
511ceabe80eSEugene Leviant 
512b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
513906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
514d3190795SRafael Espindola     return;
515d3190795SRafael Espindola 
516906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
517906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
518906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
519b71d6f7aSEugene Leviant 
520b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
521b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
522b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
523b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
524906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
525906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
526d3190795SRafael Espindola }
527d3190795SRafael Espindola 
528b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5292e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5302e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5312e081a4fSRui Ueyama     assignSymbol(Cmd, true);
532d3190795SRafael Espindola     return;
53397403d15SEugene Leviant   }
534e38cbab5SGeorge Rimar 
535e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5362e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
537906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5382e081a4fSRui Ueyama     Dot += Cmd->Size;
539906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
540e38cbab5SGeorge Rimar     return;
541e38cbab5SGeorge Rimar   }
542e38cbab5SGeorge Rimar 
5432e081a4fSRui Ueyama   // Handle ASSERT().
5442e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5452e081a4fSRui Ueyama     Cmd->Expression();
546b2d99d6aSMeador Inge     return;
547b2d99d6aSMeador Inge   }
548b2d99d6aSMeador Inge 
5492e081a4fSRui Ueyama   // Handle a single input section description command.
5502e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
551e38cbab5SGeorge Rimar   // updates the output section size.
5522e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
553a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5543fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5553fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5563fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5573fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5582e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5592e081a4fSRui Ueyama       if (S->empty())
5603fb5a6dcSGeorge Rimar         continue;
5613fb5a6dcSGeorge Rimar 
5622e081a4fSRui Ueyama     if (!Sec->Live)
56378ef645fSGeorge Rimar       continue;
564906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
565a85e8ddaSRafael Espindola     output(Sec);
566ceabe80eSEugene Leviant   }
567ceabe80eSEugene Leviant }
568ceabe80eSEugene Leviant 
569b889744eSMeador Inge // This function searches for a memory region to place the given output
570b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
571b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5728c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
573b889744eSMeador Inge   // If a memory region name was specified in the output section command,
574b889744eSMeador Inge   // then try to find that region first.
5758c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5768c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
577b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
578b889744eSMeador Inge       return &It->second;
5798c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
580b889744eSMeador Inge     return nullptr;
581b889744eSMeador Inge   }
582b889744eSMeador Inge 
583d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
584d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
585d7c5400fSRui Ueyama   // anything for memory regions.
586cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
587b889744eSMeador Inge     return nullptr;
588b889744eSMeador Inge 
589b889744eSMeador Inge   // See if a region can be found by matching section flags.
5902e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
5912e081a4fSRui Ueyama     MemoryRegion &M = Pair.second;
5922e081a4fSRui Ueyama     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
5932e081a4fSRui Ueyama       return &M;
594b889744eSMeador Inge   }
595b889744eSMeador Inge 
596b889744eSMeador Inge   // Otherwise, no suitable region was found.
597b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
598b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
599b889744eSMeador Inge   return nullptr;
600b889744eSMeador Inge }
601b889744eSMeador Inge 
6020b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6030b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6048c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
605dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
606dece2808SRafael Espindola     Dot = 0;
6078c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6088c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
609679828ffSRafael Espindola 
6108c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6110c1c8085SGeorge Rimar     uint64_t D = Dot;
6128c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6135784e96fSEugene Leviant   }
6145784e96fSEugene Leviant 
6158c022ca7SRafael Espindola   CurAddressState->MemRegion = Sec->MemRegion;
616906e9a18SPeter Smith   if (CurAddressState->MemRegion)
617906e9a18SPeter Smith     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
618b889744eSMeador Inge   switchTo(Sec);
6190b1b695aSRui Ueyama 
620d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
621d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
622906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
623d86a4e50SGeorge Rimar     return;
624d86a4e50SGeorge Rimar 
6258c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
626de8d9897SRafael Espindola     process(*C);
627d3190795SRafael Espindola }
628d3190795SRafael Espindola 
629b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6306d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6316d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6326d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6336d38e4dbSRafael Espindola   // clutter the output.
6346d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6356d38e4dbSRafael Espindola   // more aggressive at removing them.
6368c022ca7SRafael Espindola   auto Pos = std::remove_if(Opt.Commands.begin(), Opt.Commands.end(),
6378c022ca7SRafael Espindola                             [&](BaseCommand *Base) {
6388c022ca7SRafael Espindola                               if (auto *Sec = dyn_cast<OutputSection>(Base))
6398c022ca7SRafael Espindola                                 return !Sec->Live;
6400b1b695aSRui Ueyama                               return false;
6416d38e4dbSRafael Espindola                             });
6426d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
64307fe6129SRafael Espindola }
64407fe6129SRafael Espindola 
6458c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6468f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6478f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6486a53737cSRafael Espindola       return false;
6496a53737cSRafael Espindola   return true;
6506a53737cSRafael Espindola }
6516d38e4dbSRafael Espindola 
652b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6539546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6549546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6559546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6569546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6570c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
658660c9ab9SRafael Espindola 
659660c9ab9SRafael Espindola   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
6608c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I]);
6618c022ca7SRafael Espindola     if (!Sec)
6629546fffbSRafael Espindola       continue;
6638c022ca7SRafael Espindola     if (Sec->Live) {
6642b074553SRafael Espindola       Flags = Sec->Flags;
6659546fffbSRafael Espindola       continue;
6669546fffbSRafael Espindola     }
6679546fffbSRafael Espindola 
6688c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6696a53737cSRafael Espindola       continue;
6706a53737cSRafael Espindola 
6718c022ca7SRafael Espindola     Sec->Live = true;
6728c022ca7SRafael Espindola     Sec->SectionIndex = I;
6738c022ca7SRafael Espindola     Sec->Flags = Flags;
6749546fffbSRafael Espindola   }
675f7a17448SRafael Espindola }
676f7a17448SRafael Espindola 
677b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
678feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
679d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6808c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
6818c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
682d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6838c022ca7SRafael Espindola       if (Sec->AlignExpr)
6848c022ca7SRafael Espindola         Sec->updateAlignment(Sec->AlignExpr().getValue());
685d1960dc0SRafael Espindola     }
686d1960dc0SRafael Espindola   }
687feed7506SRafael Espindola 
688f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
689f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
690f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
691f7a17448SRafael Espindola   // Below is an example of such linker script:
692f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
693f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
694f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
695f7a17448SRafael Espindola   auto FirstPtLoad =
696f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
697f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
698f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
699f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
700f7a17448SRafael Espindola 
701f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
702f7a17448SRafael Espindola   // explicitly specify them.
7038f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7048c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7058c022ca7SRafael Espindola     if (!Sec)
706f7a17448SRafael Espindola       continue;
7078f99f73cSRui Ueyama 
7088c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
709a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
710a020d348SAndrew Ng       // headers to sections that are allocated.
7118c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7128c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
713a020d348SAndrew Ng     } else {
7148c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
715f7a17448SRafael Espindola     }
716a020d348SAndrew Ng   }
7176a53737cSRafael Espindola 
7186a53737cSRafael Espindola   removeEmptyCommands();
7199546fffbSRafael Espindola }
7209546fffbSRafael Espindola 
721aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7225aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7238c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7245aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7255aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7265aedebffSPeter Smith 
727aa354187SGeorge Rimar   auto It = llvm::find_if(
728aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
729aa354187SGeorge Rimar   if (It == Phdrs.end())
730d971e703SGeorge Rimar     return;
731aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
73202ed7575SRafael Espindola 
73302ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
73402ed7575SRafael Espindola   if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
73502ed7575SRafael Espindola     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
73602ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
73702ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
738d971e703SGeorge Rimar     return;
73902ed7575SRafael Espindola   }
74002ed7575SRafael Espindola 
74102ed7575SRafael Espindola   assert(FirstPTLoad->First == Out::ElfHeader);
74202ed7575SRafael Espindola   OutputSection *ActualFirst = nullptr;
7438c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
74402ed7575SRafael Espindola     if (Sec->FirstInPtLoad == Out::ElfHeader) {
74502ed7575SRafael Espindola       ActualFirst = Sec;
74602ed7575SRafael Espindola       break;
74702ed7575SRafael Espindola     }
74802ed7575SRafael Espindola   }
74902ed7575SRafael Espindola   if (ActualFirst) {
7508c022ca7SRafael Espindola     for (OutputSection *Sec : OutputSections)
75102ed7575SRafael Espindola       if (Sec->FirstInPtLoad == Out::ElfHeader)
75202ed7575SRafael Espindola         Sec->FirstInPtLoad = ActualFirst;
75302ed7575SRafael Espindola     FirstPTLoad->First = ActualFirst;
75402ed7575SRafael Espindola   } else {
755aa354187SGeorge Rimar     Phdrs.erase(It);
75602ed7575SRafael Espindola   }
75702ed7575SRafael Espindola 
758d971e703SGeorge Rimar   auto PhdrI = llvm::find_if(
759aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
76002ed7575SRafael Espindola   if (PhdrI != Phdrs.end())
76102ed7575SRafael Espindola     Phdrs.erase(PhdrI);
76202ed7575SRafael Espindola }
76302ed7575SRafael Espindola 
764906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
765906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
766906e9a18SPeter Smith     const MemoryRegion *MR = &MRI.second;
767906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
768906e9a18SPeter Smith   }
769906e9a18SPeter Smith }
770906e9a18SPeter Smith 
7715aedebffSPeter Smith void LinkerScript::assignAddresses() {
7727c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
773be607334SRafael Espindola   Dot = 0;
774906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
775c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
776c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
777c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
778c1ace40bSPeter Smith   // script parser.
779906e9a18SPeter Smith   CurAddressState = State.get();
78072dc195dSRafael Espindola   ErrorOnMissingSection = true;
78106f4743aSRafael Espindola   switchTo(Aether);
78206f4743aSRafael Espindola 
7838f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7848f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
785d379f735SRui Ueyama       assignSymbol(Cmd, false);
78605ef4cffSRui Ueyama       continue;
787652852c5SGeorge Rimar     }
788652852c5SGeorge Rimar 
7898f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
7904595df94SRafael Espindola       Cmd->Expression();
791eefa758eSGeorge Rimar       continue;
792eefa758eSGeorge Rimar     }
793eefa758eSGeorge Rimar 
7948c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
795a14b13d8SGeorge Rimar   }
796c1ace40bSPeter Smith   CurAddressState = nullptr;
797fb8978fcSDima Stepanov }
798652852c5SGeorge Rimar 
799464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
800aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
801aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
802bbe38602SEugene Leviant 
803464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
804464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
805bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
806aa354187SGeorge Rimar     PhdrEntry *Phdr =
807aa354187SGeorge Rimar         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
808bbe38602SEugene Leviant 
809bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
810aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
811bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
812aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
81356b21c86SEugene Leviant 
81456b21c86SEugene Leviant     if (Cmd.LMAExpr) {
815aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
816aa354187SGeorge Rimar       Phdr->HasLMA = true;
81756b21c86SEugene Leviant     }
818aa354187SGeorge Rimar     Ret.push_back(Phdr);
819bbe38602SEugene Leviant   }
820bbe38602SEugene Leviant 
821464daadcSRui Ueyama   // Add output sections to program headers.
8228c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
823bbe38602SEugene Leviant     // Assign headers specified by linker script
8248c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
825aa354187SGeorge Rimar       Ret[Id]->add(Sec);
826865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
827aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
828bbe38602SEugene Leviant     }
829bbe38602SEugene Leviant   }
830edebbdf1SRui Ueyama   return Ret;
831bbe38602SEugene Leviant }
832bbe38602SEugene Leviant 
833b8dd23f5SRui Ueyama bool LinkerScript::ignoreInterpSection() {
834f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
835f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
836e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
837e31d9886SRui Ueyama     return false;
838e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
839e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
840e31d9886SRui Ueyama       return false;
841e31d9886SRui Ueyama   return true;
842f9bc3bd2SEugene Leviant }
843f9bc3bd2SEugene Leviant 
844b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8454595df94SRafael Espindola   if (S == ".")
846906e9a18SPeter Smith     return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr, Loc};
847244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
84872dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
84941c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
85030f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
85141c7ab4aSGeorge Rimar       return {InX::Common, C->Offset, Loc};
85272dc195dSRafael Espindola   }
853f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
854884e786dSGeorge Rimar   return 0;
855884e786dSGeorge Rimar }
856884e786dSGeorge Rimar 
857244ef981SRafael Espindola bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
858f34f45fdSGeorge Rimar 
8596e9f98c1SAndrew Ng static const size_t NoPhdr = -1;
8606e9f98c1SAndrew Ng 
8612c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8622c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8638c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
86429c5a2a9SRui Ueyama   std::vector<size_t> Ret;
8656e9f98c1SAndrew Ng   for (StringRef PhdrName : Cmd->Phdrs) {
8666e9f98c1SAndrew Ng     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
8676e9f98c1SAndrew Ng     if (Index != NoPhdr)
8686e9f98c1SAndrew Ng       Ret.push_back(Index);
8696e9f98c1SAndrew Ng   }
87029c5a2a9SRui Ueyama   return Ret;
871bbe38602SEugene Leviant }
872bbe38602SEugene Leviant 
8736e9f98c1SAndrew Ng // Returns the index of the segment named PhdrName if found otherwise
8746e9f98c1SAndrew Ng // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
8756e9f98c1SAndrew Ng // (which can be used to explicitly specify that a section isn't assigned to a
8766e9f98c1SAndrew Ng // segment) then error.
877b8dd23f5SRui Ueyama size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
87829c5a2a9SRui Ueyama   size_t I = 0;
87929c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
88029c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
88129c5a2a9SRui Ueyama       return I;
88229c5a2a9SRui Ueyama     ++I;
88329c5a2a9SRui Ueyama   }
8846e9f98c1SAndrew Ng   if (PhdrName != "NONE")
8852a942c4bSEugene Leviant     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
8866e9f98c1SAndrew Ng   return NoPhdr;
88729c5a2a9SRui Ueyama }
888