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 
231d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2326a1aa8d9SRafael Espindola std::vector<InputSection *>
23372e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2346a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2358c6a5aafSRui Ueyama 
23672e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
23772e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
23872e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
23972e107f3SRui Ueyama 
24072e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
24172e107f3SRui Ueyama       if (Sec->Assigned)
2428c6a5aafSRui Ueyama         continue;
24372e107f3SRui Ueyama 
244e39709b2SRafael Espindola       if (!Sec->Live) {
245e39709b2SRafael Espindola         reportDiscarded(Sec);
246e39709b2SRafael Espindola         continue;
247e39709b2SRafael Espindola       }
248e39709b2SRafael Espindola 
249908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
250908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
251908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
25272e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
253908a3d34SRafael Espindola         continue;
2548c6a5aafSRui Ueyama 
25572e107f3SRui Ueyama       StringRef Filename = basename(Sec);
25672e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
25772e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
25872e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
259e0be2901SRui Ueyama         continue;
26072e107f3SRui Ueyama 
2616a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
26272e107f3SRui Ueyama       Sec->Assigned = true;
263f94efdddSRui Ueyama     }
264d3190795SRafael Espindola 
265ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
266ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
267ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
268ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
269ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
270ee924709SRui Ueyama     //
271ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
272ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
273ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
274ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
275ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
2766a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
2776a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
27807171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
27907171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
28007171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
281ee924709SRui Ueyama       else
28207171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
28307171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
28407171f21SGeorge Rimar     }
285ee924709SRui Ueyama   }
28672e107f3SRui Ueyama   return Ret;
287be94e1b6SRafael Espindola }
288be94e1b6SRafael Espindola 
289b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
290b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
291be94e1b6SRafael Espindola     S->Live = false;
2924f1fca27SRafael Espindola     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
2934f1fca27SRafael Espindola         S == InX::DynStrTab)
2942af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
295647c1685SGeorge Rimar     discard(S->DependentSections);
296be94e1b6SRafael Espindola   }
297be94e1b6SRafael Espindola }
298be94e1b6SRafael Espindola 
299b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3008c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
301b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
302e7f912cdSRui Ueyama 
3038f99f73cSRui Ueyama   for (BaseCommand *Base : OutCmd.Commands) {
3048f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3057c3ff2ebSRafael Espindola     if (!Cmd)
3060b9ce6a4SRui Ueyama       continue;
30772e107f3SRui Ueyama 
30872e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
309e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3100b9ce6a4SRui Ueyama   }
311e71a3f8aSRafael Espindola 
3120b9ce6a4SRui Ueyama   return Ret;
3130b9ce6a4SRui Ueyama }
3140b9ce6a4SRui Ueyama 
315b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3165616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3175616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3185616adf6SRafael Espindola   // section values are:
3195616adf6SRafael Espindola   // * SHN_UNDEF
3205616adf6SRafael Espindola   // * SHN_ABS
3215616adf6SRafael Espindola   // * Any value meaning a regular section.
3225616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3235616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3245616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3255616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3265616adf6SRafael Espindola   Aether->SectionIndex = 1;
327906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
328c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
329c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
330c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
331c1ace40bSPeter Smith   // script parser.
332906e9a18SPeter Smith   CurAddressState = State.get();
333906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
33449592cf6SRafael Espindola   Dot = 0;
3355616adf6SRafael Espindola 
33692a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3370b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
33892a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3394cd7352cSRafael Espindola       addSymbol(Cmd);
3402ab5f73dSRui Ueyama       continue;
3412ab5f73dSRui Ueyama     }
3420b1b695aSRui Ueyama 
3438c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3448c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3457bd37870SRafael Espindola 
3460b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3470b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3488c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3497bd37870SRafael Espindola         discard(V);
35048c3f1ceSRui Ueyama         continue;
35148c3f1ceSRui Ueyama       }
3520b9ce6a4SRui Ueyama 
3530b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3540b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3550b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
35607d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3570b1b695aSRui Ueyama       //
3580b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
35907d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3608c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
361b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
362f94efdddSRui Ueyama           S->Assigned = false;
36392a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
36407d7c42cSGeorge Rimar         --I;
3657c3ff2ebSRafael Espindola         continue;
3667c3ff2ebSRafael Espindola       }
3677c3ff2ebSRafael Espindola 
3680b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
3690b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
3708c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
3718f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
3724cd7352cSRafael Espindola           addSymbol(OutCmd);
3737c3ff2ebSRafael Espindola 
3740b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
3750b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
3760b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
3778c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
3788c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
379b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
3800b1b695aSRui Ueyama           S->Alignment = Subalign;
38120d03194SEugene Leviant       }
3820b1b695aSRui Ueyama 
3830b1b695aSRui Ueyama       // Add input sections to an output section.
384d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
3858c022ca7SRafael Espindola         Factory.addInputSec(S, Sec->Name, Sec);
386660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
387660c9ab9SRafael Espindola       Sec->SectionIndex = I;
3888c022ca7SRafael Espindola       if (Sec->Noload)
389fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
39048c3f1ceSRui Ueyama     }
3914aa2ef5bSRafael Espindola   }
392c1ace40bSPeter Smith   CurAddressState = nullptr;
393db24d9c3SGeorge Rimar }
394e63d81bdSEugene Leviant 
39502ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
396cbfe9e94SPeter Smith   // Define start address
397e76231b6SRafael Espindola   uint64_t StartAddr = -1;
398cbfe9e94SPeter Smith 
399c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
400c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
401c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
402c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
403c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
404c60b4510SPeter Smith 
4058c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
4068c022ca7SRafael Espindola                       make<SymbolAssignment>(".",
407e76231b6SRafael Espindola                                              [=] {
4088c022ca7SRafael Espindola                                                return std::min(
4098c022ca7SRafael Espindola                                                    StartAddr,
4108c022ca7SRafael Espindola                                                    Config->ImageBase +
4118c022ca7SRafael Espindola                                                        elf::getHeaderSize());
412e76231b6SRafael Espindola                                              },
413e76231b6SRafael Espindola                                              ""));
414cbfe9e94SPeter Smith }
415cbfe9e94SPeter Smith 
4160b1b695aSRui Ueyama // Add sections that didn't match any sections command.
417b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
418d7faa916SRafael Espindola   unsigned NumCommands = Opt.Commands.size();
4194f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
420db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4214f013bb3SRafael Espindola       continue;
4224f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
423d7faa916SRafael Espindola     auto End = Opt.Commands.begin() + NumCommands;
424d7faa916SRafael Espindola     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
4258c022ca7SRafael Espindola       if (auto *Sec = dyn_cast<OutputSection>(Base))
4268c022ca7SRafael Espindola         return Sec->Name == Name;
4274f013bb3SRafael Espindola       return false;
4284f013bb3SRafael Espindola     });
429d7faa916SRafael Espindola     if (I == End) {
4304f013bb3SRafael Espindola       Factory.addInputSec(S, Name);
431*a2df2f09SRafael Espindola       assert(S->getOutputSection()->SectionIndex == INT_MAX);
432de8d9897SRafael Espindola     } else {
4338c022ca7SRafael Espindola       OutputSection *Sec = cast<OutputSection>(*I);
4348c022ca7SRafael Espindola       Factory.addInputSec(S, Name, Sec);
435660c9ab9SRafael Espindola       unsigned Index = std::distance(Opt.Commands.begin(), I);
436660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
437660c9ab9SRafael Espindola       Sec->SectionIndex = Index;
438660c9ab9SRafael Espindola     }
439d7faa916SRafael Espindola   }
4404f013bb3SRafael Espindola }
441e63d81bdSEugene Leviant 
4427c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
443906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
444906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
445906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4467c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4477c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4487c4eafa3SRafael Espindola 
4497c4eafa3SRafael Espindola   if (IsTbss)
450906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4517c4eafa3SRafael Espindola   else
4527c4eafa3SRafael Espindola     Dot = End;
4537c4eafa3SRafael Espindola   return End;
454a940e539SRafael Espindola }
455a940e539SRafael Espindola 
456b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
457f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4587c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
459906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
460d3190795SRafael Espindola 
461d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
462d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
463d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
464906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
465d3190795SRafael Espindola 
466b889744eSMeador Inge   // If there is a memory region associated with this input section, then
467b889744eSMeador Inge   // place the section in that region and update the region index.
468906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
469906e9a18SPeter Smith     uint64_t &CurOffset =
470906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
471f694d33fSGeorge Rimar     CurOffset += Pos - Before;
472906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
473906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
474906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
475906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
476906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
477906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
478b889744eSMeador Inge     }
479b889744eSMeador Inge   }
4802de509c3SRui Ueyama }
481ceabe80eSEugene Leviant 
482b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
483906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
484d3190795SRafael Espindola     return;
485d3190795SRafael Espindola 
486906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
487906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
488906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
489b71d6f7aSEugene Leviant 
490b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
491b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
492b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
493b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
494906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
495906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
496d3190795SRafael Espindola }
497d3190795SRafael Espindola 
498b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
4992e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5002e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5012e081a4fSRui Ueyama     assignSymbol(Cmd, true);
502d3190795SRafael Espindola     return;
50397403d15SEugene Leviant   }
504e38cbab5SGeorge Rimar 
505e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5062e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
507906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5082e081a4fSRui Ueyama     Dot += Cmd->Size;
509906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
510e38cbab5SGeorge Rimar     return;
511e38cbab5SGeorge Rimar   }
512e38cbab5SGeorge Rimar 
5132e081a4fSRui Ueyama   // Handle ASSERT().
5142e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5152e081a4fSRui Ueyama     Cmd->Expression();
516b2d99d6aSMeador Inge     return;
517b2d99d6aSMeador Inge   }
518b2d99d6aSMeador Inge 
5192e081a4fSRui Ueyama   // Handle a single input section description command.
5202e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
521e38cbab5SGeorge Rimar   // updates the output section size.
5222e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
523a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5243fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5253fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5263fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5273fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5282e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5292e081a4fSRui Ueyama       if (S->empty())
5303fb5a6dcSGeorge Rimar         continue;
5313fb5a6dcSGeorge Rimar 
5322e081a4fSRui Ueyama     if (!Sec->Live)
53378ef645fSGeorge Rimar       continue;
534906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
535a85e8ddaSRafael Espindola     output(Sec);
536ceabe80eSEugene Leviant   }
537ceabe80eSEugene Leviant }
538ceabe80eSEugene Leviant 
539b889744eSMeador Inge // This function searches for a memory region to place the given output
540b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
541b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5428c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
543b889744eSMeador Inge   // If a memory region name was specified in the output section command,
544b889744eSMeador Inge   // then try to find that region first.
5458c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5468c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
547b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
548b889744eSMeador Inge       return &It->second;
5498c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
550b889744eSMeador Inge     return nullptr;
551b889744eSMeador Inge   }
552b889744eSMeador Inge 
553d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
554d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
555d7c5400fSRui Ueyama   // anything for memory regions.
556cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
557b889744eSMeador Inge     return nullptr;
558b889744eSMeador Inge 
559b889744eSMeador Inge   // See if a region can be found by matching section flags.
5602e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
5612e081a4fSRui Ueyama     MemoryRegion &M = Pair.second;
5622e081a4fSRui Ueyama     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
5632e081a4fSRui Ueyama       return &M;
564b889744eSMeador Inge   }
565b889744eSMeador Inge 
566b889744eSMeador Inge   // Otherwise, no suitable region was found.
567b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
568b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
569b889744eSMeador Inge   return nullptr;
570b889744eSMeador Inge }
571b889744eSMeador Inge 
5720b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
5730b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
5748c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
575dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
576dece2808SRafael Espindola     Dot = 0;
5778c022ca7SRafael Espindola   else if (Sec->AddrExpr)
5788c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
579679828ffSRafael Espindola 
5808c022ca7SRafael Espindola   if (Sec->LMAExpr) {
5810c1c8085SGeorge Rimar     uint64_t D = Dot;
5828c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
5835784e96fSEugene Leviant   }
5845784e96fSEugene Leviant 
5858c022ca7SRafael Espindola   CurAddressState->MemRegion = Sec->MemRegion;
586906e9a18SPeter Smith   if (CurAddressState->MemRegion)
587906e9a18SPeter Smith     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
588b889744eSMeador Inge   switchTo(Sec);
5890b1b695aSRui Ueyama 
590d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
591d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
592906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
593d86a4e50SGeorge Rimar     return;
594d86a4e50SGeorge Rimar 
5958c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
596de8d9897SRafael Espindola     process(*C);
597d3190795SRafael Espindola }
598d3190795SRafael Espindola 
599b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6006d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6016d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6026d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6036d38e4dbSRafael Espindola   // clutter the output.
6046d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6056d38e4dbSRafael Espindola   // more aggressive at removing them.
6068c022ca7SRafael Espindola   auto Pos = std::remove_if(Opt.Commands.begin(), Opt.Commands.end(),
6078c022ca7SRafael Espindola                             [&](BaseCommand *Base) {
6088c022ca7SRafael Espindola                               if (auto *Sec = dyn_cast<OutputSection>(Base))
6098c022ca7SRafael Espindola                                 return !Sec->Live;
6100b1b695aSRui Ueyama                               return false;
6116d38e4dbSRafael Espindola                             });
6126d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
61307fe6129SRafael Espindola }
61407fe6129SRafael Espindola 
6158c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6168f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6178f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6186a53737cSRafael Espindola       return false;
6196a53737cSRafael Espindola   return true;
6206a53737cSRafael Espindola }
6216d38e4dbSRafael Espindola 
622b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6239546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6249546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6259546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6269546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6270c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
628660c9ab9SRafael Espindola 
629660c9ab9SRafael Espindola   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
6308c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I]);
6318c022ca7SRafael Espindola     if (!Sec)
6329546fffbSRafael Espindola       continue;
6338c022ca7SRafael Espindola     if (Sec->Live) {
6342b074553SRafael Espindola       Flags = Sec->Flags;
6359546fffbSRafael Espindola       continue;
6369546fffbSRafael Espindola     }
6379546fffbSRafael Espindola 
6388c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6396a53737cSRafael Espindola       continue;
6406a53737cSRafael Espindola 
6418c022ca7SRafael Espindola     Sec->Live = true;
6428c022ca7SRafael Espindola     Sec->SectionIndex = I;
6438c022ca7SRafael Espindola     Sec->Flags = Flags;
6449546fffbSRafael Espindola   }
645f7a17448SRafael Espindola }
646f7a17448SRafael Espindola 
647b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
648feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
649d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6508c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
6518c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
652d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6538c022ca7SRafael Espindola       if (Sec->AlignExpr)
6548c022ca7SRafael Espindola         Sec->updateAlignment(Sec->AlignExpr().getValue());
655d1960dc0SRafael Espindola     }
656d1960dc0SRafael Espindola   }
657feed7506SRafael Espindola 
658f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
659f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
660f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
661f7a17448SRafael Espindola   // Below is an example of such linker script:
662f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
663f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
664f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
665f7a17448SRafael Espindola   auto FirstPtLoad =
666f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
667f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
668f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
669f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
670f7a17448SRafael Espindola 
671f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
672f7a17448SRafael Espindola   // explicitly specify them.
6738f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
6748c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
6758c022ca7SRafael Espindola     if (!Sec)
676f7a17448SRafael Espindola       continue;
6778f99f73cSRui Ueyama 
6788c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
679a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
680a020d348SAndrew Ng       // headers to sections that are allocated.
6818c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
6828c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
683a020d348SAndrew Ng     } else {
6848c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
685f7a17448SRafael Espindola     }
686a020d348SAndrew Ng   }
6876a53737cSRafael Espindola 
6886a53737cSRafael Espindola   removeEmptyCommands();
6899546fffbSRafael Espindola }
6909546fffbSRafael Espindola 
691aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
6925aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
6938c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
6945aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
6955aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
6965aedebffSPeter Smith 
697aa354187SGeorge Rimar   auto It = llvm::find_if(
698aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
699aa354187SGeorge Rimar   if (It == Phdrs.end())
700d971e703SGeorge Rimar     return;
701aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
70202ed7575SRafael Espindola 
70302ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
70402ed7575SRafael Espindola   if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
70502ed7575SRafael Espindola     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
70602ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
70702ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
708d971e703SGeorge Rimar     return;
70902ed7575SRafael Espindola   }
71002ed7575SRafael Espindola 
71102ed7575SRafael Espindola   assert(FirstPTLoad->First == Out::ElfHeader);
71202ed7575SRafael Espindola   OutputSection *ActualFirst = nullptr;
7138c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
71402ed7575SRafael Espindola     if (Sec->FirstInPtLoad == Out::ElfHeader) {
71502ed7575SRafael Espindola       ActualFirst = Sec;
71602ed7575SRafael Espindola       break;
71702ed7575SRafael Espindola     }
71802ed7575SRafael Espindola   }
71902ed7575SRafael Espindola   if (ActualFirst) {
7208c022ca7SRafael Espindola     for (OutputSection *Sec : OutputSections)
72102ed7575SRafael Espindola       if (Sec->FirstInPtLoad == Out::ElfHeader)
72202ed7575SRafael Espindola         Sec->FirstInPtLoad = ActualFirst;
72302ed7575SRafael Espindola     FirstPTLoad->First = ActualFirst;
72402ed7575SRafael Espindola   } else {
725aa354187SGeorge Rimar     Phdrs.erase(It);
72602ed7575SRafael Espindola   }
72702ed7575SRafael Espindola 
728d971e703SGeorge Rimar   auto PhdrI = llvm::find_if(
729aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
73002ed7575SRafael Espindola   if (PhdrI != Phdrs.end())
73102ed7575SRafael Espindola     Phdrs.erase(PhdrI);
73202ed7575SRafael Espindola }
73302ed7575SRafael Espindola 
734906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
735906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
736906e9a18SPeter Smith     const MemoryRegion *MR = &MRI.second;
737906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
738906e9a18SPeter Smith   }
739906e9a18SPeter Smith }
740906e9a18SPeter Smith 
7415aedebffSPeter Smith void LinkerScript::assignAddresses() {
7427c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
743be607334SRafael Espindola   Dot = 0;
744906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
745c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
746c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
747c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
748c1ace40bSPeter Smith   // script parser.
749906e9a18SPeter Smith   CurAddressState = State.get();
75072dc195dSRafael Espindola   ErrorOnMissingSection = true;
75106f4743aSRafael Espindola   switchTo(Aether);
75206f4743aSRafael Espindola 
7538f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7548f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
755d379f735SRui Ueyama       assignSymbol(Cmd, false);
75605ef4cffSRui Ueyama       continue;
757652852c5SGeorge Rimar     }
758652852c5SGeorge Rimar 
7598f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
7604595df94SRafael Espindola       Cmd->Expression();
761eefa758eSGeorge Rimar       continue;
762eefa758eSGeorge Rimar     }
763eefa758eSGeorge Rimar 
7648c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
765a14b13d8SGeorge Rimar   }
766c1ace40bSPeter Smith   CurAddressState = nullptr;
767fb8978fcSDima Stepanov }
768652852c5SGeorge Rimar 
769464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
770aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
771aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
772bbe38602SEugene Leviant 
773464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
774464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
775bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
776aa354187SGeorge Rimar     PhdrEntry *Phdr =
777aa354187SGeorge Rimar         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
778bbe38602SEugene Leviant 
779bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
780aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
781bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
782aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
78356b21c86SEugene Leviant 
78456b21c86SEugene Leviant     if (Cmd.LMAExpr) {
785aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
786aa354187SGeorge Rimar       Phdr->HasLMA = true;
78756b21c86SEugene Leviant     }
788aa354187SGeorge Rimar     Ret.push_back(Phdr);
789bbe38602SEugene Leviant   }
790bbe38602SEugene Leviant 
791464daadcSRui Ueyama   // Add output sections to program headers.
7928c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
793bbe38602SEugene Leviant     // Assign headers specified by linker script
7948c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
795aa354187SGeorge Rimar       Ret[Id]->add(Sec);
796865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
797aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
798bbe38602SEugene Leviant     }
799bbe38602SEugene Leviant   }
800edebbdf1SRui Ueyama   return Ret;
801bbe38602SEugene Leviant }
802bbe38602SEugene Leviant 
803b8dd23f5SRui Ueyama bool LinkerScript::ignoreInterpSection() {
804f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
805f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
806e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
807e31d9886SRui Ueyama     return false;
808e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
809e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
810e31d9886SRui Ueyama       return false;
811e31d9886SRui Ueyama   return true;
812f9bc3bd2SEugene Leviant }
813f9bc3bd2SEugene Leviant 
814b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8154595df94SRafael Espindola   if (S == ".")
816906e9a18SPeter Smith     return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr, Loc};
817244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
81872dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
81941c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
82030f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
82141c7ab4aSGeorge Rimar       return {InX::Common, C->Offset, Loc};
82272dc195dSRafael Espindola   }
823f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
824884e786dSGeorge Rimar   return 0;
825884e786dSGeorge Rimar }
826884e786dSGeorge Rimar 
827244ef981SRafael Espindola bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
828f34f45fdSGeorge Rimar 
8296e9f98c1SAndrew Ng static const size_t NoPhdr = -1;
8306e9f98c1SAndrew Ng 
8312c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8322c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8338c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
83429c5a2a9SRui Ueyama   std::vector<size_t> Ret;
8356e9f98c1SAndrew Ng   for (StringRef PhdrName : Cmd->Phdrs) {
8366e9f98c1SAndrew Ng     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
8376e9f98c1SAndrew Ng     if (Index != NoPhdr)
8386e9f98c1SAndrew Ng       Ret.push_back(Index);
8396e9f98c1SAndrew Ng   }
84029c5a2a9SRui Ueyama   return Ret;
841bbe38602SEugene Leviant }
842bbe38602SEugene Leviant 
8436e9f98c1SAndrew Ng // Returns the index of the segment named PhdrName if found otherwise
8446e9f98c1SAndrew Ng // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
8456e9f98c1SAndrew Ng // (which can be used to explicitly specify that a section isn't assigned to a
8466e9f98c1SAndrew Ng // segment) then error.
847b8dd23f5SRui Ueyama size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
84829c5a2a9SRui Ueyama   size_t I = 0;
84929c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
85029c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
85129c5a2a9SRui Ueyama       return I;
85229c5a2a9SRui Ueyama     ++I;
85329c5a2a9SRui Ueyama   }
8546e9f98c1SAndrew Ng   if (PhdrName != "NONE")
8552a942c4bSEugene Leviant     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
8566e9f98c1SAndrew Ng   return NoPhdr;
85729c5a2a9SRui Ueyama }
858