1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===//
2f7c5fbb1SRui Ueyama //
3f7c5fbb1SRui Ueyama //                             The LLVM Linker
4f7c5fbb1SRui Ueyama //
5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source
6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details.
7f7c5fbb1SRui Ueyama //
8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
9f7c5fbb1SRui Ueyama //
10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script.
11f7c5fbb1SRui Ueyama //
12f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
13f7c5fbb1SRui Ueyama 
14717677afSRui Ueyama #include "LinkerScript.h"
15f7c5fbb1SRui Ueyama #include "Config.h"
161ebc8ed7SRui Ueyama #include "InputSection.h"
179381eb10SRui Ueyama #include "Memory.h"
18652852c5SGeorge Rimar #include "OutputSections.h"
1993c9af42SRui Ueyama #include "Strings.h"
20f7c5fbb1SRui Ueyama #include "SymbolTable.h"
2155518e7dSRui Ueyama #include "Symbols.h"
223fb5a6dcSGeorge Rimar #include "SyntheticSections.h"
2355b169bfSRafael Espindola #include "Target.h"
2455b169bfSRafael Espindola #include "Threads.h"
25bbe38602SEugene Leviant #include "Writer.h"
2622886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h"
2722886a28SEugene Zelenko #include "llvm/ADT/StringRef.h"
28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
2922886a28SEugene Zelenko #include "llvm/Support/Casting.h"
3022886a28SEugene Zelenko #include "llvm/Support/Endian.h"
3122886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
32f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
33f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
3422886a28SEugene Zelenko #include <algorithm>
3522886a28SEugene Zelenko #include <cassert>
3622886a28SEugene Zelenko #include <cstddef>
3722886a28SEugene Zelenko #include <cstdint>
3822886a28SEugene Zelenko #include <iterator>
3922886a28SEugene Zelenko #include <limits>
4022886a28SEugene Zelenko #include <string>
4122886a28SEugene Zelenko #include <vector>
42f7c5fbb1SRui Ueyama 
43f7c5fbb1SRui Ueyama using namespace llvm;
44652852c5SGeorge Rimar using namespace llvm::ELF;
451ebc8ed7SRui Ueyama using namespace llvm::object;
46e38cbab5SGeorge Rimar using namespace llvm::support::endian;
47f7c5fbb1SRui Ueyama using namespace lld;
48e0df00b9SRafael Espindola using namespace lld::elf;
49f7c5fbb1SRui Ueyama 
50a34da938SRui Ueyama LinkerScript *elf::Script;
51a34da938SRui Ueyama 
525d0ea70aSGeorge Rimar static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
535d0ea70aSGeorge Rimar   if (OutputSection *OS = InputSec->getOutputSection())
545d0ea70aSGeorge Rimar     return OS->Addr;
555d0ea70aSGeorge Rimar   error(Loc + ": unable to evaluate expression: input section " +
565d0ea70aSGeorge Rimar         InputSec->Name + " has no output section assigned");
575d0ea70aSGeorge Rimar   return 0;
58608cf670SGeorge Rimar }
595d0ea70aSGeorge Rimar 
605d0ea70aSGeorge Rimar uint64_t ExprValue::getValue() const {
615d0ea70aSGeorge Rimar   if (Sec)
625d0ea70aSGeorge Rimar     return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
635d0ea70aSGeorge Rimar                    Alignment);
643c6de1a6SPetr Hosek   return alignTo(Val, Alignment);
6572dc195dSRafael Espindola }
6672dc195dSRafael Espindola 
677ba5f47eSRafael Espindola uint64_t ExprValue::getSecAddr() const {
687ba5f47eSRafael Espindola   if (Sec)
695d0ea70aSGeorge Rimar     return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
707ba5f47eSRafael Espindola   return 0;
717ba5f47eSRafael Espindola }
727ba5f47eSRafael Espindola 
73a6acd23cSRafael Espindola uint64_t ExprValue::getSectionOffset() const {
748b250344SRafael Espindola   // If the alignment is trivial, we don't have to compute the full
758b250344SRafael Espindola   // value to know the offset. This allows this function to succeed in
768b250344SRafael Espindola   // cases where the output section is not yet known.
778b250344SRafael Espindola   if (Alignment == 1)
788b250344SRafael Espindola     return Val;
79a6acd23cSRafael Espindola   return getValue() - getSecAddr();
80a6acd23cSRafael Espindola }
81a6acd23cSRafael Espindola 
828c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name,
838c022ca7SRafael Espindola                                                  StringRef Location) {
848c022ca7SRafael Espindola   OutputSection *&SecRef = NameToOutputSection[Name];
858c022ca7SRafael Espindola   OutputSection *Sec;
868c022ca7SRafael Espindola   if (SecRef && SecRef->Location.empty()) {
8705c4f67cSRafael Espindola     // There was a forward reference.
888c022ca7SRafael Espindola     Sec = SecRef;
8905c4f67cSRafael Espindola   } else {
908c022ca7SRafael Espindola     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
918c022ca7SRafael Espindola     if (!SecRef)
928c022ca7SRafael Espindola       SecRef = Sec;
9305c4f67cSRafael Espindola   }
948c022ca7SRafael Espindola   Sec->Location = Location;
958c022ca7SRafael Espindola   return Sec;
96851dc1e8SGeorge Rimar }
97851dc1e8SGeorge Rimar 
988c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
998c022ca7SRafael Espindola   OutputSection *&CmdRef = NameToOutputSection[Name];
10005c4f67cSRafael Espindola   if (!CmdRef)
1018c022ca7SRafael Espindola     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
10205c4f67cSRafael Espindola   return CmdRef;
103d83ce1b4SGeorge Rimar }
104d83ce1b4SGeorge Rimar 
105b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
10672dc195dSRafael Espindola   uint64_t Val = E().getValue();
1078c804d97SGeorge Rimar   if (Val < Dot && InSec)
1082ee2d2dcSGeorge Rimar     error(Loc + ": unable to move location counter backward for: " +
109906e9a18SPeter Smith           CurAddressState->OutSec->Name);
1104cd7352cSRafael Espindola   Dot = Val;
11118d19687SRui Ueyama 
1124cd7352cSRafael Espindola   // Update to location counter means update to section size.
1134cd7352cSRafael Espindola   if (InSec)
114906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
115679828ffSRafael Espindola }
116679828ffSRafael Espindola 
11718d19687SRui Ueyama // This function is called from processCommands, while we are
11818d19687SRui Ueyama // fixing the output section layout.
119b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
1201602421cSRui Ueyama   if (Cmd->Name == ".")
1218f1f3c40SMeador Inge     return;
1228f1f3c40SMeador Inge 
1238f1f3c40SMeador Inge   // If a symbol was in PROVIDE(), we need to define it only when
1248f1f3c40SMeador Inge   // it is a referenced undefined symbol.
125244ef981SRafael Espindola   SymbolBody *B = Symtab->find(Cmd->Name);
1268f1f3c40SMeador Inge   if (Cmd->Provide && (!B || B->isDefined()))
1278f1f3c40SMeador Inge     return;
1288f1f3c40SMeador Inge 
12918d19687SRui Ueyama   // Define a symbol.
13018d19687SRui Ueyama   Symbol *Sym;
13118d19687SRui Ueyama   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
13218d19687SRui Ueyama   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
13318d19687SRui Ueyama                                               /*CanOmitFromDynSym*/ false,
13418d19687SRui Ueyama                                               /*File*/ nullptr);
13518d19687SRui Ueyama   Sym->Binding = STB_GLOBAL;
13618d19687SRui Ueyama   ExprValue Value = Cmd->Expression();
13718d19687SRui Ueyama   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
13818d19687SRui Ueyama 
13918d19687SRui Ueyama   // When this function is called, section addresses have not been
14018d19687SRui Ueyama   // fixed yet. So, we may or may not know the value of the RHS
14118d19687SRui Ueyama   // expression.
14218d19687SRui Ueyama   //
14318d19687SRui Ueyama   // For example, if an expression is `x = 42`, we know x is always 42.
14418d19687SRui Ueyama   // However, if an expression is `x = .`, there's no way to know its
14518d19687SRui Ueyama   // value at the moment.
14618d19687SRui Ueyama   //
14718d19687SRui Ueyama   // We want to set symbol values early if we can. This allows us to
14818d19687SRui Ueyama   // use symbols as variables in linker scripts. Doing so allows us to
14918d19687SRui Ueyama   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
15018d19687SRui Ueyama   uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
15118d19687SRui Ueyama 
15218d19687SRui Ueyama   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
15318d19687SRui Ueyama                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
15418d19687SRui Ueyama   Cmd->Sym = cast<DefinedRegular>(Sym->body());
15518d19687SRui Ueyama }
15618d19687SRui Ueyama 
15718d19687SRui Ueyama // This function is called from assignAddresses, while we are
15818d19687SRui Ueyama // fixing the output section addresses. This function is supposed
15918d19687SRui Ueyama // to set the final value for a given symbol assignment.
16018d19687SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
16118d19687SRui Ueyama   if (Cmd->Name == ".") {
16218d19687SRui Ueyama     setDot(Cmd->Expression, Cmd->Location, InSec);
16318d19687SRui Ueyama     return;
16418d19687SRui Ueyama   }
16518d19687SRui Ueyama 
16618d19687SRui Ueyama   if (!Cmd->Sym)
16718d19687SRui Ueyama     return;
16818d19687SRui Ueyama 
16918d19687SRui Ueyama   ExprValue V = Cmd->Expression();
17018d19687SRui Ueyama   if (V.isAbsolute()) {
17118d19687SRui Ueyama     Cmd->Sym->Section = nullptr;
17218d19687SRui Ueyama     Cmd->Sym->Value = V.getValue();
17318d19687SRui Ueyama   } else {
17418d19687SRui Ueyama     Cmd->Sym->Section = V.Sec;
17518d19687SRui Ueyama     Cmd->Sym->Value = V.getSectionOffset();
17618d19687SRui Ueyama   }
177ceabe80eSEugene Leviant }
178ceabe80eSEugene Leviant 
179076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
180076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
181076fe157SGeorge Rimar }
182076fe157SGeorge Rimar 
183eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
184eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
185eea3114fSGeorge Rimar }
186eea3114fSGeorge Rimar 
187eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
188eefa758eSGeorge Rimar   return C->Kind == AssertKind;
189eefa758eSGeorge Rimar }
190eefa758eSGeorge Rimar 
191e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
192e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
193e38cbab5SGeorge Rimar }
194e38cbab5SGeorge Rimar 
1951e30f07cSDmitry Mikulin static std::string filename(InputFile *File) {
1961e30f07cSDmitry Mikulin   if (!File)
197e0be2901SRui Ueyama     return "";
1981e30f07cSDmitry Mikulin   if (File->ArchiveName.empty())
1991e30f07cSDmitry Mikulin     return File->getName();
2001e30f07cSDmitry Mikulin   return (File->ArchiveName + "(" + File->getName() + ")").str();
201e0be2901SRui Ueyama }
202e0be2901SRui Ueyama 
203b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) {
2041e30f07cSDmitry Mikulin   std::string Filename = filename(S->File);
2057f1c266eSRui Ueyama   for (InputSectionDescription *ID : KeptSections)
206f300ca21SDmitry Mikulin     if (ID->FilePat.match(Filename))
207cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
208f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
209eea3114fSGeorge Rimar           return true;
210eea3114fSGeorge Rimar   return false;
211eea3114fSGeorge Rimar }
212eea3114fSGeorge Rimar 
213ea93fe00SRui Ueyama // A helper function for the SORT() command.
214c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)>
215be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
216be394db3SGeorge Rimar   switch (K) {
217be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
218ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
219ea93fe00SRui Ueyama       // ">" is not a mistake. Sections with larger alignments are placed
220ea93fe00SRui Ueyama       // before sections with smaller alignments in order to reduce the
221ea93fe00SRui Ueyama       // amount of padding necessary. This is compatible with GNU.
222ea93fe00SRui Ueyama       return A->Alignment > B->Alignment;
223ea93fe00SRui Ueyama     };
224be394db3SGeorge Rimar   case SortSectionPolicy::Name:
225ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
226ea93fe00SRui Ueyama       return A->Name < B->Name;
227ea93fe00SRui Ueyama     };
228be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
229ea93fe00SRui Ueyama     return [](InputSectionBase *A, InputSectionBase *B) {
230ea93fe00SRui Ueyama       return getPriority(A->Name) < getPriority(B->Name);
231ea93fe00SRui Ueyama     };
232be394db3SGeorge Rimar   default:
233be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
234be394db3SGeorge Rimar   }
235742c3836SRui Ueyama }
2360702c4e8SGeorge Rimar 
237ea93fe00SRui Ueyama // A helper function for the SORT() command.
238b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
23906ae6836SGeorge Rimar                              ConstraintKind Kind) {
2408f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
2418f66df92SGeorge Rimar     return true;
2422c7171bfSRui Ueyama 
2432c7171bfSRui Ueyama   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
2442c7171bfSRui Ueyama     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
24506ae6836SGeorge Rimar   });
2462c7171bfSRui Ueyama 
247e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
248e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
24906ae6836SGeorge Rimar }
25006ae6836SGeorge Rimar 
2516a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End,
252ee924709SRui Ueyama                          SortSectionPolicy K) {
253ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
25407171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
255ee924709SRui Ueyama }
256ee924709SRui Ueyama 
257d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
258d6bcde38SGeorge Rimar   if (Config->SymbolOrderingFile.empty())
259d6bcde38SGeorge Rimar     return;
260696a7f9aSGeorge Rimar   static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder();
261d6bcde38SGeorge Rimar   MutableArrayRef<InputSection *> In(Begin, End - Begin);
262d6bcde38SGeorge Rimar   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
263d6bcde38SGeorge Rimar }
264d6bcde38SGeorge Rimar 
265d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
2666a1aa8d9SRafael Espindola std::vector<InputSection *>
26772e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
2686a1aa8d9SRafael Espindola   std::vector<InputSection *> Ret;
2698c6a5aafSRui Ueyama 
27072e107f3SRui Ueyama   // Collects all sections that satisfy constraints of Cmd.
27172e107f3SRui Ueyama   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
27272e107f3SRui Ueyama     size_t SizeBefore = Ret.size();
27372e107f3SRui Ueyama 
27472e107f3SRui Ueyama     for (InputSectionBase *Sec : InputSections) {
27572e107f3SRui Ueyama       if (Sec->Assigned)
2768c6a5aafSRui Ueyama         continue;
27772e107f3SRui Ueyama 
278e39709b2SRafael Espindola       if (!Sec->Live) {
279e39709b2SRafael Espindola         reportDiscarded(Sec);
280e39709b2SRafael Espindola         continue;
281e39709b2SRafael Espindola       }
282e39709b2SRafael Espindola 
283908a3d34SRafael Espindola       // For -emit-relocs we have to ignore entries like
284908a3d34SRafael Espindola       //   .rela.dyn : { *(.rela.data) }
285908a3d34SRafael Espindola       // which are common because they are in the default bfd script.
28672e107f3SRui Ueyama       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
287908a3d34SRafael Espindola         continue;
2888c6a5aafSRui Ueyama 
2891e30f07cSDmitry Mikulin       std::string Filename = filename(Sec->File);
29072e107f3SRui Ueyama       if (!Cmd->FilePat.match(Filename) ||
29172e107f3SRui Ueyama           Pat.ExcludedFilePat.match(Filename) ||
29272e107f3SRui Ueyama           !Pat.SectionPat.match(Sec->Name))
293e0be2901SRui Ueyama         continue;
29472e107f3SRui Ueyama 
2956a1aa8d9SRafael Espindola       Ret.push_back(cast<InputSection>(Sec));
29672e107f3SRui Ueyama       Sec->Assigned = true;
297f94efdddSRui Ueyama     }
298d3190795SRafael Espindola 
299ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
300ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
301ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
302ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
303ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
304ee924709SRui Ueyama     //
305ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
306ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
307ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
308ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
309ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
310d6bcde38SGeorge Rimar     // 5. If no SORT commands are given and --sort-section is not specified,
311d6bcde38SGeorge Rimar     //    apply sorting provided by --symbol-ordering-file if any exist.
3126a1aa8d9SRafael Espindola     InputSection **Begin = Ret.data() + SizeBefore;
3136a1aa8d9SRafael Espindola     InputSection **End = Ret.data() + Ret.size();
314d6bcde38SGeorge Rimar     if (Pat.SortOuter == SortSectionPolicy::Default &&
315d6bcde38SGeorge Rimar         Config->SortSection == SortSectionPolicy::Default) {
316d6bcde38SGeorge Rimar       sortBySymbolOrder(Begin, End);
317d6bcde38SGeorge Rimar       continue;
318d6bcde38SGeorge Rimar     }
31907171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
32007171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
32107171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
322ee924709SRui Ueyama       else
32307171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
32407171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
32507171f21SGeorge Rimar     }
326ee924709SRui Ueyama   }
32772e107f3SRui Ueyama   return Ret;
328be94e1b6SRafael Espindola }
329be94e1b6SRafael Espindola 
330b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
331b4c9b81aSRafael Espindola   for (InputSectionBase *S : V) {
332be94e1b6SRafael Espindola     S->Live = false;
3331e30f07cSDmitry Mikulin     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
3341e30f07cSDmitry Mikulin         S == InX::DynStrTab)
3352af64b0bSRafael Espindola       error("discarding " + S->Name + " section is not allowed");
336647c1685SGeorge Rimar     discard(S->DependentSections);
337be94e1b6SRafael Espindola   }
338be94e1b6SRafael Espindola }
339be94e1b6SRafael Espindola 
340b4c9b81aSRafael Espindola std::vector<InputSectionBase *>
3418c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) {
342b4c9b81aSRafael Espindola   std::vector<InputSectionBase *> Ret;
343e7f912cdSRui Ueyama 
344*6b394caaSRui Ueyama   for (BaseCommand *Base : OutCmd.SectionCommands) {
3458f99f73cSRui Ueyama     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
3467c3ff2ebSRafael Espindola     if (!Cmd)
3470b9ce6a4SRui Ueyama       continue;
34872e107f3SRui Ueyama 
34972e107f3SRui Ueyama     Cmd->Sections = computeInputSections(Cmd);
350e4c8b9b7SRafael Espindola     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
3510b9ce6a4SRui Ueyama   }
352e71a3f8aSRafael Espindola 
3530b9ce6a4SRui Ueyama   return Ret;
3540b9ce6a4SRui Ueyama }
3550b9ce6a4SRui Ueyama 
356b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) {
3575616adf6SRafael Espindola   // A symbol can be assigned before any section is mentioned in the linker
3585616adf6SRafael Espindola   // script. In an DSO, the symbol values are addresses, so the only important
3595616adf6SRafael Espindola   // section values are:
3605616adf6SRafael Espindola   // * SHN_UNDEF
3615616adf6SRafael Espindola   // * SHN_ABS
3625616adf6SRafael Espindola   // * Any value meaning a regular section.
3635616adf6SRafael Espindola   // To handle that, create a dummy aether section that fills the void before
3645616adf6SRafael Espindola   // the linker scripts switches to another section. It has an index of one
3655616adf6SRafael Espindola   // which will map to whatever the first actual section is.
3665616adf6SRafael Espindola   Aether = make<OutputSection>("", 0, SHF_ALLOC);
3675616adf6SRafael Espindola   Aether->SectionIndex = 1;
368ac27de9dSRui Ueyama   auto State = make_unique<AddressState>();
36918d19687SRui Ueyama 
370c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
371c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
372c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
373c1ace40bSPeter Smith   // script parser.
374906e9a18SPeter Smith   CurAddressState = State.get();
375906e9a18SPeter Smith   CurAddressState->OutSec = Aether;
3765616adf6SRafael Espindola 
377*6b394caaSRui Ueyama   for (size_t I = 0; I < SectionCommands.size(); ++I) {
3780b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
379*6b394caaSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(SectionCommands[I])) {
3804cd7352cSRafael Espindola       addSymbol(Cmd);
3812ab5f73dSRui Ueyama       continue;
3822ab5f73dSRui Ueyama     }
3830b1b695aSRui Ueyama 
384*6b394caaSRui Ueyama     if (auto *Sec = dyn_cast<OutputSection>(SectionCommands[I])) {
3858c022ca7SRafael Espindola       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
3867bd37870SRafael Espindola 
3870b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3880b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
3898c022ca7SRafael Espindola       if (Sec->Name == "/DISCARD/") {
3907bd37870SRafael Espindola         discard(V);
39148c3f1ceSRui Ueyama         continue;
39248c3f1ceSRui Ueyama       }
3930b9ce6a4SRui Ueyama 
3940b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3950b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3960b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
39707d7c42cSGeorge Rimar       // as if it wasn't present from the beginning.
3980b1b695aSRui Ueyama       //
399*6b394caaSRui Ueyama       // Because we'll iterate over SectionCommands many more times, the easiest
40007d7c42cSGeorge Rimar       // way to "make it as if it wasn't present" is to just remove it.
4018c022ca7SRafael Espindola       if (!matchConstraints(V, Sec->Constraint)) {
402b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
403f94efdddSRui Ueyama           S->Assigned = false;
404*6b394caaSRui Ueyama         SectionCommands.erase(SectionCommands.begin() + I);
40507d7c42cSGeorge Rimar         --I;
4067c3ff2ebSRafael Espindola         continue;
4077c3ff2ebSRafael Espindola       }
4087c3ff2ebSRafael Espindola 
4090b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
4100b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
411*6b394caaSRui Ueyama       for (BaseCommand *Base : Sec->SectionCommands)
4128f99f73cSRui Ueyama         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
4134cd7352cSRafael Espindola           addSymbol(OutCmd);
4147c3ff2ebSRafael Espindola 
4150b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
4160b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
4170b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
4188c022ca7SRafael Espindola       if (Sec->SubalignExpr) {
4198c022ca7SRafael Espindola         uint32_t Subalign = Sec->SubalignExpr().getValue();
420b4c9b81aSRafael Espindola         for (InputSectionBase *S : V)
4210b1b695aSRui Ueyama           S->Alignment = Subalign;
42220d03194SEugene Leviant       }
4230b1b695aSRui Ueyama 
4240b1b695aSRui Ueyama       // Add input sections to an output section.
425d86a4e50SGeorge Rimar       for (InputSectionBase *S : V)
4260e2bfb1eSRui Ueyama         Sec->addSection(cast<InputSection>(S));
427c54d5b16SRui Ueyama 
428660c9ab9SRafael Espindola       assert(Sec->SectionIndex == INT_MAX);
429660c9ab9SRafael Espindola       Sec->SectionIndex = I;
4308c022ca7SRafael Espindola       if (Sec->Noload)
431fbb0463fSGeorge Rimar         Sec->Type = SHT_NOBITS;
43248c3f1ceSRui Ueyama     }
4334aa2ef5bSRafael Espindola   }
434c1ace40bSPeter Smith   CurAddressState = nullptr;
435db24d9c3SGeorge Rimar }
436e63d81bdSEugene Leviant 
43702ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() {
438cbfe9e94SPeter Smith   // Define start address
439761f0b66SRui Ueyama   uint64_t StartAddr = UINT64_MAX;
440cbfe9e94SPeter Smith 
441c60b4510SPeter Smith   // The Sections with -T<section> have been sorted in order of ascending
442c60b4510SPeter Smith   // address. We must lower StartAddr if the lowest -T<section address> as
443c60b4510SPeter Smith   // calls to setDot() must be monotonically increasing.
444c60b4510SPeter Smith   for (auto &KV : Config->SectionStartMap)
445c60b4510SPeter Smith     StartAddr = std::min(StartAddr, KV.second);
446c60b4510SPeter Smith 
447f5db0b36SRui Ueyama   auto Expr = [=] {
448b5ca92efSJames Henderson     return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize());
449f5db0b36SRui Ueyama   };
450*6b394caaSRui Ueyama   SectionCommands.insert(SectionCommands.begin(),
451*6b394caaSRui Ueyama                          make<SymbolAssignment>(".", Expr, ""));
452cbfe9e94SPeter Smith }
453cbfe9e94SPeter Smith 
454d2f225fdSRui Ueyama static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
455d2f225fdSRui Ueyama                                  StringRef Name) {
456d2f225fdSRui Ueyama   for (BaseCommand *Base : Vec)
457d2f225fdSRui Ueyama     if (auto *Sec = dyn_cast<OutputSection>(Base))
458d2f225fdSRui Ueyama       if (Sec->Name == Name)
459d2f225fdSRui Ueyama         return Sec;
460d2f225fdSRui Ueyama   return nullptr;
461d2f225fdSRui Ueyama }
462d2f225fdSRui Ueyama 
4630b1b695aSRui Ueyama // Add sections that didn't match any sections command.
464b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
465*6b394caaSRui Ueyama   unsigned End = SectionCommands.size();
466d2f225fdSRui Ueyama 
4674f013bb3SRafael Espindola   for (InputSectionBase *S : InputSections) {
468db5e56f7SRafael Espindola     if (!S->Live || S->Parent)
4694f013bb3SRafael Espindola       continue;
470d2f225fdSRui Ueyama 
4714f013bb3SRafael Espindola     StringRef Name = getOutputSectionName(S->Name);
472347c70d7SGeorge Rimar     log(toString(S) + " is being placed in '" + Name + "'");
473d2f225fdSRui Ueyama 
474ac27de9dSRui Ueyama     if (OutputSection *Sec =
475*6b394caaSRui Ueyama             findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) {
4760e2bfb1eSRui Ueyama       Sec->addSection(cast<InputSection>(S));
477c54d5b16SRui Ueyama       continue;
478660c9ab9SRafael Espindola     }
479c54d5b16SRui Ueyama 
480c54d5b16SRui Ueyama     if (OutputSection *OS = Factory.addInputSec(S, Name))
481*6b394caaSRui Ueyama       SectionCommands.push_back(OS);
482c54d5b16SRui Ueyama     assert(S->getOutputSection()->SectionIndex == INT_MAX);
483d7faa916SRafael Espindola   }
4844f013bb3SRafael Espindola }
485e63d81bdSEugene Leviant 
4867c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
487906e9a18SPeter Smith   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
488906e9a18SPeter Smith                 CurAddressState->OutSec->Type == SHT_NOBITS;
489906e9a18SPeter Smith   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
4907c4eafa3SRafael Espindola   Start = alignTo(Start, Align);
4917c4eafa3SRafael Espindola   uint64_t End = Start + Size;
4927c4eafa3SRafael Espindola 
4937c4eafa3SRafael Espindola   if (IsTbss)
494906e9a18SPeter Smith     CurAddressState->ThreadBssOffset = End - Dot;
4957c4eafa3SRafael Espindola   else
4967c4eafa3SRafael Espindola     Dot = End;
4977c4eafa3SRafael Espindola   return End;
498a940e539SRafael Espindola }
499a940e539SRafael Espindola 
500b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) {
501f694d33fSGeorge Rimar   uint64_t Before = advance(0, 1);
5027c4eafa3SRafael Espindola   uint64_t Pos = advance(S->getSize(), S->Alignment);
503906e9a18SPeter Smith   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
504d3190795SRafael Espindola 
505d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
506d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
507d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
508906e9a18SPeter Smith   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
509d3190795SRafael Espindola 
510b889744eSMeador Inge   // If there is a memory region associated with this input section, then
511b889744eSMeador Inge   // place the section in that region and update the region index.
512906e9a18SPeter Smith   if (CurAddressState->MemRegion) {
513906e9a18SPeter Smith     uint64_t &CurOffset =
514906e9a18SPeter Smith         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
515f694d33fSGeorge Rimar     CurOffset += Pos - Before;
516906e9a18SPeter Smith     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
517906e9a18SPeter Smith     if (CurSize > CurAddressState->MemRegion->Length) {
518906e9a18SPeter Smith       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
519906e9a18SPeter Smith       error("section '" + CurAddressState->OutSec->Name +
520906e9a18SPeter Smith             "' will not fit in region '" + CurAddressState->MemRegion->Name +
521906e9a18SPeter Smith             "': overflowed by " + Twine(OverflowAmt) + " bytes");
522b889744eSMeador Inge     }
523b889744eSMeador Inge   }
5242de509c3SRui Ueyama }
525ceabe80eSEugene Leviant 
526b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) {
527906e9a18SPeter Smith   if (CurAddressState->OutSec == Sec)
528d3190795SRafael Espindola     return;
529d3190795SRafael Espindola 
530906e9a18SPeter Smith   CurAddressState->OutSec = Sec;
531906e9a18SPeter Smith   CurAddressState->OutSec->Addr =
532906e9a18SPeter Smith       advance(0, CurAddressState->OutSec->Alignment);
533b71d6f7aSEugene Leviant 
534b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
535b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
536b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
537b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
538906e9a18SPeter Smith   if (CurAddressState->LMAOffset)
539906e9a18SPeter Smith     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
540d3190795SRafael Espindola }
541d3190795SRafael Espindola 
542b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) {
5432e081a4fSRui Ueyama   // This handles the assignments to symbol or to the dot.
5442e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
5452e081a4fSRui Ueyama     assignSymbol(Cmd, true);
546d3190795SRafael Espindola     return;
54797403d15SEugene Leviant   }
548e38cbab5SGeorge Rimar 
549e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
5502e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
551906e9a18SPeter Smith     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
5522e081a4fSRui Ueyama     Dot += Cmd->Size;
553906e9a18SPeter Smith     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
554e38cbab5SGeorge Rimar     return;
555e38cbab5SGeorge Rimar   }
556e38cbab5SGeorge Rimar 
5572e081a4fSRui Ueyama   // Handle ASSERT().
5582e081a4fSRui Ueyama   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
5592e081a4fSRui Ueyama     Cmd->Expression();
560b2d99d6aSMeador Inge     return;
561b2d99d6aSMeador Inge   }
562b2d99d6aSMeador Inge 
5632e081a4fSRui Ueyama   // Handle a single input section description command.
5642e081a4fSRui Ueyama   // It calculates and assigns the offsets for each section and also
565e38cbab5SGeorge Rimar   // updates the output section size.
5662e081a4fSRui Ueyama   auto &Cmd = cast<InputSectionDescription>(Base);
567a85e8ddaSRafael Espindola   for (InputSection *Sec : Cmd.Sections) {
5683fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
5693fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5703fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5713fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5722e081a4fSRui Ueyama     if (auto *S = dyn_cast<SyntheticSection>(Sec))
5732e081a4fSRui Ueyama       if (S->empty())
5743fb5a6dcSGeorge Rimar         continue;
5753fb5a6dcSGeorge Rimar 
5762e081a4fSRui Ueyama     if (!Sec->Live)
57778ef645fSGeorge Rimar       continue;
578906e9a18SPeter Smith     assert(CurAddressState->OutSec == Sec->getParent());
579a85e8ddaSRafael Espindola     output(Sec);
580ceabe80eSEugene Leviant   }
581ceabe80eSEugene Leviant }
582ceabe80eSEugene Leviant 
583b889744eSMeador Inge // This function searches for a memory region to place the given output
584b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is
585b889744eSMeador Inge // returned. Otherwise, a nullptr is returned.
5868c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
587b889744eSMeador Inge   // If a memory region name was specified in the output section command,
588b889744eSMeador Inge   // then try to find that region first.
5898c022ca7SRafael Espindola   if (!Sec->MemoryRegionName.empty()) {
590ac27de9dSRui Ueyama     auto It = MemoryRegions.find(Sec->MemoryRegionName);
591ac27de9dSRui Ueyama     if (It != MemoryRegions.end())
5925f37541cSGeorge Rimar       return It->second;
5938c022ca7SRafael Espindola     error("memory region '" + Sec->MemoryRegionName + "' not declared");
594b889744eSMeador Inge     return nullptr;
595b889744eSMeador Inge   }
596b889744eSMeador Inge 
597d7c5400fSRui Ueyama   // If at least one memory region is defined, all sections must
598d7c5400fSRui Ueyama   // belong to some memory region. Otherwise, we don't need to do
599d7c5400fSRui Ueyama   // anything for memory regions.
600ac27de9dSRui Ueyama   if (MemoryRegions.empty())
601b889744eSMeador Inge     return nullptr;
602b889744eSMeador Inge 
603b889744eSMeador Inge   // See if a region can be found by matching section flags.
604ac27de9dSRui Ueyama   for (auto &Pair : MemoryRegions) {
6055f37541cSGeorge Rimar     MemoryRegion *M = Pair.second;
6065f37541cSGeorge Rimar     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
6075f37541cSGeorge Rimar       return M;
608b889744eSMeador Inge   }
609b889744eSMeador Inge 
610b889744eSMeador Inge   // Otherwise, no suitable region was found.
611b889744eSMeador Inge   if (Sec->Flags & SHF_ALLOC)
612b889744eSMeador Inge     error("no memory region specified for section '" + Sec->Name + "'");
613b889744eSMeador Inge   return nullptr;
614b889744eSMeador Inge }
615b889744eSMeador Inge 
6160b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
6170b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
6188c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) {
619dece2808SRafael Espindola   if (!(Sec->Flags & SHF_ALLOC))
620dece2808SRafael Espindola     Dot = 0;
6218c022ca7SRafael Espindola   else if (Sec->AddrExpr)
6228c022ca7SRafael Espindola     setDot(Sec->AddrExpr, Sec->Location, false);
623679828ffSRafael Espindola 
624c2dffe3aSGeorge Rimar   CurAddressState->MemRegion = Sec->MemRegion;
625c2dffe3aSGeorge Rimar   if (CurAddressState->MemRegion)
626c2dffe3aSGeorge Rimar     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
627c2dffe3aSGeorge Rimar 
6288c022ca7SRafael Espindola   if (Sec->LMAExpr) {
6290c1c8085SGeorge Rimar     uint64_t D = Dot;
6308c022ca7SRafael Espindola     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
6315784e96fSEugene Leviant   }
6325784e96fSEugene Leviant 
633b889744eSMeador Inge   switchTo(Sec);
6340b1b695aSRui Ueyama 
635d86a4e50SGeorge Rimar   // We do not support custom layout for compressed debug sectons.
636d86a4e50SGeorge Rimar   // At this point we already know their size and have compressed content.
637906e9a18SPeter Smith   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
638d86a4e50SGeorge Rimar     return;
639d86a4e50SGeorge Rimar 
640*6b394caaSRui Ueyama   for (BaseCommand *C : Sec->SectionCommands)
641de8d9897SRafael Espindola     process(*C);
642d3190795SRafael Espindola }
643d3190795SRafael Espindola 
644b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() {
6456d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
6466d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
6476d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
6486d38e4dbSRafael Espindola   // clutter the output.
6496d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
6506d38e4dbSRafael Espindola   // more aggressive at removing them.
651*6b394caaSRui Ueyama   llvm::erase_if(SectionCommands, [&](BaseCommand *Base) {
6528c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base))
6538c022ca7SRafael Espindola       return !Sec->Live;
6540b1b695aSRui Ueyama     return false;
6556d38e4dbSRafael Espindola   });
65607fe6129SRafael Espindola }
65707fe6129SRafael Espindola 
6588c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) {
659*6b394caaSRui Ueyama   for (BaseCommand *Base : Cmd.SectionCommands)
6608f99f73cSRui Ueyama     if (!isa<InputSectionDescription>(*Base))
6616a53737cSRafael Espindola       return false;
6626a53737cSRafael Espindola   return true;
6636a53737cSRafael Espindola }
6646d38e4dbSRafael Espindola 
665b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() {
6669546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
6679546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
6689546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
6699546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
6700c1c8085SGeorge Rimar   uint64_t Flags = SHF_ALLOC;
671660c9ab9SRafael Espindola 
672*6b394caaSRui Ueyama   for (BaseCommand *Cmd : SectionCommands) {
6738962db91SGeorge Rimar     auto *Sec = dyn_cast<OutputSection>(Cmd);
6748c022ca7SRafael Espindola     if (!Sec)
6759546fffbSRafael Espindola       continue;
6768c022ca7SRafael Espindola     if (Sec->Live) {
6772b074553SRafael Espindola       Flags = Sec->Flags;
6789546fffbSRafael Espindola       continue;
6799546fffbSRafael Espindola     }
6809546fffbSRafael Espindola 
6818c022ca7SRafael Espindola     if (isAllSectionDescription(*Sec))
6826a53737cSRafael Espindola       continue;
6836a53737cSRafael Espindola 
6848c022ca7SRafael Espindola     Sec->Live = true;
6858c022ca7SRafael Espindola     Sec->Flags = Flags;
6869546fffbSRafael Espindola   }
687f7a17448SRafael Espindola }
688f7a17448SRafael Espindola 
689b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() {
690feed7506SRafael Espindola   // Try and find an appropriate memory region to assign offsets in.
691*6b394caaSRui Ueyama   for (BaseCommand *Base : SectionCommands) {
6928c022ca7SRafael Espindola     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
693ba45584cSGeorge Rimar       if (!Sec->Live)
694ba45584cSGeorge Rimar         continue;
6958c022ca7SRafael Espindola       Sec->MemRegion = findMemoryRegion(Sec);
696d1960dc0SRafael Espindola       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
6978c022ca7SRafael Espindola       if (Sec->AlignExpr)
6988befefb2SRui Ueyama         Sec->Alignment =
6998befefb2SRui Ueyama             std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
700d1960dc0SRafael Espindola     }
701d1960dc0SRafael Espindola   }
702feed7506SRafael Espindola 
703f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
704f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
705f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
706f7a17448SRafael Espindola   // Below is an example of such linker script:
707f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
708f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
709f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
710f7a17448SRafael Espindola   auto FirstPtLoad =
711ac27de9dSRui Ueyama       std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(),
712f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
713ac27de9dSRui Ueyama   if (FirstPtLoad != PhdrsCommands.end())
714f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
715f7a17448SRafael Espindola 
716f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
717f7a17448SRafael Espindola   // explicitly specify them.
718*6b394caaSRui Ueyama   for (BaseCommand *Base : SectionCommands) {
7198c022ca7SRafael Espindola     auto *Sec = dyn_cast<OutputSection>(Base);
7208c022ca7SRafael Espindola     if (!Sec)
721f7a17448SRafael Espindola       continue;
7228f99f73cSRui Ueyama 
7238c022ca7SRafael Espindola     if (Sec->Phdrs.empty()) {
724a020d348SAndrew Ng       // To match the bfd linker script behaviour, only propagate program
725a020d348SAndrew Ng       // headers to sections that are allocated.
7268c022ca7SRafael Espindola       if (Sec->Flags & SHF_ALLOC)
7278c022ca7SRafael Espindola         Sec->Phdrs = DefPhdrs;
728a020d348SAndrew Ng     } else {
7298c022ca7SRafael Espindola       DefPhdrs = Sec->Phdrs;
730f7a17448SRafael Espindola     }
731a020d348SAndrew Ng   }
7329546fffbSRafael Espindola }
7339546fffbSRafael Espindola 
734582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) {
735582ede89SGeorge Rimar   for (OutputSection *Sec : OutputSections)
736582ede89SGeorge Rimar     if (Sec->PtLoad == Load)
737582ede89SGeorge Rimar       return Sec;
738582ede89SGeorge Rimar   return nullptr;
739582ede89SGeorge Rimar }
740582ede89SGeorge Rimar 
741b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections,
742b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier.
743b93c5b9fSPetr Hosek //
744b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first
745b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers
746b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not
747b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common
748b93c5b9fSPetr Hosek // in embedded systems.
749b93c5b9fSPetr Hosek //
750b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the
751b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
752aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
7535aedebffSPeter Smith   uint64_t Min = std::numeric_limits<uint64_t>::max();
7548c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections)
7555aedebffSPeter Smith     if (Sec->Flags & SHF_ALLOC)
7565aedebffSPeter Smith       Min = std::min<uint64_t>(Min, Sec->Addr);
7575aedebffSPeter Smith 
758aa354187SGeorge Rimar   auto It = llvm::find_if(
759aa354187SGeorge Rimar       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
760aa354187SGeorge Rimar   if (It == Phdrs.end())
761d971e703SGeorge Rimar     return;
762aa354187SGeorge Rimar   PhdrEntry *FirstPTLoad = *It;
76302ed7575SRafael Espindola 
76402ed7575SRafael Espindola   uint64_t HeaderSize = getHeaderSize();
765b93c5b9fSPetr Hosek   // When linker script with SECTIONS is being used, don't output headers
766b93c5b9fSPetr Hosek   // unless there's a space for them.
767a323e2a7SRui Ueyama   uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0;
768b93c5b9fSPetr Hosek   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
7691f0fe88aSRafael Espindola     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
77002ed7575SRafael Espindola     Out::ElfHeader->Addr = Min;
77102ed7575SRafael Espindola     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
772d971e703SGeorge Rimar     return;
77302ed7575SRafael Espindola   }
77402ed7575SRafael Espindola 
775582ede89SGeorge Rimar   Out::ElfHeader->PtLoad = nullptr;
776582ede89SGeorge Rimar   Out::ProgramHeaders->PtLoad = nullptr;
7776823c5f0SGeorge Rimar   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
77802ed7575SRafael Espindola 
77960608a8aSGeorge Rimar   llvm::erase_if(Phdrs,
78060608a8aSGeorge Rimar                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
78102ed7575SRafael Espindola }
78202ed7575SRafael Espindola 
783ac27de9dSRui Ueyama LinkerScript::AddressState::AddressState() {
784ac27de9dSRui Ueyama   for (auto &MRI : Script->MemoryRegions) {
7855f37541cSGeorge Rimar     const MemoryRegion *MR = MRI.second;
786906e9a18SPeter Smith     MemRegionOffset[MR] = MR->Origin;
787906e9a18SPeter Smith   }
788906e9a18SPeter Smith }
789906e9a18SPeter Smith 
7907c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands.
791b5ca92efSJames Henderson void LinkerScript::assignAddresses() {
792b5ca92efSJames Henderson   // By default linker scripts use an initial value of 0 for '.', but prefer
793b5ca92efSJames Henderson   // -image-base if set.
794b5ca92efSJames Henderson   Dot = Config->ImageBase ? *Config->ImageBase : 0;
795ac27de9dSRui Ueyama   auto State = make_unique<AddressState>();
79618d19687SRui Ueyama 
797c1ace40bSPeter Smith   // CurAddressState captures the local AddressState and makes it accessible
798c1ace40bSPeter Smith   // deliberately. This is needed as there are some cases where we cannot just
799c1ace40bSPeter Smith   // thread the current state through to a lambda function created by the
800c1ace40bSPeter Smith   // script parser.
801906e9a18SPeter Smith   CurAddressState = State.get();
80272dc195dSRafael Espindola   ErrorOnMissingSection = true;
80306f4743aSRafael Espindola   switchTo(Aether);
80406f4743aSRafael Espindola 
805*6b394caaSRui Ueyama   for (BaseCommand *Base : SectionCommands) {
8068f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
807d379f735SRui Ueyama       assignSymbol(Cmd, false);
80805ef4cffSRui Ueyama       continue;
809652852c5SGeorge Rimar     }
810652852c5SGeorge Rimar 
8118f99f73cSRui Ueyama     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
8124595df94SRafael Espindola       Cmd->Expression();
813eefa758eSGeorge Rimar       continue;
814eefa758eSGeorge Rimar     }
815eefa758eSGeorge Rimar 
8168c022ca7SRafael Espindola     assignOffsets(cast<OutputSection>(Base));
817a14b13d8SGeorge Rimar   }
818c1ace40bSPeter Smith   CurAddressState = nullptr;
819fb8978fcSDima Stepanov }
820652852c5SGeorge Rimar 
821464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
822aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
823aa354187SGeorge Rimar   std::vector<PhdrEntry *> Ret;
824bbe38602SEugene Leviant 
825464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
826464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
827ac27de9dSRui Ueyama   for (const PhdrsCommand &Cmd : PhdrsCommands) {
8280ae2c24cSRui Ueyama     PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R);
829bbe38602SEugene Leviant 
830bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
831aa354187SGeorge Rimar       Phdr->add(Out::ElfHeader);
832bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
833aa354187SGeorge Rimar       Phdr->add(Out::ProgramHeaders);
83456b21c86SEugene Leviant 
83556b21c86SEugene Leviant     if (Cmd.LMAExpr) {
836aa354187SGeorge Rimar       Phdr->p_paddr = Cmd.LMAExpr().getValue();
837aa354187SGeorge Rimar       Phdr->HasLMA = true;
83856b21c86SEugene Leviant     }
839aa354187SGeorge Rimar     Ret.push_back(Phdr);
840bbe38602SEugene Leviant   }
841bbe38602SEugene Leviant 
842464daadcSRui Ueyama   // Add output sections to program headers.
8438c022ca7SRafael Espindola   for (OutputSection *Sec : OutputSections) {
844bbe38602SEugene Leviant     // Assign headers specified by linker script
8458c022ca7SRafael Espindola     for (size_t Id : getPhdrIndices(Sec)) {
846aa354187SGeorge Rimar       Ret[Id]->add(Sec);
847ac27de9dSRui Ueyama       if (!PhdrsCommands[Id].Flags.hasValue())
848aa354187SGeorge Rimar         Ret[Id]->p_flags |= Sec->getPhdrFlags();
849bbe38602SEugene Leviant     }
850bbe38602SEugene Leviant   }
851edebbdf1SRui Ueyama   return Ret;
852bbe38602SEugene Leviant }
853bbe38602SEugene Leviant 
854e03ba023SRui Ueyama // Returns true if we should emit an .interp section.
855e03ba023SRui Ueyama //
856e03ba023SRui Ueyama // We usually do. But if PHDRS commands are given, and
857e03ba023SRui Ueyama // no PT_INTERP is there, there's no place to emit an
858e03ba023SRui Ueyama // .interp, so we don't do that in that case.
859e03ba023SRui Ueyama bool LinkerScript::needsInterpSection() {
860ac27de9dSRui Ueyama   if (PhdrsCommands.empty())
861e03ba023SRui Ueyama     return true;
862ac27de9dSRui Ueyama   for (PhdrsCommand &Cmd : PhdrsCommands)
863e31d9886SRui Ueyama     if (Cmd.Type == PT_INTERP)
864e31d9886SRui Ueyama       return true;
865e03ba023SRui Ueyama   return false;
866f9bc3bd2SEugene Leviant }
867f9bc3bd2SEugene Leviant 
868b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
8697e5b0a59SGeorge Rimar   if (S == ".") {
8707e5b0a59SGeorge Rimar     if (CurAddressState)
8714fbe3518SRui Ueyama       return {CurAddressState->OutSec, false,
8724fbe3518SRui Ueyama               Dot - CurAddressState->OutSec->Addr, Loc};
8737e5b0a59SGeorge Rimar     error(Loc + ": unable to get location counter value");
8747e5b0a59SGeorge Rimar     return 0;
8757e5b0a59SGeorge Rimar   }
876244ef981SRafael Espindola   if (SymbolBody *B = Symtab->find(S)) {
87772dc195dSRafael Espindola     if (auto *D = dyn_cast<DefinedRegular>(B))
8784fbe3518SRui Ueyama       return {D->Section, false, D->Value, Loc};
87930f16b23SPetr Hosek     if (auto *C = dyn_cast<DefinedCommon>(B))
8804fbe3518SRui Ueyama       return {C->Section, false, 0, Loc};
88172dc195dSRafael Espindola   }
882f6aeed36SEugene Leviant   error(Loc + ": symbol not found: " + S);
883884e786dSGeorge Rimar   return 0;
884884e786dSGeorge Rimar }
885884e786dSGeorge Rimar 
886656be311SRui Ueyama // Returns the index of the segment named Name.
887656be311SRui Ueyama static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec,
888656be311SRui Ueyama                                      StringRef Name) {
889656be311SRui Ueyama   for (size_t I = 0; I < Vec.size(); ++I)
890656be311SRui Ueyama     if (Vec[I].Name == Name)
891656be311SRui Ueyama       return I;
892656be311SRui Ueyama   return None;
893656be311SRui Ueyama }
894656be311SRui Ueyama 
8952c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a
8962c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block.
8978c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
89829c5a2a9SRui Ueyama   std::vector<size_t> Ret;
899656be311SRui Ueyama 
900656be311SRui Ueyama   for (StringRef S : Cmd->Phdrs) {
901ac27de9dSRui Ueyama     if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S))
90287223574SRui Ueyama       Ret.push_back(*Idx);
903656be311SRui Ueyama     else if (S != "NONE")
904656be311SRui Ueyama       error(Cmd->Location + ": section header '" + S +
905656be311SRui Ueyama             "' is not listed in PHDRS");
906bbe38602SEugene Leviant   }
907656be311SRui Ueyama   return Ret;
90829c5a2a9SRui Ueyama }
909