1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===//
2f7c5fbb1SRui Ueyama //
3f7c5fbb1SRui Ueyama //                             The LLVM Linker
4f7c5fbb1SRui Ueyama //
5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source
6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details.
7f7c5fbb1SRui Ueyama //
8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
9f7c5fbb1SRui Ueyama //
10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script.
11f7c5fbb1SRui Ueyama //
12f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
13f7c5fbb1SRui Ueyama 
14717677afSRui Ueyama #include "LinkerScript.h"
15f7c5fbb1SRui Ueyama #include "Config.h"
161ebc8ed7SRui Ueyama #include "InputSection.h"
179381eb10SRui Ueyama #include "Memory.h"
18652852c5SGeorge Rimar #include "OutputSections.h"
1993c9af42SRui Ueyama #include "Strings.h"
20f7c5fbb1SRui Ueyama #include "SymbolTable.h"
2155518e7dSRui Ueyama #include "Symbols.h"
223fb5a6dcSGeorge Rimar #include "SyntheticSections.h"
2355b169bfSRafael Espindola #include "Target.h"
2455b169bfSRafael Espindola #include "Threads.h"
25bbe38602SEugene Leviant #include "Writer.h"
2622886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h"
2722886a28SEugene Zelenko #include "llvm/ADT/StringRef.h"
28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
2922886a28SEugene Zelenko #include "llvm/Support/Casting.h"
3022886a28SEugene Zelenko #include "llvm/Support/Endian.h"
3122886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
32f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
33f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
3422886a28SEugene Zelenko #include <algorithm>
3522886a28SEugene Zelenko #include <cassert>
3622886a28SEugene Zelenko #include <cstddef>
3722886a28SEugene Zelenko #include <cstdint>
3822886a28SEugene Zelenko #include <iterator>
3922886a28SEugene Zelenko #include <limits>
4022886a28SEugene Zelenko #include <string>
4122886a28SEugene Zelenko #include <vector>
42f7c5fbb1SRui Ueyama 
43f7c5fbb1SRui Ueyama using namespace llvm;
44652852c5SGeorge Rimar using namespace llvm::ELF;
451ebc8ed7SRui Ueyama using namespace llvm::object;
46e38cbab5SGeorge Rimar using namespace llvm::support::endian;
47f7c5fbb1SRui Ueyama using namespace lld;
48e0df00b9SRafael Espindola using namespace lld::elf;
49f7c5fbb1SRui Ueyama 
50a34da938SRui Ueyama LinkerScript *elf::Script;
51a34da938SRui Ueyama 
525d0ea70aSGeorge Rimar static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
535d0ea70aSGeorge Rimar   if (OutputSection *OS = InputSec->getOutputSection())
545d0ea70aSGeorge Rimar     return OS->Addr;
555d0ea70aSGeorge Rimar   error(Loc + ": unable to evaluate expression: input section " +
565d0ea70aSGeorge Rimar         InputSec->Name + " has no output section assigned");
575d0ea70aSGeorge Rimar   return 0;
58608cf670SGeorge Rimar }
595d0ea70aSGeorge Rimar 
605d0ea70aSGeorge Rimar uint64_t ExprValue::getValue() const {
615d0ea70aSGeorge Rimar   if (Sec)
625d0ea70aSGeorge Rimar     return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
635d0ea70aSGeorge Rimar                    Alignment);
643c6de1a6SPetr Hosek   return alignTo(Val, Alignment);
6572dc195dSRafael Espindola }
6672dc195dSRafael Espindola 
677ba5f47eSRafael Espindola uint64_t ExprValue::getSecAddr() const {
687ba5f47eSRafael Espindola   if (Sec)
695d0ea70aSGeorge Rimar     return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
707ba5f47eSRafael Espindola   return 0;
717ba5f47eSRafael Espindola }
727ba5f47eSRafael Espindola 
73a6acd23cSRafael Espindola uint64_t ExprValue::getSectionOffset() const {
74a6acd23cSRafael Espindola   return getValue() - getSecAddr();
75a6acd23cSRafael Espindola }
76a6acd23cSRafael Espindola 
77a5e8dd35SRafael Espindola static SymbolBody *addRegular(SymbolAssignment *Cmd) {
785e51f7d2SPetr Hosek   Symbol *Sym;
793dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
80244ef981SRafael Espindola   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
81244ef981SRafael Espindola                                               /*CanOmitFromDynSym*/ false,
825e51f7d2SPetr Hosek                                               /*File*/ nullptr);
835e51f7d2SPetr Hosek   Sym->Binding = STB_GLOBAL;
8472dc195dSRafael Espindola   ExprValue Value = Cmd->Expression();
8572dc195dSRafael Espindola   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
8601aa795fSGeorge Rimar 
8701aa795fSGeorge Rimar   // We want to set symbol values early if we can. This allows us to use symbols
8801aa795fSGeorge Rimar   // as variables in linker scripts. Doing so allows us to write expressions
8901aa795fSGeorge Rimar   // like this: `alignment = 16; . = ALIGN(., alignment)`
90*e4bad83eSRafael Espindola   uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
916e93d054SRafael Espindola   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
926e93d054SRafael Espindola                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
938f1f3c40SMeador Inge   return Sym->body();
94ceabe80eSEugene Leviant }
95ceabe80eSEugene Leviant 
968c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
978c022ca7SRafael Espindola                                                  StringRef Location) {
988c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
998c022ca7SRafael Espindola   OutputSection *Sec;
1008c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
10105c4f67cSRafael Espindola     // There was a forward reference.
1028c022ca7SRafael Espindola     Sec = SecRef;
10305c4f67cSRafael Espindola   } else {
1048c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
1058c022ca7SRafael Espindola     if (!SecRef)
1068c022ca7SRafael Espindola       SecRef = Sec;
10705c4f67cSRafael Espindola   }
1088c022ca7SRafael Espindola   Sec->Location = Location;
1098c022ca7SRafael Espindola   return Sec;
110851dc1e8SGeorge Rimar }
111851dc1e8SGeorge Rimar 
1128c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
1138c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
11405c4f67cSRafael Espindola   if (!CmdRef)
1158c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
11605c4f67cSRafael Espindola   return CmdRef;
117d83ce1b4SGeorge Rimar }
118d83ce1b4SGeorge Rimar 
119b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
12072dc195dSRafael Espindola   uint64_t Val = E().getValue();
1218c804d97SGeorge Rimar   if (Val < Dot && InSec)
1222ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
123906e9a18SPeter Smith           CurAddressState->OutSec->Name);
1244cd7352cSRafael Espindola   Dot = Val;
1254cd7352cSRafael Espindola   // Update to location counter means update to section size.
1264cd7352cSRafael Espindola   if (InSec)
127906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
128679828ffSRafael Espindola }
129679828ffSRafael Espindola 
130679828ffSRafael Espindola // Sets value of a symbol. Two kinds of symbols are processed: synthetic
131679828ffSRafael Espindola // symbols, whose value is an offset from beginning of section and regular
132679828ffSRafael Espindola // symbols whose value is absolute.
133b8dd23f5SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
134679828ffSRafael Espindola   if (Cmd->Name == ".") {
1352ee2d2dcSGeorge Rimar     setDot(Cmd->Expression, Cmd->Location, InSec);
1364cd7352cSRafael Espindola     return;
1374cd7352cSRafael Espindola   }
1384cd7352cSRafael Espindola 
139b2b70975SGeorge Rimar   if (!Cmd->Sym)
1408f1f3c40SMeador Inge     return;
1418f1f3c40SMeador Inge 
1425616adf6SRafael Espindola   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
14372dc195dSRafael Espindola   ExprValue V = Cmd->Expression();
14472dc195dSRafael Espindola   if (V.isAbsolute()) {
14572dc195dSRafael Espindola     Sym->Value = V.getValue();
14672dc195dSRafael Espindola   } else {
14772dc195dSRafael Espindola     Sym->Section = V.Sec;
148a6acd23cSRafael Espindola     Sym->Value = V.getSectionOffset();
149ea590d91SRafael Espindola   }
1508f1f3c40SMeador Inge }
1518f1f3c40SMeador Inge 
152b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1531602421cSRui Ueyama   if (Cmd->Name == ".")
1548f1f3c40SMeador Inge     return;
1558f1f3c40SMeador Inge 
1568f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1578f1f3c40SMeador Inge   // it is a referenced undefined symbol.
158244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1598f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1608f1f3c40SMeador Inge     return;
1618f1f3c40SMeador Inge 
162a5e8dd35SRafael Espindola   Cmd->Sym = addRegular(Cmd);
163ceabe80eSEugene Leviant }
164ceabe80eSEugene Leviant 
165076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
166076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
167076fe157SGeorge Rimar }
168076fe157SGeorge Rimar 
169eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
170eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
171eea3114fSGeorge Rimar }
172eea3114fSGeorge Rimar 
173eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
174eefa758eSGeorge Rimar   return C->Kind == AssertKind;
175eefa758eSGeorge Rimar }
176eefa758eSGeorge Rimar 
177e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
178e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
179e38cbab5SGeorge Rimar }
180e38cbab5SGeorge Rimar 
1811e30f07cSDmitry Mikulin static std::string filename(InputFile *File) {
1821e30f07cSDmitry Mikulin   if (!File)
183e0be2901SRui Ueyama     return "";
1841e30f07cSDmitry Mikulin   if (File->ArchiveName.empty())
1851e30f07cSDmitry Mikulin     return File->getName();
1861e30f07cSDmitry Mikulin   return (File->ArchiveName + "(" + File->getName() + ")").str();
187e0be2901SRui Ueyama }
188e0be2901SRui Ueyama 
189b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
190f300ca21SDmitry Mikulin   for (InputSectionDescription *ID : Opt.KeptSections) {
1911e30f07cSDmitry Mikulin     std::string Filename = filename(S->File);
192f300ca21SDmitry Mikulin     if (ID->FilePat.match(Filename))
193cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
194f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
195eea3114fSGeorge Rimar           return true;
196f300ca21SDmitry Mikulin   }
197eea3114fSGeorge Rimar   return false;
198eea3114fSGeorge Rimar }
199eea3114fSGeorge Rimar 
200ea93fe00SRui Ueyama // A helper function for the SORT() command.
201c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
202be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
203be394db3SGeorge Rimar   switch (K) {
204be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
205ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
206ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
207ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
208ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
209ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
210ea93fe00SRui Ueyama     };
211be394db3SGeorge Rimar   case SortSectionPolicy::Name:
212ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
213ea93fe00SRui Ueyama       return A->Name < B->Name;
214ea93fe00SRui Ueyama     };
215be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
216ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
217ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
218ea93fe00SRui Ueyama     };
219be394db3SGeorge Rimar   default:
220be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
221be394db3SGeorge Rimar   }
222742c3836SRui Ueyama }
2230702c4e8SGeorge Rimar 
224ea93fe00SRui Ueyama // A helper function for the SORT() command.
225b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
22606ae6836SGeorge Rimar                              ConstraintKind Kind) {
2278f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2288f66df92SGeorge Rimar     return true;
2292c7171bfSRui Ueyama 
2302c7171bfSRui Ueyama   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
2312c7171bfSRui Ueyama     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
23206ae6836SGeorge Rimar   });
2332c7171bfSRui Ueyama 
234e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
235e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
23606ae6836SGeorge Rimar }
23706ae6836SGeorge Rimar 
2386a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End,
239ee924709SRui Ueyama                          SortSectionPolicy K) {
240ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
24107171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
242ee924709SRui Ueyama }
243ee924709SRui Ueyama 
244d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
245d6bcde38SGeorge Rimar   if (Config->SymbolOrderingFile.empty())
246d6bcde38SGeorge Rimar     return;
247696a7f9aSGeorge Rimar   static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder();
248d6bcde38SGeorge Rimar   MutableArrayRef<InputSection *> In(Begin, End - Begin);
249d6bcde38SGeorge Rimar   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
250d6bcde38SGeorge Rimar }
251d6bcde38SGeorge Rimar 
252d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2536a1aa8d9SRafael Espindola std::vector<InputSection *>
25472e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2556a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2568c6a5aafSRui Ueyama 
25772e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
25872e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
25972e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
26072e107f3SRui Ueyama 
26172e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
26272e107f3SRui Ueyama       if (Sec->Assigned)
2638c6a5aafSRui Ueyama         continue;
26472e107f3SRui Ueyama 
265e39709b2SRafael Espindola       if (!Sec->Live) {
266e39709b2SRafael Espindola         reportDiscarded(Sec);
267e39709b2SRafael Espindola         continue;
268e39709b2SRafael Espindola       }
269e39709b2SRafael Espindola 
270908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
271908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
272908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
27372e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
274908a3d34SRafael Espindola         continue;
2758c6a5aafSRui Ueyama 
2761e30f07cSDmitry Mikulin       std::string Filename = filename(Sec->File);
27772e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
27872e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
27972e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
280e0be2901SRui Ueyama         continue;
28172e107f3SRui Ueyama 
2826a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
28372e107f3SRui Ueyama       Sec->Assigned = true;
284f94efdddSRui Ueyama     }
285d3190795SRafael Espindola 
286ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
287ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
288ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
289ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
290ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
291ee924709SRui Ueyama     //
292ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
293ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
294ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
295ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
296ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
297d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
298d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
2996a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
3006a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
301d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
302d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
303d6bcde38SGeorge Rimar       sortBySymbolOrder(Begin, End);
304d6bcde38SGeorge Rimar       continue;
305d6bcde38SGeorge Rimar     }
30607171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
30707171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
30807171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
309ee924709SRui Ueyama       else
31007171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
31107171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
31207171f21SGeorge Rimar     }
313ee924709SRui Ueyama   }
31472e107f3SRui Ueyama   return Ret;
315be94e1b6SRafael Espindola }
316be94e1b6SRafael Espindola 
317b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
318b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
319be94e1b6SRafael Espindola     S->Live = false;
3201e30f07cSDmitry Mikulin     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
3211e30f07cSDmitry Mikulin         S == InX::DynStrTab)
3222af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
323647c1685SGeorge Rimar     discard(S->DependentSections);
324be94e1b6SRafael Espindola   }
325be94e1b6SRafael Espindola }
326be94e1b6SRafael Espindola 
327b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3288c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
329b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
330e7f912cdSRui Ueyama 
3318f99f73cSRui Ueyama   for (BaseCommand *Base : OutCmd.Commands) {
3328f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3337c3ff2ebSRafael Espindola     if (!Cmd)
3340b9ce6a4SRui Ueyama       continue;
33572e107f3SRui Ueyama 
33672e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
337e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3380b9ce6a4SRui Ueyama   }
339e71a3f8aSRafael Espindola 
3400b9ce6a4SRui Ueyama   return Ret;
3410b9ce6a4SRui Ueyama }
3420b9ce6a4SRui Ueyama 
343b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3445616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3455616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3465616adf6SRafael Espindola   // section values are:
3475616adf6SRafael Espindola   // * SHN_UNDEF
3485616adf6SRafael Espindola   // * SHN_ABS
3495616adf6SRafael Espindola   // * Any value meaning a regular section.
3505616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3515616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3525616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3535616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3545616adf6SRafael Espindola   Aether->SectionIndex = 1;
355906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
356c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
357c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
358c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
359c1ace40bSPeter Smith   // script parser.
360906e9a18SPeter Smith   CurAddressState = State.get();
361906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
36249592cf6SRafael Espindola   Dot = 0;
3635616adf6SRafael Espindola 
36492a5ba6dSRui Ueyama   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
3650b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
36692a5ba6dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
3674cd7352cSRafael Espindola       addSymbol(Cmd);
3682ab5f73dSRui Ueyama       continue;
3692ab5f73dSRui Ueyama     }
3700b1b695aSRui Ueyama 
3718c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
3728c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3737bd37870SRafael Espindola 
3740b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3750b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3768c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3777bd37870SRafael Espindola         discard(V);
37848c3f1ceSRui Ueyama         continue;
37948c3f1ceSRui Ueyama       }
3800b9ce6a4SRui Ueyama 
3810b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3820b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3830b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
38407d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3850b1b695aSRui Ueyama       //
3860b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
38707d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
3888c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
389b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
390f94efdddSRui Ueyama           S->Assigned = false;
39192a5ba6dSRui Ueyama         Opt.Commands.erase(Opt.Commands.begin() + I);
39207d7c42cSGeorge Rimar         --I;
3937c3ff2ebSRafael Espindola         continue;
3947c3ff2ebSRafael Espindola       }
3957c3ff2ebSRafael Espindola 
3960b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
3970b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
3988c022ca7SRafael Espindola       for (BaseCommand *Base : Sec->Commands)
3998f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4004cd7352cSRafael Espindola           addSymbol(OutCmd);
4017c3ff2ebSRafael Espindola 
4020b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4030b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4040b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4058c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4068c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
407b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4080b1b695aSRui Ueyama           S->Alignment = Subalign;
40920d03194SEugene Leviant       }
4100b1b695aSRui Ueyama 
4110b1b695aSRui Ueyama       // Add input sections to an output section.
412d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4138c022ca7SRafael Espindola         Factory.addInputSec(S, Sec->Name, Sec);
414660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
415660c9ab9SRafael Espindola       Sec->SectionIndex = I;
4168c022ca7SRafael Espindola       if (Sec->Noload)
417fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
41848c3f1ceSRui Ueyama     }
4194aa2ef5bSRafael Espindola   }
420c1ace40bSPeter Smith   CurAddressState = nullptr;
421db24d9c3SGeorge Rimar }
422e63d81bdSEugene Leviant 
42302ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
424cbfe9e94SPeter Smith   // Define start address
425e76231b6SRafael Espindola   uint64_t StartAddr = -1;
426cbfe9e94SPeter Smith 
427c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
428c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
429c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
430c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
431c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
432c60b4510SPeter Smith 
4338c022ca7SRafael Espindola   Opt.Commands.insert(Opt.Commands.begin(),
4348c022ca7SRafael Espindola                       make<SymbolAssignment>(".",
435e76231b6SRafael Espindola                                              [=] {
4368c022ca7SRafael Espindola                                                return std::min(
4378c022ca7SRafael Espindola                                                    StartAddr,
4388c022ca7SRafael Espindola                                                    Config->ImageBase +
4398c022ca7SRafael Espindola                                                        elf::getHeaderSize());
440e76231b6SRafael Espindola                                              },
441e76231b6SRafael Espindola                                              ""));
442cbfe9e94SPeter Smith }
443cbfe9e94SPeter Smith 
4440b1b695aSRui Ueyama // Add sections that didn't match any sections command.
445b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
446d7faa916SRafael Espindola   unsigned NumCommands = Opt.Commands.size();
4474f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
448db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4494f013bb3SRafael Espindola       continue;
4504f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
451d7faa916SRafael Espindola     auto End = Opt.Commands.begin() + NumCommands;
452d7faa916SRafael Espindola     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
4538c022ca7SRafael Espindola       if (auto *Sec = dyn_cast<OutputSection>(Base))
4548c022ca7SRafael Espindola         return Sec->Name == Name;
4554f013bb3SRafael Espindola       return false;
4564f013bb3SRafael Espindola     });
457d7faa916SRafael Espindola     if (I == End) {
4584f013bb3SRafael Espindola       Factory.addInputSec(S, Name);
459a2df2f09SRafael Espindola       assert(S->getOutputSection()->SectionIndex == INT_MAX);
460de8d9897SRafael Espindola     } else {
4618c022ca7SRafael Espindola       OutputSection *Sec = cast<OutputSection>(*I);
4628c022ca7SRafael Espindola       Factory.addInputSec(S, Name, Sec);
463660c9ab9SRafael Espindola       unsigned Index = std::distance(Opt.Commands.begin(), I);
464660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
465660c9ab9SRafael Espindola       Sec->SectionIndex = Index;
466660c9ab9SRafael Espindola     }
467d7faa916SRafael Espindola   }
4684f013bb3SRafael Espindola }
469e63d81bdSEugene Leviant 
4707c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
471906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
472906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
473906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4747c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4757c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4767c4eafa3SRafael Espindola 
4777c4eafa3SRafael Espindola   if (IsTbss)
478906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4797c4eafa3SRafael Espindola   else
4807c4eafa3SRafael Espindola     Dot = End;
4817c4eafa3SRafael Espindola   return End;
482a940e539SRafael Espindola }
483a940e539SRafael Espindola 
484b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
485f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
4867c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
487906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
488d3190795SRafael Espindola 
489d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
490d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
491d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
492906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
493d3190795SRafael Espindola 
494b889744eSMeador Inge   // If there is a memory region associated with this input section, then
495b889744eSMeador Inge   // place the section in that region and update the region index.
496906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
497906e9a18SPeter Smith     uint64_t &CurOffset =
498906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
499f694d33fSGeorge Rimar     CurOffset += Pos - Before;
500906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
501906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
502906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
503906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
504906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
505906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
506b889744eSMeador Inge     }
507b889744eSMeador Inge   }
5082de509c3SRui Ueyama }
509ceabe80eSEugene Leviant 
510b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
511906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
512d3190795SRafael Espindola     return;
513d3190795SRafael Espindola 
514906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
515906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
516906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
517b71d6f7aSEugene Leviant 
518b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
519b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
520b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
521b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
522906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
523906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
524d3190795SRafael Espindola }
525d3190795SRafael Espindola 
526b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5272e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5282e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5292e081a4fSRui Ueyama     assignSymbol(Cmd, true);
530d3190795SRafael Espindola     return;
53197403d15SEugene Leviant   }
532e38cbab5SGeorge Rimar 
533e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5342e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
535906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5362e081a4fSRui Ueyama     Dot += Cmd->Size;
537906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
538e38cbab5SGeorge Rimar     return;
539e38cbab5SGeorge Rimar   }
540e38cbab5SGeorge Rimar 
5412e081a4fSRui Ueyama   // Handle ASSERT().
5422e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5432e081a4fSRui Ueyama     Cmd->Expression();
544b2d99d6aSMeador Inge     return;
545b2d99d6aSMeador Inge   }
546b2d99d6aSMeador Inge 
5472e081a4fSRui Ueyama   // Handle a single input section description command.
5482e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
549e38cbab5SGeorge Rimar   // updates the output section size.
5502e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
551a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5523fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5533fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5543fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5553fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5562e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5572e081a4fSRui Ueyama       if (S->empty())
5583fb5a6dcSGeorge Rimar         continue;
5593fb5a6dcSGeorge Rimar 
5602e081a4fSRui Ueyama     if (!Sec->Live)
56178ef645fSGeorge Rimar       continue;
562906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
563a85e8ddaSRafael Espindola     output(Sec);
564ceabe80eSEugene Leviant   }
565ceabe80eSEugene Leviant }
566ceabe80eSEugene Leviant 
567b889744eSMeador Inge // This function searches for a memory region to place the given output
568b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
569b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5708c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
571b889744eSMeador Inge   // If a memory region name was specified in the output section command,
572b889744eSMeador Inge   // then try to find that region first.
5738c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
5748c022ca7SRafael Espindola     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
575b889744eSMeador Inge     if (It != Opt.MemoryRegions.end())
5765f37541cSGeorge Rimar       return It->second;
5778c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
578b889744eSMeador Inge     return nullptr;
579b889744eSMeador Inge   }
580b889744eSMeador Inge 
581d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
582d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
583d7c5400fSRui Ueyama   // anything for memory regions.
584cc400cc8SRui Ueyama   if (Opt.MemoryRegions.empty())
585b889744eSMeador Inge     return nullptr;
586b889744eSMeador Inge 
587b889744eSMeador Inge   // See if a region can be found by matching section flags.
5882e081a4fSRui Ueyama   for (auto &Pair : Opt.MemoryRegions) {
5895f37541cSGeorge Rimar     MemoryRegion *M = Pair.second;
5905f37541cSGeorge Rimar     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
5915f37541cSGeorge Rimar       return M;
592b889744eSMeador Inge   }
593b889744eSMeador Inge 
594b889744eSMeador Inge   // Otherwise, no suitable region was found.
595b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
596b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
597b889744eSMeador Inge   return nullptr;
598b889744eSMeador Inge }
599b889744eSMeador Inge 
6000b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6010b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6028c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
603dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
604dece2808SRafael Espindola     Dot = 0;
6058c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6068c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
607679828ffSRafael Espindola 
608c2dffe3aSGeorge Rimar   CurAddressState->MemRegion = Sec->MemRegion;
609c2dffe3aSGeorge Rimar   if (CurAddressState->MemRegion)
610c2dffe3aSGeorge Rimar     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
611c2dffe3aSGeorge Rimar 
6128c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6130c1c8085SGeorge Rimar     uint64_t D = Dot;
6148c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6155784e96fSEugene Leviant   }
6165784e96fSEugene Leviant 
617b889744eSMeador Inge   switchTo(Sec);
6180b1b695aSRui Ueyama 
619d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
620d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
621906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
622d86a4e50SGeorge Rimar     return;
623d86a4e50SGeorge Rimar 
6248c022ca7SRafael Espindola   for (BaseCommand *C : Sec->Commands)
625de8d9897SRafael Espindola     process(*C);
626d3190795SRafael Espindola }
627d3190795SRafael Espindola 
628b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6296d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6306d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6316d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6326d38e4dbSRafael Espindola   // clutter the output.
6336d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6346d38e4dbSRafael Espindola   // more aggressive at removing them.
63560608a8aSGeorge Rimar   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
6368c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6378c022ca7SRafael Espindola       return !Sec->Live;
6380b1b695aSRui Ueyama     return false;
6396d38e4dbSRafael Espindola   });
64007fe6129SRafael Espindola }
64107fe6129SRafael Espindola 
6428c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
6438f99f73cSRui Ueyama   for (BaseCommand *Base : Cmd.Commands)
6448f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6456a53737cSRafael Espindola       return false;
6466a53737cSRafael Espindola   return true;
6476a53737cSRafael Espindola }
6486d38e4dbSRafael Espindola 
649b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6509546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6519546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6529546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6539546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6540c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
655660c9ab9SRafael Espindola 
6568962db91SGeorge Rimar   for (BaseCommand * Cmd : Opt.Commands) {
6578962db91SGeorge Rimar     auto *Sec = dyn_cast<OutputSection>(Cmd);
6588c022ca7SRafael Espindola     if (!Sec)
6599546fffbSRafael Espindola       continue;
6608c022ca7SRafael Espindola     if (Sec->Live) {
6612b074553SRafael Espindola       Flags = Sec->Flags;
6629546fffbSRafael Espindola       continue;
6639546fffbSRafael Espindola     }
6649546fffbSRafael Espindola 
6658c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6666a53737cSRafael Espindola       continue;
6676a53737cSRafael Espindola 
6688c022ca7SRafael Espindola     Sec->Live = true;
6698c022ca7SRafael Espindola     Sec->Flags = Flags;
6709546fffbSRafael Espindola   }
671f7a17448SRafael Espindola }
672f7a17448SRafael Espindola 
673b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
674feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
675d1960dc0SRafael Espindola   for (BaseCommand *Base : Opt.Commands) {
6768c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
6778c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
678d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6798c022ca7SRafael Espindola       if (Sec->AlignExpr)
6808c022ca7SRafael Espindola         Sec->updateAlignment(Sec->AlignExpr().getValue());
681d1960dc0SRafael Espindola     }
682d1960dc0SRafael Espindola   }
683feed7506SRafael Espindola 
684f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
685f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
686f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
687f7a17448SRafael Espindola   // Below is an example of such linker script:
688f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
689f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
690f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
691f7a17448SRafael Espindola   auto FirstPtLoad =
692f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
693f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
694f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
695f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
696f7a17448SRafael Espindola 
697f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
698f7a17448SRafael Espindola   // explicitly specify them.
6998f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7008c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7018c022ca7SRafael Espindola     if (!Sec)
702f7a17448SRafael Espindola       continue;
7038f99f73cSRui Ueyama 
7048c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
705a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
706a020d348SAndrew Ng       // headers to sections that are allocated.
7078c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7088c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
709a020d348SAndrew Ng     } else {
7108c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
711f7a17448SRafael Espindola     }
712a020d348SAndrew Ng   }
7136a53737cSRafael Espindola 
7146a53737cSRafael Espindola   removeEmptyCommands();
7159546fffbSRafael Espindola }
7169546fffbSRafael Espindola 
717582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) {
718582ede89SGeorge Rimar   for (OutputSection *Sec : OutputSections)
719582ede89SGeorge Rimar     if (Sec->PtLoad == Load)
720582ede89SGeorge Rimar       return Sec;
721582ede89SGeorge Rimar   return nullptr;
722582ede89SGeorge Rimar }
723582ede89SGeorge Rimar 
724b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections,
725b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier.
726b93c5b9fSPetr Hosek //
727b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first
728b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers
729b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not
730b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common
731b93c5b9fSPetr Hosek // in embedded systems.
732b93c5b9fSPetr Hosek //
733b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the
734b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
735aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7365aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7378c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7385aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7395aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7405aedebffSPeter Smith 
741aa354187SGeorge Rimar   auto It = llvm::find_if(
742aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
743aa354187SGeorge Rimar   if (It == Phdrs.end())
744d971e703SGeorge Rimar     return;
745aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
74602ed7575SRafael Espindola 
74702ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
748b93c5b9fSPetr Hosek   // When linker script with SECTIONS is being used, don't output headers
749b93c5b9fSPetr Hosek   // unless there's a space for them.
750b93c5b9fSPetr Hosek   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
751b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
752b93c5b9fSPetr Hosek     Min = Opt.HasSections ? Base
753b93c5b9fSPetr Hosek                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
75402ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
75502ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
756d971e703SGeorge Rimar     return;
75702ed7575SRafael Espindola   }
75802ed7575SRafael Espindola 
759582ede89SGeorge Rimar   Out::ElfHeader->PtLoad = nullptr;
760582ede89SGeorge Rimar   Out::ProgramHeaders->PtLoad = nullptr;
7616823c5f0SGeorge Rimar   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
76202ed7575SRafael Espindola 
76360608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
76460608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
76502ed7575SRafael Espindola }
76602ed7575SRafael Espindola 
767906e9a18SPeter Smith LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
768906e9a18SPeter Smith   for (auto &MRI : Opt.MemoryRegions) {
7695f37541cSGeorge Rimar     const MemoryRegion *MR = MRI.second;
770906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
771906e9a18SPeter Smith   }
772906e9a18SPeter Smith }
773906e9a18SPeter Smith 
7745aedebffSPeter Smith void LinkerScript::assignAddresses() {
7757c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
776be607334SRafael Espindola   Dot = 0;
777906e9a18SPeter Smith   auto State = make_unique<AddressState>(Opt);
778c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
779c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
780c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
781c1ace40bSPeter Smith   // script parser.
782906e9a18SPeter Smith   CurAddressState = State.get();
78372dc195dSRafael Espindola   ErrorOnMissingSection = true;
78406f4743aSRafael Espindola   switchTo(Aether);
78506f4743aSRafael Espindola 
7868f99f73cSRui Ueyama   for (BaseCommand *Base : Opt.Commands) {
7878f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
788d379f735SRui Ueyama       assignSymbol(Cmd, false);
78905ef4cffSRui Ueyama       continue;
790652852c5SGeorge Rimar     }
791652852c5SGeorge Rimar 
7928f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
7934595df94SRafael Espindola       Cmd->Expression();
794eefa758eSGeorge Rimar       continue;
795eefa758eSGeorge Rimar     }
796eefa758eSGeorge Rimar 
7978c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
798a14b13d8SGeorge Rimar   }
799c1ace40bSPeter Smith   CurAddressState = nullptr;
800fb8978fcSDima Stepanov }
801652852c5SGeorge Rimar 
802464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
803aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
804aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
805bbe38602SEugene Leviant 
806464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
807464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
808bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
809aa354187SGeorge Rimar     PhdrEntry *Phdr =
810aa354187SGeorge Rimar         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
811bbe38602SEugene Leviant 
812bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
813aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
814bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
815aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
81656b21c86SEugene Leviant 
81756b21c86SEugene Leviant     if (Cmd.LMAExpr) {
818aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
819aa354187SGeorge Rimar       Phdr->HasLMA = true;
82056b21c86SEugene Leviant     }
821aa354187SGeorge Rimar     Ret.push_back(Phdr);
822bbe38602SEugene Leviant   }
823bbe38602SEugene Leviant 
824464daadcSRui Ueyama   // Add output sections to program headers.
8258c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
826bbe38602SEugene Leviant     // Assign headers specified by linker script
8278c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
828aa354187SGeorge Rimar       Ret[Id]->add(Sec);
829865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
830aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
831bbe38602SEugene Leviant     }
832bbe38602SEugene Leviant   }
833edebbdf1SRui Ueyama   return Ret;
834bbe38602SEugene Leviant }
835bbe38602SEugene Leviant 
836b8dd23f5SRui Ueyama bool LinkerScript::ignoreInterpSection() {
837f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
838f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
839e31d9886SRui Ueyama   if (Opt.PhdrsCommands.empty())
840e31d9886SRui Ueyama     return false;
841e31d9886SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
842e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
843e31d9886SRui Ueyama       return false;
844e31d9886SRui Ueyama   return true;
845f9bc3bd2SEugene Leviant }
846f9bc3bd2SEugene Leviant 
847b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8487e5b0a59SGeorge Rimar   if (S == ".") {
8497e5b0a59SGeorge Rimar     if (CurAddressState)
8507e5b0a59SGeorge Rimar       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
8517e5b0a59SGeorge Rimar               Loc};
8527e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8537e5b0a59SGeorge Rimar     return 0;
8547e5b0a59SGeorge Rimar   }
855244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
85672dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
85741c7ab4aSGeorge Rimar       return {D->Section, D->Value, Loc};
85830f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
85967df57a2SRafael Espindola       return {C->Section, 0, Loc};
86072dc195dSRafael Espindola   }
861f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
862884e786dSGeorge Rimar   return 0;
863884e786dSGeorge Rimar }
864884e786dSGeorge Rimar 
865244ef981SRafael Espindola bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
866f34f45fdSGeorge Rimar 
8676e9f98c1SAndrew Ng static const size_t NoPhdr = -1;
8686e9f98c1SAndrew Ng 
8692c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8702c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8718c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
87229c5a2a9SRui Ueyama   std::vector<size_t> Ret;
8736e9f98c1SAndrew Ng   for (StringRef PhdrName : Cmd->Phdrs) {
8746e9f98c1SAndrew Ng     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
8756e9f98c1SAndrew Ng     if (Index != NoPhdr)
8766e9f98c1SAndrew Ng       Ret.push_back(Index);
8776e9f98c1SAndrew Ng   }
87829c5a2a9SRui Ueyama   return Ret;
879bbe38602SEugene Leviant }
880bbe38602SEugene Leviant 
8816e9f98c1SAndrew Ng // Returns the index of the segment named PhdrName if found otherwise
8826e9f98c1SAndrew Ng // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
8836e9f98c1SAndrew Ng // (which can be used to explicitly specify that a section isn't assigned to a
8846e9f98c1SAndrew Ng // segment) then error.
885b8dd23f5SRui Ueyama size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
88629c5a2a9SRui Ueyama   size_t I = 0;
88729c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
88829c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
88929c5a2a9SRui Ueyama       return I;
89029c5a2a9SRui Ueyama     ++I;
89129c5a2a9SRui Ueyama   }
8926e9f98c1SAndrew Ng   if (PhdrName != "NONE")
8932a942c4bSEugene Leviant     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
8946e9f98c1SAndrew Ng   return NoPhdr;
89529c5a2a9SRui Ueyama }
896