blob: 3b045f08555f13ae592a8230708c1b2eac909a45 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama717677a2016-02-11 21:17:59 +000014#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000015#include "Config.h"
16#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000017#include "InputSection.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000018#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000019#include "OutputSections.h"
Rui Ueyama794366a2017-02-14 04:47:05 +000020#include "ScriptLexer.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000021#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000022#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000023#include "Symbols.h"
George Rimar3fb5a6d2016-11-29 16:05:27 +000024#include "SyntheticSections.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000025#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000026#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000030#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000033#include "llvm/Support/Endian.h"
34#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000035#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/MathExtras.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000037#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <iterator>
43#include <limits>
44#include <memory>
45#include <string>
46#include <tuple>
47#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000048
49using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000050using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000051using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000052using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000053using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000054using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000055
George Rimar884e7862016-09-08 08:19:13 +000056LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000057ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000058
Meador Inge8f1f3c42017-01-09 18:36:57 +000059template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000060 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000061 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +000062 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
63 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
64 /*File*/ nullptr);
65 Sym->Binding = STB_GLOBAL;
Meador Inge8f1f3c42017-01-09 18:36:57 +000066 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, /*IsLocal=*/false,
67 Visibility, STT_NOTYPE, 0, 0, nullptr,
68 nullptr);
69 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000070}
71
Meador Inge8f1f3c42017-01-09 18:36:57 +000072template <class ELFT> static SymbolBody *addSynthetic(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000073 Symbol *Sym;
Meador Inge8f1f3c42017-01-09 18:36:57 +000074 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rafael Espindola24e6f362017-02-24 15:07:30 +000075 const OutputSection *Sec =
Eugene Leviantafaa9342016-11-16 09:49:39 +000076 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
Petr Hosek5e51f7d2017-02-21 22:32:51 +000077 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
78 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
79 /*File*/ nullptr);
80 Sym->Binding = STB_GLOBAL;
Meador Inge8f1f3c42017-01-09 18:36:57 +000081 replaceBody<DefinedSynthetic>(Sym, Cmd->Name, 0, Sec);
82 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000083}
84
Rui Ueyama22375f22016-11-25 18:51:54 +000085static bool isUnderSysroot(StringRef Path) {
86 if (Config->Sysroot == "")
87 return false;
88 for (; !Path.empty(); Path = sys::path::parent_path(Path))
89 if (sys::fs::equivalent(Config->Sysroot, Path))
90 return true;
91 return false;
92}
93
George Rimar2ee2d2d2017-02-21 14:50:38 +000094template <class ELFT>
95void LinkerScript<ELFT>::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola679828f2017-02-17 16:26:13 +000096 uintX_t Val = E(Dot);
97 if (Val < Dot) {
98 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +000099 error(Loc + ": unable to move location counter backward for: " +
100 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000101 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000102 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000103 }
104 Dot = Val;
105 // Update to location counter means update to section size.
106 if (InSec)
107 CurOutSec->Size = Dot - CurOutSec->Addr;
108}
109
George Rimarb2b70972017-02-07 10:23:28 +0000110// Sets value of a symbol. Two kinds of symbols are processed: synthetic
111// symbols, whose value is an offset from beginning of section and regular
112// symbols whose value is absolute.
113template <class ELFT>
Rafael Espindola4cd73522017-02-17 16:01:51 +0000114void LinkerScript<ELFT>::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
115 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000116 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000117 return;
118 }
119
George Rimarb2b70972017-02-07 10:23:28 +0000120 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000121 return;
122
George Rimarb2b70972017-02-07 10:23:28 +0000123 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
124 Body->Section = Cmd->Expression.Section();
Rafael Espindolaea590d92017-02-08 15:19:03 +0000125 if (Body->Section) {
126 uint64_t VA = 0;
127 if (Body->Section->Flags & SHF_ALLOC)
128 VA = Body->Section->Addr;
129 Body->Value = Cmd->Expression(Dot) - VA;
130 }
George Rimarb2b70972017-02-07 10:23:28 +0000131 return;
Meador Inge8f1f3c42017-01-09 18:36:57 +0000132 }
George Rimarb2b70972017-02-07 10:23:28 +0000133
134 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000135}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000136
Rafael Espindola4cd73522017-02-17 16:01:51 +0000137template <class ELFT>
138void LinkerScript<ELFT>::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000139 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000140 return;
141
142 // If a symbol was in PROVIDE(), we need to define it only when
143 // it is a referenced undefined symbol.
Rui Ueyama16024212016-08-11 23:22:52 +0000144 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000145 if (Cmd->Provide && (!B || B->isDefined()))
146 return;
147
148 // Otherwise, create a new symbol if one does not exist or an
149 // undefined one does exist.
150 if (Cmd->Expression.IsAbsolute())
151 Cmd->Sym = addRegular<ELFT>(Cmd);
152 else
153 Cmd->Sym = addSynthetic<ELFT>(Cmd);
George Rimarb2b70972017-02-07 10:23:28 +0000154
155 // If there are sections, then let the value be assigned later in
156 // `assignAddresses`.
157 if (!ScriptConfig->HasSections)
Rafael Espindola4cd73522017-02-17 16:01:51 +0000158 assignSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000159}
160
George Rimar076fe152016-07-21 06:43:01 +0000161bool SymbolAssignment::classof(const BaseCommand *C) {
162 return C->Kind == AssignmentKind;
163}
164
165bool OutputSectionCommand::classof(const BaseCommand *C) {
166 return C->Kind == OutputSectionKind;
167}
168
George Rimareea31142016-07-21 14:26:59 +0000169bool InputSectionDescription::classof(const BaseCommand *C) {
170 return C->Kind == InputSectionKind;
171}
172
George Rimareefa7582016-08-04 09:29:31 +0000173bool AssertCommand::classof(const BaseCommand *C) {
174 return C->Kind == AssertKind;
175}
176
George Rimare38cbab2016-09-26 19:22:50 +0000177bool BytesDataCommand::classof(const BaseCommand *C) {
178 return C->Kind == BytesDataKind;
179}
180
Eugene Zelenko22886a22016-11-05 01:00:56 +0000181template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
182template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000183
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000184static StringRef basename(InputSectionBase *S) {
185 if (S->File)
186 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000187 return "";
188}
189
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000190template <class ELFT> bool LinkerScript<ELFT>::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000191 for (InputSectionDescription *ID : Opt.KeptSections)
192 if (ID->FilePat.match(basename(S)))
193 for (SectionPattern &P : ID->SectionPatterns)
194 if (P.SectionPat.match(S->Name))
195 return true;
George Rimareea31142016-07-21 14:26:59 +0000196 return false;
197}
198
Rafael Espindolac404d502017-02-23 02:32:18 +0000199static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
George Rimar575208c2016-09-15 19:15:12 +0000200 return getPriority(A->Name) < getPriority(B->Name);
201}
202
Rafael Espindolac404d502017-02-23 02:32:18 +0000203static bool compareName(InputSectionBase *A, InputSectionBase *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000204 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000205}
George Rimar350ece42016-08-03 08:35:59 +0000206
Rafael Espindolac404d502017-02-23 02:32:18 +0000207static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000208 // ">" is not a mistake. Larger alignments are placed before smaller
209 // alignments in order to reduce the amount of padding necessary.
210 // This is compatible with GNU.
211 return A->Alignment > B->Alignment;
212}
George Rimar350ece42016-08-03 08:35:59 +0000213
Rafael Espindolac404d502017-02-23 02:32:18 +0000214static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000215getComparator(SortSectionPolicy K) {
216 switch (K) {
217 case SortSectionPolicy::Alignment:
218 return compareAlignment;
219 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000220 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000221 case SortSectionPolicy::Priority:
222 return comparePriority;
223 default:
224 llvm_unreachable("unknown sort policy");
225 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000226}
George Rimar0702c4e2016-07-29 15:32:46 +0000227
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000228template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000229static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000230 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000231 if (Kind == ConstraintKind::NoConstraint)
232 return true;
Rafael Espindolac404d502017-02-23 02:32:18 +0000233 bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000234 auto *Sec = static_cast<InputSectionBase *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000235 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000236 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000237 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
238 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000239}
240
Rafael Espindolac404d502017-02-23 02:32:18 +0000241static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000242 SortSectionPolicy K) {
243 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000244 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000245}
246
Rafael Espindolad3190792016-09-16 15:10:23 +0000247// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000248template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000249void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000250 // Collects all sections that satisfy constraints of I
251 // and attach them to I.
252 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000253 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000254
Rui Ueyama536a2672017-02-27 02:32:08 +0000255 for (InputSectionBase *S : InputSections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000256 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000257 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000258 // For -emit-relocs we have to ignore entries like
259 // .rela.dyn : { *(.rela.data) }
260 // which are common because they are in the default bfd script.
261 if (S->Type == SHT_REL || S->Type == SHT_RELA)
262 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000263
Rui Ueyamae0be2902016-11-21 02:10:12 +0000264 StringRef Filename = basename(S);
265 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
266 continue;
267 if (!Pat.SectionPat.match(S->Name))
268 continue;
269 I->Sections.push_back(S);
270 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000271 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000272
George Rimar07171f22016-09-21 15:56:44 +0000273 // Sort sections as instructed by SORT-family commands and --sort-section
274 // option. Because SORT-family commands can be nested at most two depth
275 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
276 // line option is respected even if a SORT command is given, the exact
277 // behavior we have here is a bit complicated. Here are the rules.
278 //
279 // 1. If two SORT commands are given, --sort-section is ignored.
280 // 2. If one SORT command is given, and if it is not SORT_NONE,
281 // --sort-section is handled as an inner SORT command.
282 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
283 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindolac404d502017-02-23 02:32:18 +0000284 InputSectionBase **Begin = I->Sections.data() + SizeBefore;
285 InputSectionBase **End = I->Sections.data() + I->Sections.size();
George Rimar07171f22016-09-21 15:56:44 +0000286 if (Pat.SortOuter != SortSectionPolicy::None) {
287 if (Pat.SortInner == SortSectionPolicy::Default)
288 sortSections(Begin, End, Config->SortSection);
289 else
290 sortSections(Begin, End, Pat.SortInner);
291 sortSections(Begin, End, Pat.SortOuter);
292 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000293 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000294}
295
296template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000297void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase *> V) {
298 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000299 S->Live = false;
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000300 if (S == In<ELFT>::ShStrTab)
301 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000302 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000303 }
304}
305
George Rimar06ae6832016-08-12 09:07:57 +0000306template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000307std::vector<InputSectionBase *>
George Rimar06ae6832016-08-12 09:07:57 +0000308LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000309 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000310
George Rimar06ae6832016-08-12 09:07:57 +0000311 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000312 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
313 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000314 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000315 computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000316 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000317 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000318 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000319
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000320 return Ret;
321}
322
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000323template <class ELFT>
Rui Ueyama02a036f2017-02-27 02:31:48 +0000324void LinkerScript<ELFT>::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000325 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
326 auto Iter = Opt.Commands.begin() + I;
327 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000328
329 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000330 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000331 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000332 continue;
333 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000334
Eugene Leviant20d03192016-09-16 15:30:47 +0000335 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
336 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000337 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000338 // will not be called, so ASSERT should be evaluated now.
339 if (!Opt.HasSections)
340 Cmd->Expression(0);
341 continue;
342 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000343
Eugene Leviantceabe802016-08-11 07:56:43 +0000344 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000345 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000346
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000347 // The output section name `/DISCARD/' is special.
348 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000349 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000350 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000351 continue;
352 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000353
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000354 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
355 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
356 // sections satisfy a given constraint. If not, a directive is handled
357 // as if it wasn't present from the beginning.
358 //
359 // Because we'll iterate over Commands many more times, the easiest
360 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000361 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000362 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000363 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000364 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000365 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000366 continue;
367 }
368
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000369 // A directive may contain symbol definitions like this:
370 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000371 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
372 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000373 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000374
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000375 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
376 // is given, input sections are aligned to that value, whether the
377 // given value is larger or smaller than the original section alignment.
378 if (Cmd->SubalignExpr) {
379 uint32_t Subalign = Cmd->SubalignExpr(0);
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000380 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000381 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000382 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000383
384 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000385 for (InputSectionBase *S : V)
Rui Ueyama02a036f2017-02-27 02:31:48 +0000386 Factory.addInputSec<ELFT>(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000387 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000388 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000389}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000390
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000391// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000392template <class ELFT>
Rui Ueyama02a036f2017-02-27 02:31:48 +0000393void LinkerScript<ELFT>::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000394 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000395 if (S->Live && !S->OutSec)
Rui Ueyama02a036f2017-02-27 02:31:48 +0000396 Factory.addInputSec<ELFT>(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000397}
398
Rafael Espindola24e6f362017-02-24 15:07:30 +0000399template <class ELFT> static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000400 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000401}
402
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000403template <class ELFT> void LinkerScript<ELFT>::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000404 if (!AlreadyOutputIS.insert(S).second)
405 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000406 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000407
Rafael Espindolad3190792016-09-16 15:10:23 +0000408 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
409 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000410 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000411 Pos += S->template getSize<ELFT>();
Rafael Espindolad3190792016-09-16 15:10:23 +0000412
413 // Update output section size after adding each section. This is so that
414 // SIZEOF works correctly in the case below:
415 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000416 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000417
Meador Ingeb8897442017-01-24 02:34:00 +0000418 // If there is a memory region associated with this input section, then
419 // place the section in that region and update the region index.
420 if (CurMemRegion) {
421 CurMemRegion->Offset += CurOutSec->Size;
422 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
423 if (CurSize > CurMemRegion->Length) {
424 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
425 error("section '" + CurOutSec->Name + "' will not fit in region '" +
426 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
427 " bytes");
428 }
429 }
430
Rafael Espindola7252ae52016-09-22 12:00:08 +0000431 if (IsTbss)
432 ThreadBssOffset = Pos - Dot;
433 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000434 Dot = Pos;
435}
436
437template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000438 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
439 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000440 for (InputSection *I : CurOutSec->Sections)
441 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000442}
443
Rafael Espindola24e6f362017-02-24 15:07:30 +0000444template <class ELFT> void LinkerScript<ELFT>::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000445 if (CurOutSec == Sec)
446 return;
447 if (AlreadyOutputOS.count(Sec))
448 return;
449
450 flush();
451 CurOutSec = Sec;
452
Rafael Espindola04a2e342016-11-09 01:42:41 +0000453 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000454 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000455
456 // If neither AT nor AT> is specified for an allocatable section, the linker
457 // will set the LMA such that the difference between VMA and LMA for the
458 // section is the same as the preceding output section in the same region
459 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000460 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000461 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000462}
463
464template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000465 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000466 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000467 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000468 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000469 }
George Rimare38cbab2016-09-26 19:22:50 +0000470
471 // Handle BYTE(), SHORT(), LONG(), or QUAD().
472 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000473 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000474 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000475 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000476 return;
477 }
478
Meador Ingeb2d99d62016-11-22 18:01:50 +0000479 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
480 AssertCmd->Expression(Dot);
481 return;
482 }
483
George Rimare38cbab2016-09-26 19:22:50 +0000484 // It handles single input section description command,
485 // calculates and assigns the offsets for each section and also
486 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000487 auto &ICmd = cast<InputSectionDescription>(Base);
Rafael Espindolac404d502017-02-23 02:32:18 +0000488 for (InputSectionBase *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000489 // We tentatively added all synthetic sections at the beginning and removed
490 // empty ones afterwards (because there is no way to know whether they were
491 // going be empty or not other than actually running linker scripts.)
492 // We need to ignore remains of empty sections.
493 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
494 if (Sec->empty())
495 continue;
496
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000497 auto *IB = static_cast<InputSectionBase *>(ID);
George Rimar78ef6452017-02-21 15:46:43 +0000498 if (!IB->Live)
499 continue;
Rafael Espindolad3190792016-09-16 15:10:23 +0000500 switchTo(IB->OutSec);
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000501 if (auto *I = dyn_cast<InputSection>(IB))
Rafael Espindolad3190792016-09-16 15:10:23 +0000502 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000503 else
504 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000505 }
506}
507
George Rimar8f66df92016-08-12 20:38:20 +0000508template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000509static OutputSection *
510findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000511 auto End = Sections.end();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000512 auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
Rafael Espindola2b074552017-02-03 22:27:05 +0000513 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000514 std::vector<OutputSection *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000515 if (I == End)
516 return nullptr;
517 assert(std::find_if(I + 1, End, HasName) == End);
518 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000519}
520
Meador Ingeb8897442017-01-24 02:34:00 +0000521// This function searches for a memory region to place the given output
522// section in. If found, a pointer to the appropriate memory region is
523// returned. Otherwise, a nullptr is returned.
524template <class ELFT>
525MemoryRegion *LinkerScript<ELFT>::findMemoryRegion(OutputSectionCommand *Cmd,
Rafael Espindola24e6f362017-02-24 15:07:30 +0000526 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000527 // If a memory region name was specified in the output section command,
528 // then try to find that region first.
529 if (!Cmd->MemoryRegionName.empty()) {
530 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
531 if (It != Opt.MemoryRegions.end())
532 return &It->second;
533 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
534 return nullptr;
535 }
536
537 // The memory region name is empty, thus a suitable region must be
538 // searched for in the region map. If the region map is empty, just
539 // return. Note that this check doesn't happen at the very beginning
540 // so that uses of undeclared regions can be caught.
541 if (!Opt.MemoryRegions.size())
542 return nullptr;
543
544 // See if a region can be found by matching section flags.
545 for (auto &MRI : Opt.MemoryRegions) {
546 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000547 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000548 return &MR;
549 }
550
551 // Otherwise, no suitable region was found.
552 if (Sec->Flags & SHF_ALLOC)
553 error("no memory region specified for section '" + Sec->Name + "'");
554 return nullptr;
555}
556
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000557// This function assigns offsets to input sections and an output section
558// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000559template <class ELFT>
560void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar21467872017-02-23 07:57:55 +0000561 if (Cmd->LMAExpr) {
562 uintX_t D = Dot;
563 LMAOffset = [=] { return Cmd->LMAExpr(D) - D; };
564 }
Rafael Espindola24e6f362017-02-24 15:07:30 +0000565 OutputSection *Sec = findSection<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000566 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000567 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000568
Rafael Espindola679828f2017-02-17 16:26:13 +0000569 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000570 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000571
Petr Hosek165088a2017-02-07 23:42:31 +0000572 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
573 if (Cmd->AlignExpr)
574 Sec->updateAlignment(Cmd->AlignExpr(0));
575
Meador Ingeb8897442017-01-24 02:34:00 +0000576 // Try and find an appropriate memory region to assign offsets in.
577 CurMemRegion = findMemoryRegion(Cmd, Sec);
578 if (CurMemRegion)
579 Dot = CurMemRegion->Offset;
580 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000581
Rafael Espindolad3190792016-09-16 15:10:23 +0000582 // Find the last section output location. We will output orphan sections
583 // there so that end symbols point to the correct location.
584 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
585 [](const std::unique_ptr<BaseCommand> &Cmd) {
586 return !isa<SymbolAssignment>(*Cmd);
587 })
588 .base();
589 for (auto I = Cmd->Commands.begin(); I != E; ++I)
590 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000591 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000592 std::for_each(E, Cmd->Commands.end(),
593 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000594}
595
Rafael Espindola07fe6122016-11-14 14:23:35 +0000596template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000597 // It is common practice to use very generic linker scripts. So for any
598 // given run some of the output sections in the script will be empty.
599 // We could create corresponding empty output sections, but that would
600 // clutter the output.
601 // We instead remove trivially empty sections. The bfd linker seems even
602 // more aggressive at removing them.
603 auto Pos = std::remove_if(
604 Opt.Commands.begin(), Opt.Commands.end(),
605 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000606 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Rafael Espindola2b074552017-02-03 22:27:05 +0000607 return !findSection<ELFT>(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000608 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000609 });
610 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000611}
612
Rafael Espindola6a537372016-11-14 14:33:49 +0000613static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
614 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
615 if (!isa<InputSectionDescription>(*I))
616 return false;
617 return true;
618}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000619
Rafael Espindola6a537372016-11-14 14:33:49 +0000620template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000621 // If the output section contains only symbol assignments, create a
622 // corresponding output section. The bfd linker seems to only create them if
623 // '.' is assigned to, but creating these section should not have any bad
624 // consequeces and gives us a section to put the symbol in.
625 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000626 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000627 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
628 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
629 if (!Cmd)
630 continue;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000631 if (OutputSection *Sec = findSection<ELFT>(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000632 Flags = Sec->Flags;
633 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000634 continue;
635 }
636
Rafael Espindola6a537372016-11-14 14:33:49 +0000637 if (isAllSectionDescription(*Cmd))
638 continue;
639
Rafael Espindola24e6f362017-02-24 15:07:30 +0000640 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000641 OutputSections->push_back(OutSec);
642 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000643}
644
645template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
646 placeOrphanSections();
647
648 // If output section command doesn't specify any segments,
649 // and we haven't previously assigned any section to segment,
650 // then we simply assign section to the very first load segment.
651 // Below is an example of such linker script:
652 // PHDRS { seg PT_LOAD; }
653 // SECTIONS { .aaa : { *(.aaa) } }
654 std::vector<StringRef> DefPhdrs;
655 auto FirstPtLoad =
656 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
657 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
658 if (FirstPtLoad != Opt.PhdrsCommands.end())
659 DefPhdrs.push_back(FirstPtLoad->Name);
660
661 // Walk the commands and propagate the program headers to commands that don't
662 // explicitly specify them.
663 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
664 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
665 if (!Cmd)
666 continue;
667 if (Cmd->Phdrs.empty())
668 Cmd->Phdrs = DefPhdrs;
669 else
670 DefPhdrs = Cmd->Phdrs;
671 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000672
673 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000674}
675
Rafael Espindola15c57952016-09-22 18:05:49 +0000676// When placing orphan sections, we want to place them after symbol assignments
677// so that an orphan after
678// begin_foo = .;
679// foo : { *(foo) }
680// end_foo = .;
681// doesn't break the intended meaning of the begin/end symbols.
682// We don't want to go over sections since Writer<ELFT>::sortSections is the
683// one in charge of deciding the order of the sections.
684// We don't want to go over alignments, since doing so in
685// rx_sec : { *(rx_sec) }
686// . = ALIGN(0x1000);
687// /* The RW PT_LOAD starts here*/
688// rw_sec : { *(rw_sec) }
689// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000690static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000691 if (isa<OutputSectionCommand>(Cmd))
692 return false;
693 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
694 if (!Assign)
695 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000696 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000697}
698
Rui Ueyama6697ec22017-02-02 23:26:12 +0000699// Orphan sections are sections present in the input files which are
700// not explicitly placed into the output file by the linker script.
701//
702// When the control reaches this function, Opt.Commands contains
703// output section commands for non-orphan sections only. This function
704// adds new elements for orphan sections to Opt.Commands so that all
705// sections are explicitly handled by Opt.Commands.
706//
707// Writer<ELFT>::sortSections has already sorted output sections.
708// What we need to do is to scan OutputSections vector and
709// Opt.Commands in parallel to find orphan sections. If there is an
710// output section that doesn't have a corresponding entry in
711// Opt.Commands, we will insert a new entry to Opt.Commands.
712//
713// There is some ambiguity as to where exactly a new entry should be
714// inserted, because Opt.Commands contains not only output section
715// commands but other types of commands such as symbol assignment
716// expressions. There's no correct answer here due to the lack of the
717// formal specification of the linker script. We use heuristics to
718// determine whether a new output command should be added before or
719// after another commands. For the details, look at shouldSkip
720// function.
George Rimar93c64022016-12-15 15:38:09 +0000721template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000722 // The OutputSections are already in the correct order.
723 // This loops creates or moves commands as needed so that they are in the
724 // correct order.
725 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000726
727 // As a horrible special case, skip the first . assignment if it is before any
728 // section. We do this because it is common to set a load address by starting
729 // the script with ". = 0xabcd" and the expectation is that every section is
730 // after that.
731 auto FirstSectionOrDotAssignment =
732 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
733 [](const std::unique_ptr<BaseCommand> &Cmd) {
734 if (isa<OutputSectionCommand>(*Cmd))
735 return true;
736 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
737 if (!Assign)
738 return false;
739 return Assign->Name == ".";
740 });
741 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
742 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
743 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
744 ++CmdIndex;
745 }
746
Rafael Espindola24e6f362017-02-24 15:07:30 +0000747 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000748 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000749
750 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000751 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000752 auto CmdIter = Opt.Commands.begin() + CmdIndex;
753 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000754 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000755 ++CmdIter;
756 ++CmdIndex;
757 }
758
759 auto Pos =
760 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
761 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
762 return Cmd && Cmd->Name == Name;
763 });
764 if (Pos == E) {
765 Opt.Commands.insert(CmdIter,
766 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000767 ++CmdIndex;
768 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000769 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000770
771 // Continue from where we found it.
772 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000773 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000774}
775
776template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000777void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000778 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000779 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000780
Rafael Espindola06f47432017-02-06 22:21:46 +0000781 // A symbol can be assigned before any section is mentioned in the linker
782 // script. In an DSO, the symbol values are addresses, so the only important
783 // section values are:
784 // * SHN_UNDEF
785 // * SHN_ABS
786 // * Any value meaning a regular section.
787 // To handle that, create a dummy aether section that fills the void before
788 // the linker scripts switches to another section. It has an index of one
789 // which will map to whatever the first actual section is.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000790 auto *Aether = make<OutputSection>("", 0, SHF_ALLOC);
Rafael Espindola06f47432017-02-06 22:21:46 +0000791 Aether->SectionIndex = 1;
792 switchTo(Aether);
793
George Rimar076fe152016-07-21 06:43:01 +0000794 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
795 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000796 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000797 continue;
798 }
799
George Rimareefa7582016-08-04 09:29:31 +0000800 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
801 Cmd->Expression(Dot);
802 continue;
803 }
804
George Rimar076fe152016-07-21 06:43:01 +0000805 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000806 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000807 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000808
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000809 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000810 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000811 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000812 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000813 else
814 Sec->Addr = 0;
815 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000816
Rafael Espindola8c495e22017-01-20 20:41:18 +0000817 allocateHeaders<ELFT>(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000818}
819
Rui Ueyama464daad2016-08-22 04:55:20 +0000820// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000821template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
822 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000823
Rui Ueyama464daad2016-08-22 04:55:20 +0000824 // Process PHDRS and FILEHDR keywords because they are not
825 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000826 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000827 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000828 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000829
830 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000831 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000832 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000833 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000834
835 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000836 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000837 Phdr.HasLMA = true;
838 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000839 }
840
Rui Ueyama464daad2016-08-22 04:55:20 +0000841 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000842 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000843 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000844 break;
845
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000846 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000847 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000848 Ret[Id].add(Sec);
849 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000850 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000851 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000852 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000853 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000854}
855
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000856template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
857 // Ignore .interp section in case we have PHDRS specification
858 // and PT_INTERP isn't listed.
859 return !Opt.PhdrsCommands.empty() &&
860 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
861 return Cmd.Type == PT_INTERP;
862 }) == Opt.PhdrsCommands.end();
863}
864
George Rimar93c64022016-12-15 15:38:09 +0000865template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000866 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
867 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
868 if (Cmd->Name == Name)
869 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000870 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000871}
872
George Rimare38cbab2016-09-26 19:22:50 +0000873template <class ELFT>
874static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
875 const endianness E = ELFT::TargetEndianness;
876
877 switch (Size) {
878 case 1:
879 *Buf = (uint8_t)Data;
880 break;
881 case 2:
882 write16<E>(Buf, Data);
883 break;
884 case 4:
885 write32<E>(Buf, Data);
886 break;
887 case 8:
888 write64<E>(Buf, Data);
889 break;
890 default:
891 llvm_unreachable("unsupported Size argument");
892 }
893}
894
895template <class ELFT>
896void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
897 int I = getSectionIndex(Name);
898 if (I == INT_MAX)
899 return;
900
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000901 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
902 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
903 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000904 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000905}
906
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000907template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000908 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
909 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000910 if (Cmd->LMAExpr && Cmd->Name == Name)
911 return true;
912 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000913}
914
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000915// Returns the index of the given section name in linker script
916// SECTIONS commands. Sections are laid out as the same order as they
917// were in the script. If a given name did not appear in the script,
918// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000919template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000920 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
921 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000922 if (Cmd->Name == Name)
923 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000924 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000925}
926
Eugene Leviantbbe38602016-07-19 09:25:43 +0000927template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
928 return !Opt.PhdrsCommands.empty();
929}
930
George Rimar9e694502016-07-29 16:18:47 +0000931template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000932const OutputSection *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
933 StringRef Name) {
934 static OutputSection FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000935
Rafael Espindola24e6f362017-02-24 15:07:30 +0000936 for (OutputSection *Sec : *OutputSections)
Rafael Espindola40849412017-02-24 14:28:00 +0000937 if (Sec->Name == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000938 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000939
940 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000941 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000942}
943
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000944// This function is essentially the same as getOutputSection(Name)->Size,
945// but it won't print out an error message if a given section is not found.
946//
947// Linker script does not create an output section if its content is empty.
948// We want to allow SIZEOF(.foo) where .foo is a section which happened to
949// be empty. That is why this function is different from getOutputSection().
950template <class ELFT>
951uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000952 for (OutputSection *Sec : *OutputSections)
Rafael Espindola40849412017-02-24 14:28:00 +0000953 if (Sec->Name == Name)
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000954 return Sec->Size;
955 return 0;
956}
957
George Rimar884e7862016-09-08 08:19:13 +0000958template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000959 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000960}
961
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000962template <class ELFT>
963uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar884e7862016-09-08 08:19:13 +0000964 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
965 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000966 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000967 return 0;
968}
969
George Rimarf34f45f2016-09-23 13:17:23 +0000970template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
971 return Symtab<ELFT>::X->find(S) != nullptr;
972}
973
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000974template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
975 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
976 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
977 return DR && !DR->Section;
978}
979
Eugene Leviantafaa9342016-11-16 09:49:39 +0000980// Gets section symbol belongs to. Symbol "." doesn't belong to any
981// specific section but isn't absolute at the same time, so we try
982// to find suitable section for it as well.
983template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000984const OutputSection *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
Rafael Espindola06f47432017-02-06 22:21:46 +0000985 if (SymbolBody *Sym = Symtab<ELFT>::X->find(S))
986 return SymbolTableSection<ELFT>::getOutputSection(Sym);
987 return CurOutSec;
Eugene Leviantafaa9342016-11-16 09:49:39 +0000988}
989
Eugene Leviantbbe38602016-07-19 09:25:43 +0000990// Returns indices of ELF headers containing specific section, identified
991// by Name. Each index is a zero based number of ELF header listed within
992// PHDRS {} script block.
993template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000994std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000995 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
996 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000997 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000998 continue;
999
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001000 std::vector<size_t> Ret;
1001 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001002 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001003 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001004 }
George Rimar31d842f2016-07-20 16:43:03 +00001005 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001006}
1007
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001008template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +00001009size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001010 size_t I = 0;
1011 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1012 if (Cmd.Name == PhdrName)
1013 return I;
1014 ++I;
1015 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001016 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001017 return 0;
1018}
1019
Rui Ueyama794366a2017-02-14 04:47:05 +00001020class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001021 typedef void (ScriptParser::*Handler)();
1022
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001023public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001024 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001025 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001026 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001027
George Rimar20b65982016-08-31 09:08:26 +00001028 void readLinkerScript();
1029 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001030 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001031
1032private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001033 void addFile(StringRef Path);
1034
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001035 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001036 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001037 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001038 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001039 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001040 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001041 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001042 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001043 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001044 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001045 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001046 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001047 void readVersion();
1048 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001049
Rui Ueyama113cdec2016-07-24 23:05:57 +00001050 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001051 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001052 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001053 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001054 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001055 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001056 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001057 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001058 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001059 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001060 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001061 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001062 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001063 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001064 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001065 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001066
Rui Ueyama24e626c2017-01-26 02:58:19 +00001067 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1068 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1069
Rui Ueyama708019c2016-07-24 18:19:40 +00001070 Expr readExpr();
1071 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001072 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001073 Expr readPrimary();
1074 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001075 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001076
George Rimar20b65982016-08-31 09:08:26 +00001077 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001078 std::vector<SymbolVersion> readVersionExtern();
1079 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001080 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001081 std::vector<SymbolVersion> readSymbols();
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001082 void readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001083
Rui Ueyama07320e42016-04-20 20:13:41 +00001084 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001085 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001086};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001087
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001088void ScriptParser::readDynamicList() {
1089 expect("{");
1090 readAnonymousDeclaration();
1091 if (!atEOF())
1092 setError("EOF expected, but got " + next());
1093}
1094
George Rimar20b65982016-08-31 09:08:26 +00001095void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001096 readVersionScriptCommand();
1097 if (!atEOF())
1098 setError("EOF expected, but got " + next());
1099}
1100
1101void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001102 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001103 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001104 return;
1105 }
1106
Rui Ueyama95769b42016-08-31 20:03:54 +00001107 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001108 StringRef VerStr = next();
1109 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001110 setError("anonymous version definition is used in "
1111 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001112 return;
1113 }
1114 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001115 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001116 }
1117}
1118
Rui Ueyama95769b42016-08-31 20:03:54 +00001119void ScriptParser::readVersion() {
1120 expect("{");
1121 readVersionScriptCommand();
1122 expect("}");
1123}
1124
George Rimar20b65982016-08-31 09:08:26 +00001125void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001126 while (!atEOF()) {
1127 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001128 if (Tok == ";")
1129 continue;
1130
Eugene Leviant20d03192016-09-16 15:30:47 +00001131 if (Tok == "ASSERT") {
1132 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1133 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001134 readEntry();
1135 } else if (Tok == "EXTERN") {
1136 readExtern();
1137 } else if (Tok == "GROUP" || Tok == "INPUT") {
1138 readGroup();
1139 } else if (Tok == "INCLUDE") {
1140 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001141 } else if (Tok == "MEMORY") {
1142 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001143 } else if (Tok == "OUTPUT") {
1144 readOutput();
1145 } else if (Tok == "OUTPUT_ARCH") {
1146 readOutputArch();
1147 } else if (Tok == "OUTPUT_FORMAT") {
1148 readOutputFormat();
1149 } else if (Tok == "PHDRS") {
1150 readPhdrs();
1151 } else if (Tok == "SEARCH_DIR") {
1152 readSearchDir();
1153 } else if (Tok == "SECTIONS") {
1154 readSections();
1155 } else if (Tok == "VERSION") {
1156 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001157 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001158 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001159 } else {
George Rimar57610422016-03-11 14:43:02 +00001160 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001161 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001162 }
1163}
1164
Rui Ueyama717677a2016-02-11 21:17:59 +00001165void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001166 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001167 SmallString<128> PathData;
1168 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001169 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001170 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001171 return;
1172 }
1173 }
1174
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001175 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001176 Driver->addFile(S);
1177 } else if (S.startswith("=")) {
1178 if (Config->Sysroot.empty())
1179 Driver->addFile(S.substr(1));
1180 else
1181 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1182 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001183 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001184 } else if (sys::fs::exists(S)) {
1185 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001186 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001187 if (Optional<std::string> Path = findFromSearchPaths(S))
1188 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001189 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001190 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001191 }
1192}
1193
Rui Ueyama717677a2016-02-11 21:17:59 +00001194void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001195 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001196 bool Orig = Config->AsNeeded;
1197 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001198 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001199 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001200 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001201}
1202
Rui Ueyama717677a2016-02-11 21:17:59 +00001203void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001204 // -e <symbol> takes predecence over ENTRY(<symbol>).
1205 expect("(");
1206 StringRef Tok = next();
1207 if (Config->Entry.empty())
1208 Config->Entry = Tok;
1209 expect(")");
1210}
1211
Rui Ueyama717677a2016-02-11 21:17:59 +00001212void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001213 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001214 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001215 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001216}
1217
Rui Ueyama717677a2016-02-11 21:17:59 +00001218void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001219 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001220 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001221 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001222 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001223 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001224 else
George Rimarcd574a52016-09-09 14:35:36 +00001225 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001226 }
1227}
1228
Rui Ueyama717677a2016-02-11 21:17:59 +00001229void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001230 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001231
George Rimard4500652016-12-21 09:42:25 +00001232 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1233 // The file will be searched for in the current directory, and in any
1234 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001235 if (sys::fs::exists(Tok)) {
1236 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1237 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001238 return;
1239 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001240 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1241 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1242 tokenize(*MB);
1243 return;
1244 }
1245 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001246}
1247
Rui Ueyama717677a2016-02-11 21:17:59 +00001248void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001249 // -o <file> takes predecence over OUTPUT(<file>).
1250 expect("(");
1251 StringRef Tok = next();
1252 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001253 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001254 expect(")");
1255}
1256
Rui Ueyama717677a2016-02-11 21:17:59 +00001257void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001258 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001259 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001260 while (!Error && !consume(")"))
1261 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001262}
1263
Rui Ueyama717677a2016-02-11 21:17:59 +00001264void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001265 // Error checking only for now.
1266 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001267 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001268 StringRef Tok = next();
1269 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001270 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001271 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001272 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001273 return;
1274 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001275 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001276 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001277 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001278 expect(")");
1279}
1280
Eugene Leviantbbe38602016-07-19 09:25:43 +00001281void ScriptParser::readPhdrs() {
1282 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001283 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001284 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001285 Opt.PhdrsCommands.push_back(
1286 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001287 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1288
1289 PhdrCmd.Type = readPhdrType();
1290 do {
1291 Tok = next();
1292 if (Tok == ";")
1293 break;
1294 if (Tok == "FILEHDR")
1295 PhdrCmd.HasFilehdr = true;
1296 else if (Tok == "PHDRS")
1297 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001298 else if (Tok == "AT")
1299 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001300 else if (Tok == "FLAGS") {
1301 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001302 // Passing 0 for the value of dot is a bit of a hack. It means that
1303 // we accept expressions like ".|1".
1304 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001305 expect(")");
1306 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001307 setError("unexpected header attribute: " + Tok);
1308 } while (!Error);
1309 }
1310}
1311
Rui Ueyama717677a2016-02-11 21:17:59 +00001312void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001313 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001314 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001315 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001316 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001317 expect(")");
1318}
1319
Rui Ueyama717677a2016-02-11 21:17:59 +00001320void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001321 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001322 // -no-rosegment is used to avoid placing read only non-executable sections in
1323 // their own segment. We do the same if SECTIONS command is present in linker
1324 // script. See comment for computeFlags().
1325 Config->SingleRoRx = true;
1326
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001327 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001328 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001329 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001330 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001331 if (!Cmd) {
1332 if (Tok == "ASSERT")
1333 Cmd = new AssertCommand(readAssert());
1334 else
1335 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001336 }
Rui Ueyama10416562016-08-04 02:03:27 +00001337 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001338 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001339}
1340
Rui Ueyama708019c2016-07-24 18:19:40 +00001341static int precedence(StringRef Op) {
1342 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001343 .Cases("*", "/", 5)
1344 .Cases("+", "-", 4)
1345 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001346 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001347 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001348 .Default(-1);
1349}
1350
Eugene Leviantdb688452016-11-03 10:54:58 +00001351StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001352 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001353 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001354 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001355 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001356}
1357
George Rimarbe394db2016-09-16 20:21:55 +00001358SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001359 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001360 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001361 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001362 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001363 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001364 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001365 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001366 return SortSectionPolicy::None;
1367 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001368}
1369
George Rimar395281c2016-09-16 17:42:10 +00001370// Method reads a list of sequence of excluded files and section globs given in
1371// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1372// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001373// The semantics of that is next:
1374// * Include .foo.1 from every file.
1375// * Include .foo.2 from every file but a.o
1376// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001377std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1378 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001379 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001380 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001381 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001382 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001383 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001384 }
1385
George Rimar601e9892016-09-21 08:53:21 +00001386 std::vector<StringRef> V;
1387 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1388 V.push_back(next());
1389
1390 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001391 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001392 else
1393 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001394 }
George Rimar07171f22016-09-21 15:56:44 +00001395 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001396}
1397
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001398// Reads contents of "SECTIONS" directive. That directive contains a
1399// list of glob patterns for input sections. The grammar is as follows.
1400//
1401// <patterns> ::= <section-list>
1402// | <sort> "(" <section-list> ")"
1403// | <sort> "(" <sort> "(" <section-list> ")" ")"
1404//
1405// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1406// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1407//
1408// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001409InputSectionDescription *
1410ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001411 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001412 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001413 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001414 SortSectionPolicy Outer = readSortKind();
1415 SortSectionPolicy Inner = SortSectionPolicy::Default;
1416 std::vector<SectionPattern> V;
1417 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001418 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001419 Inner = readSortKind();
1420 if (Inner != SortSectionPolicy::Default) {
1421 expect("(");
1422 V = readInputSectionsList();
1423 expect(")");
1424 } else {
1425 V = readInputSectionsList();
1426 }
George Rimar350ece42016-08-03 08:35:59 +00001427 expect(")");
1428 } else {
George Rimar07171f22016-09-21 15:56:44 +00001429 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001430 }
George Rimar0702c4e2016-07-29 15:32:46 +00001431
George Rimar07171f22016-09-21 15:56:44 +00001432 for (SectionPattern &Pat : V) {
1433 Pat.SortInner = Inner;
1434 Pat.SortOuter = Outer;
1435 }
1436
1437 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1438 }
Rui Ueyama10416562016-08-04 02:03:27 +00001439 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001440}
1441
George Rimara2496cb2016-08-30 09:46:59 +00001442InputSectionDescription *
1443ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001444 // Input section wildcard can be surrounded by KEEP.
1445 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001446 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001447 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001448 StringRef FilePattern = next();
1449 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001450 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001451 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001452 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001453 }
George Rimara2496cb2016-08-30 09:46:59 +00001454 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001455}
1456
George Rimar03fc0102016-07-28 07:18:23 +00001457void ScriptParser::readSort() {
1458 expect("(");
1459 expect("CONSTRUCTORS");
1460 expect(")");
1461}
1462
George Rimareefa7582016-08-04 09:29:31 +00001463Expr ScriptParser::readAssert() {
1464 expect("(");
1465 Expr E = readExpr();
1466 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001467 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001468 expect(")");
1469 return [=](uint64_t Dot) {
George Rimar60f1fe82017-02-21 07:33:38 +00001470 if (!E(Dot))
George Rimareefa7582016-08-04 09:29:31 +00001471 error(Msg);
George Rimar60f1fe82017-02-21 07:33:38 +00001472 return Dot;
George Rimareefa7582016-08-04 09:29:31 +00001473 };
1474}
1475
Rui Ueyama25150e82016-09-06 17:46:43 +00001476// Reads a FILL(expr) command. We handle the FILL command as an
1477// alias for =fillexp section attribute, which is different from
1478// what GNU linkers do.
1479// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001480uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001481 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001482 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001483 expect(")");
1484 expect(";");
1485 return V;
1486}
1487
Rui Ueyama10416562016-08-04 02:03:27 +00001488OutputSectionCommand *
1489ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001490 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001491 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001492
1493 // Read an address expression.
1494 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1495 if (peek() != ":")
1496 Cmd->AddrExpr = readExpr();
1497
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001498 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001499
Rui Ueyama83043f22016-10-17 16:01:53 +00001500 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001501 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001502 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001503 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001504 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001505 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001506
Davide Italiano246f6812016-07-22 03:36:24 +00001507 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001508 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001509 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001510 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001511 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001512 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001513
Rui Ueyama83043f22016-10-17 16:01:53 +00001514 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001515 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001516 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001517 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001518 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001519 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001520 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001521 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001522 } else if (Tok == "ASSERT") {
1523 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1524 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001525 } else if (Tok == "CONSTRUCTORS") {
1526 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1527 // by name. This is for very old file formats such as ECOFF/XCOFF.
1528 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001529 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001530 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001531 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001532 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001533 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001534 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001535 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001536 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001537 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001538 }
Meador Ingeb8897442017-01-24 02:34:00 +00001539
1540 if (consume(">"))
1541 Cmd->MemoryRegionName = next();
1542
George Rimar076fe152016-07-21 06:43:01 +00001543 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001544
Rui Ueyama83043f22016-10-17 16:01:53 +00001545 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001546 Cmd->Filler = readOutputSectionFiller(next());
1547 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001548 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001549
George Rimar7185a1a2017-01-17 15:32:12 +00001550 // Consume optional comma following output section command.
1551 consume(",");
1552
Rui Ueyama10416562016-08-04 02:03:27 +00001553 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001554}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001555
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001556// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1557// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1558//
1559// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1560// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1561// as 32-bit big-endian values. We will do the same as ld.gold does
1562// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001563uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001564 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001565 if (!Tok.getAsInteger(0, V))
1566 return V;
1567 setError("invalid filler expression: " + Tok);
1568 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001569}
1570
Petr Hoseka35e39c2016-08-16 01:11:16 +00001571SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001572 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001573 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001574 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001575 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001576 expect(")");
1577 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001578 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001579}
1580
Rafael Espindolac96da112016-11-01 11:30:45 +00001581SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001582 SymbolAssignment *Cmd = nullptr;
1583 if (peek() == "=" || peek() == "+=") {
1584 Cmd = readAssignment(Tok);
1585 expect(";");
1586 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001587 Cmd = readProvideHidden(true, false);
1588 } else if (Tok == "HIDDEN") {
1589 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001590 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001591 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001592 }
1593 return Cmd;
1594}
1595
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001596static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
George Rimar30835ea2016-07-28 21:08:56 +00001597 if (S == ".")
1598 return Dot;
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001599 return ScriptBase->getSymbolValue(Loc, S);
George Rimare32a3592016-08-10 07:59:34 +00001600}
1601
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001602static bool isAbsolute(StringRef S) {
1603 if (S == ".")
1604 return false;
1605 return ScriptBase->isAbsolute(S);
1606}
1607
George Rimar30835ea2016-07-28 21:08:56 +00001608SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1609 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001610 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001611 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001612 if (consume("ABSOLUTE")) {
Rui Ueyama731a66a2017-02-15 19:58:17 +00001613 E = readExpr();
Rui Ueyama009d1742016-11-18 06:49:09 +00001614 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001615 } else {
1616 E = readExpr();
1617 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001618 if (Op == "+=") {
1619 std::string Loc = getCurrentLocation();
1620 E = [=](uint64_t Dot) {
1621 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1622 };
1623 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001624 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001625}
1626
1627// This is an operator-precedence parser to parse a linker
1628// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001629Expr ScriptParser::readExpr() {
1630 // Our lexer is context-aware. Set the in-expression bit so that
1631 // they apply different tokenization rules.
1632 bool Orig = InExpr;
1633 InExpr = true;
1634 Expr E = readExpr1(readPrimary(), 0);
1635 InExpr = Orig;
1636 return E;
1637}
George Rimar30835ea2016-07-28 21:08:56 +00001638
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001639static Expr combine(StringRef Op, Expr L, Expr R) {
George Rimarcc4d3e52017-02-01 09:01:16 +00001640 auto IsAbs = [=] { return L.IsAbsolute() && R.IsAbsolute(); };
1641 auto GetOutSec = [=] {
Rafael Espindola24e6f362017-02-24 15:07:30 +00001642 const OutputSection *S = L.Section();
George Rimarcc4d3e52017-02-01 09:01:16 +00001643 return S ? S : R.Section();
1644 };
1645
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001646 if (Op == "*")
1647 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1648 if (Op == "/") {
1649 return [=](uint64_t Dot) -> uint64_t {
1650 uint64_t RHS = R(Dot);
1651 if (RHS == 0) {
1652 error("division by zero");
1653 return 0;
1654 }
1655 return L(Dot) / RHS;
1656 };
1657 }
1658 if (Op == "+")
George Rimarcc4d3e52017-02-01 09:01:16 +00001659 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); }, IsAbs, GetOutSec};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001660 if (Op == "-")
George Rimarcc4d3e52017-02-01 09:01:16 +00001661 return {[=](uint64_t Dot) { return L(Dot) - R(Dot); }, IsAbs, GetOutSec};
George Rimarc8ccd1f2016-09-23 13:13:55 +00001662 if (Op == "<<")
1663 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1664 if (Op == ">>")
1665 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001666 if (Op == "<")
1667 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1668 if (Op == ">")
1669 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1670 if (Op == ">=")
1671 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1672 if (Op == "<=")
1673 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1674 if (Op == "==")
1675 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1676 if (Op == "!=")
1677 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1678 if (Op == "&")
1679 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001680 if (Op == "|")
1681 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001682 llvm_unreachable("invalid operator");
1683}
1684
Rui Ueyama708019c2016-07-24 18:19:40 +00001685// This is a part of the operator-precedence parser. This function
1686// assumes that the remaining token stream starts with an operator.
1687Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1688 while (!atEOF() && !Error) {
1689 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001690 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001691 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001692 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001693 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001694 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001695 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001696 Expr Rhs = readPrimary();
1697
1698 // Evaluate the remaining part of the expression first if the
1699 // next operator has greater precedence than the previous one.
1700 // For example, if we have read "+" and "3", and if the next
1701 // operator is "*", then we'll evaluate 3 * ... part first.
1702 while (!atEOF()) {
1703 StringRef Op2 = peek();
1704 if (precedence(Op2) <= precedence(Op1))
1705 break;
1706 Rhs = readExpr1(Rhs, precedence(Op2));
1707 }
1708
1709 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001710 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001711 return Lhs;
1712}
1713
1714uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001715 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001716 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001717 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001718 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001719 error("unknown constant: " + S);
1720 return 0;
1721}
1722
Rui Ueyama626e0b02016-09-02 18:19:00 +00001723// Parses Tok as an integer. Returns true if successful.
1724// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1725// and decimal numbers. Decimal numbers may have "K" (kilo) or
1726// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001727static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001728 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001729 if (Tok.startswith("-")) {
1730 if (!readInteger(Tok.substr(1), Result))
1731 return false;
1732 Result = -Result;
1733 return true;
1734 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001735
1736 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001737 if (Tok.startswith_lower("0x"))
1738 return !Tok.substr(2).getAsInteger(16, Result);
1739 if (Tok.endswith_lower("H"))
1740 return !Tok.drop_back().getAsInteger(16, Result);
1741
Rui Ueyama46247b82016-11-18 06:49:07 +00001742 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001743 int Suffix = 1;
1744 if (Tok.endswith_lower("K")) {
1745 Suffix = 1024;
1746 Tok = Tok.drop_back();
1747 } else if (Tok.endswith_lower("M")) {
1748 Suffix = 1024 * 1024;
1749 Tok = Tok.drop_back();
1750 }
1751 if (Tok.getAsInteger(10, Result))
1752 return false;
1753 Result *= Suffix;
1754 return true;
1755}
1756
George Rimare38cbab2016-09-26 19:22:50 +00001757BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1758 int Size = StringSwitch<unsigned>(Tok)
1759 .Case("BYTE", 1)
1760 .Case("SHORT", 2)
1761 .Case("LONG", 4)
1762 .Case("QUAD", 8)
1763 .Default(-1);
1764 if (Size == -1)
1765 return nullptr;
1766
Meador Inge95c7d8d2016-12-08 23:21:30 +00001767 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001768}
1769
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001770StringRef ScriptParser::readParenLiteral() {
1771 expect("(");
1772 StringRef Tok = next();
1773 expect(")");
1774 return Tok;
1775}
1776
Rui Ueyama708019c2016-07-24 18:19:40 +00001777Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001778 if (peek() == "(")
1779 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001780
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001781 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001782 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001783
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001784 if (Tok == "~") {
1785 Expr E = readPrimary();
1786 return [=](uint64_t Dot) { return ~E(Dot); };
1787 }
1788 if (Tok == "-") {
1789 Expr E = readPrimary();
1790 return [=](uint64_t Dot) { return -E(Dot); };
1791 }
1792
Rui Ueyama708019c2016-07-24 18:19:40 +00001793 // Built-in functions are parsed here.
1794 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001795 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001796 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001797 return {[=](uint64_t Dot) {
1798 return ScriptBase->getOutputSection(Location, Name)->Addr;
1799 },
1800 [=] { return false; },
1801 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001802 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001803 if (Tok == "LOADADDR") {
1804 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001805 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001806 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001807 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001808 }
George Rimareefa7582016-08-04 09:29:31 +00001809 if (Tok == "ASSERT")
1810 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001811 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001812 expect("(");
1813 Expr E = readExpr();
1814 if (consume(",")) {
1815 Expr E2 = readExpr();
1816 expect(")");
1817 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1818 }
1819 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001820 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1821 }
1822 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001823 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001824 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001825 }
George Rimarf34f45f2016-09-23 13:17:23 +00001826 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001827 StringRef Name = readParenLiteral();
1828 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001829 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001830 if (Tok == "SEGMENT_START") {
1831 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001832 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001833 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001834 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001835 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001836 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001837 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001838 if (Tok == "DATA_SEGMENT_ALIGN") {
1839 expect("(");
1840 Expr E = readExpr();
1841 expect(",");
1842 readExpr();
1843 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001844 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001845 }
1846 if (Tok == "DATA_SEGMENT_END") {
1847 expect("(");
1848 expect(".");
1849 expect(")");
1850 return [](uint64_t Dot) { return Dot; };
1851 }
George Rimar276b4e62016-07-26 17:58:44 +00001852 // GNU linkers implements more complicated logic to handle
1853 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1854 // the next page boundary for simplicity.
1855 if (Tok == "DATA_SEGMENT_RELRO_END") {
1856 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001857 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001858 expect(",");
1859 readExpr();
1860 expect(")");
1861 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1862 }
George Rimar9e694502016-07-29 16:18:47 +00001863 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001864 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001865 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001866 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001867 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001868 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001869 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001870 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001871 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001872 }
George Rimare32a3592016-08-10 07:59:34 +00001873 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001874 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001875
George Rimar9f2f7ad2016-09-02 16:01:42 +00001876 // Tok is a literal number.
1877 uint64_t V;
1878 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001879 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001880
1881 // Tok is a symbol name.
1882 if (Tok != "." && !isValidCIdentifier(Tok))
1883 setError("malformed number: " + Tok);
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001884 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001885 [=] { return isAbsolute(Tok); },
1886 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001887}
1888
1889Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001890 Expr L = readExpr();
1891 expect(":");
1892 Expr R = readExpr();
1893 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1894}
1895
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001896Expr ScriptParser::readParenExpr() {
1897 expect("(");
1898 Expr E = readExpr();
1899 expect(")");
1900 return E;
1901}
1902
Eugene Leviantbbe38602016-07-19 09:25:43 +00001903std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1904 std::vector<StringRef> Phdrs;
1905 while (!Error && peek().startswith(":")) {
1906 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001907 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001908 }
1909 return Phdrs;
1910}
1911
George Rimar95dd7182016-10-18 10:49:50 +00001912// Read a program header type name. The next token must be a
1913// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001914unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001915 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001916 uint64_t Val;
1917 if (readInteger(Tok, Val))
1918 return Val;
1919
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001920 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001921 .Case("PT_NULL", PT_NULL)
1922 .Case("PT_LOAD", PT_LOAD)
1923 .Case("PT_DYNAMIC", PT_DYNAMIC)
1924 .Case("PT_INTERP", PT_INTERP)
1925 .Case("PT_NOTE", PT_NOTE)
1926 .Case("PT_SHLIB", PT_SHLIB)
1927 .Case("PT_PHDR", PT_PHDR)
1928 .Case("PT_TLS", PT_TLS)
1929 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1930 .Case("PT_GNU_STACK", PT_GNU_STACK)
1931 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001932 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001933 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001934 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001935 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001936
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001937 if (Ret == (unsigned)-1) {
1938 setError("invalid program header type: " + Tok);
1939 return PT_NULL;
1940 }
1941 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001942}
1943
Rui Ueyama12450b22016-11-18 06:30:09 +00001944// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1945void ScriptParser::readAnonymousDeclaration() {
1946 // Read global symbols first. "global:" is default, so if there's
1947 // no label, we assume global symbols.
Rafael Espindola45242682017-02-03 13:24:01 +00001948 if (peek() != "local") {
1949 if (consume("global"))
1950 expect(":");
Peter Collingbourne904c5ed2017-02-13 18:31:12 +00001951 for (SymbolVersion V : readSymbols())
1952 Config->VersionScriptGlobals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001953 }
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001954 readLocals();
Rui Ueyama12450b22016-11-18 06:30:09 +00001955 expect("}");
1956 expect(";");
1957}
1958
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001959void ScriptParser::readLocals() {
Rafael Espindola45242682017-02-03 13:24:01 +00001960 if (!consume("local"))
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001961 return;
Rafael Espindola45242682017-02-03 13:24:01 +00001962 expect(":");
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001963 std::vector<SymbolVersion> Locals = readSymbols();
1964 for (SymbolVersion V : Locals) {
1965 if (V.Name == "*") {
1966 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1967 continue;
1968 }
1969 Config->VersionScriptLocals.push_back(V);
1970 }
1971}
1972
Rui Ueyama12450b22016-11-18 06:30:09 +00001973// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001974void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001975 // Identifiers start at 2 because 0 and 1 are reserved
1976 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001977 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001978 Config->VersionDefinitions.push_back({VerStr, VersionId});
1979
Rui Ueyama12450b22016-11-18 06:30:09 +00001980 // Read global symbols.
Rafael Espindola45242682017-02-03 13:24:01 +00001981 if (peek() != "local") {
1982 if (consume("global"))
1983 expect(":");
Rui Ueyama12450b22016-11-18 06:30:09 +00001984 Config->VersionDefinitions.back().Globals = readSymbols();
Rafael Espindola45242682017-02-03 13:24:01 +00001985 }
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001986 readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001987 expect("}");
1988
Rui Ueyama12450b22016-11-18 06:30:09 +00001989 // Each version may have a parent version. For example, "Ver2"
1990 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1991 // as a parent. This version hierarchy is, probably against your
1992 // instinct, purely for hint; the runtime doesn't care about it
1993 // at all. In LLD, we simply ignore it.
1994 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001995 skip();
George Rimar20b65982016-08-31 09:08:26 +00001996 expect(";");
1997}
1998
Rui Ueyama12450b22016-11-18 06:30:09 +00001999// Reads a list of symbols for a versions cript.
2000std::vector<SymbolVersion> ScriptParser::readSymbols() {
2001 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00002002 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002003 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00002004 for (SymbolVersion V : readVersionExtern())
2005 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002006 continue;
2007 }
George Rimare0fc2422016-11-16 17:59:10 +00002008
Dmitry Mikulinf3965c02017-02-07 19:50:47 +00002009 if (peek() == "}" || (peek() == "local" && peek(1) == ":") || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00002010 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002011 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00002012 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00002013 expect(";");
2014 }
Rui Ueyama12450b22016-11-18 06:30:09 +00002015 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00002016}
2017
Rui Ueyama12450b22016-11-18 06:30:09 +00002018// Reads an "extern C++" directive, e.g.,
2019// "extern "C++" { ns::*; "f(int, double)"; };"
2020std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002021 StringRef Tok = next();
2022 bool IsCXX = Tok == "\"C++\"";
2023 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002024 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002025 expect("{");
2026
Rui Ueyama12450b22016-11-18 06:30:09 +00002027 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002028 while (!Error && peek() != "}") {
2029 StringRef Tok = next();
2030 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002031 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002032 expect(";");
2033 }
2034
2035 expect("}");
2036 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00002037 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002038}
2039
Rui Ueyama24e626c2017-01-26 02:58:19 +00002040uint64_t ScriptParser::readMemoryAssignment(
2041 StringRef S1, StringRef S2, StringRef S3) {
2042 if (!(consume(S1) || consume(S2) || consume(S3))) {
2043 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2044 return 0;
2045 }
2046 expect("=");
2047
2048 // TODO: Fully support constant expressions.
2049 uint64_t Val;
2050 if (!readInteger(next(), Val))
2051 setError("nonconstant expression for "+ S1);
2052 return Val;
2053}
2054
2055// Parse the MEMORY command as specified in:
2056// https://sourceware.org/binutils/docs/ld/MEMORY.html
2057//
2058// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002059void ScriptParser::readMemory() {
2060 expect("{");
2061 while (!Error && !consume("}")) {
2062 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002063
Meador Ingeb8897442017-01-24 02:34:00 +00002064 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002065 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002066 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002067 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002068 expect(")");
2069 }
2070 expect(":");
2071
Rui Ueyama24e626c2017-01-26 02:58:19 +00002072 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002073 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002074 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002075
Meador Ingeb8897442017-01-24 02:34:00 +00002076 // Add the memory region to the region map (if it doesn't already exist).
2077 auto It = Opt.MemoryRegions.find(Name);
2078 if (It != Opt.MemoryRegions.end())
2079 setError("region '" + Name + "' already defined");
2080 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002081 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002082 }
2083}
2084
2085// This function parses the attributes used to match against section
2086// flags when placing output sections in a memory region. These flags
2087// are only used when an explicit memory region name is not used.
2088std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2089 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002090 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002091 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002092
2093 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002094 uint32_t Flag = 0;
2095 if (C == '!')
2096 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002097 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002098 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002099 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002100 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002101 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002102 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002103 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002104 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002105
Meador Ingeb8897442017-01-24 02:34:00 +00002106 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002107 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002108 else
2109 Flags |= Flag;
2110 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002111 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002112}
2113
Rui Ueyama07320e42016-04-20 20:13:41 +00002114void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002115 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002116}
2117
2118void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002119 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002120}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002121
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002122void elf::readDynamicList(MemoryBufferRef MB) {
2123 ScriptParser(MB).readDynamicList();
2124}
2125
Rui Ueyama07320e42016-04-20 20:13:41 +00002126template class elf::LinkerScript<ELF32LE>;
2127template class elf::LinkerScript<ELF32BE>;
2128template class elf::LinkerScript<ELF64LE>;
2129template class elf::LinkerScript<ELF64BE>;