blob: 4eca9dd45ab68f3e90f89811c5376287f960626b [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
Rui Ueyamaa34da932017-03-21 23:03:09 +000056LinkerScript *elf::Script;
57
Rafael Espindola72dc1952017-03-17 13:05:04 +000058uint64_t ExprValue::getValue() const {
59 if (Sec)
60 return Sec->getOffset(Val) + Sec->getOutputSection()->Addr;
61 return Val;
62}
63
Rafael Espindola7ba5f472017-03-17 14:55:36 +000064uint64_t ExprValue::getSecAddr() const {
65 if (Sec)
66 return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
67 return 0;
68}
69
70// Some operations only support one non absolute value. Move the
71// absolute one to the right hand side for convenience.
72static void moveAbsRight(ExprValue &A, ExprValue &B) {
Rafael Espindolaf2115f02017-03-17 13:45:36 +000073 if (A.isAbsolute())
74 std::swap(A, B);
Rafael Espindola5f08a1d2017-03-17 14:51:07 +000075 if (!B.isAbsolute())
76 error("At least one side of the expression must be absolute");
Rafael Espindola7ba5f472017-03-17 14:55:36 +000077}
78
79static ExprValue add(ExprValue A, ExprValue B) {
80 moveAbsRight(A, B);
Rafael Espindola72dc1952017-03-17 13:05:04 +000081 return {A.Sec, A.ForceAbsolute, A.Val + B.getValue()};
82}
83static ExprValue sub(ExprValue A, ExprValue B) {
84 return {A.Sec, A.Val - B.getValue()};
85}
86static ExprValue mul(ExprValue A, ExprValue B) {
87 return A.getValue() * B.getValue();
88}
89static ExprValue div(ExprValue A, ExprValue B) {
90 if (uint64_t BV = B.getValue())
91 return A.getValue() / BV;
92 error("division by zero");
93 return 0;
94}
95static ExprValue leftShift(ExprValue A, ExprValue B) {
96 return A.getValue() << B.getValue();
97}
98static ExprValue rightShift(ExprValue A, ExprValue B) {
99 return A.getValue() >> B.getValue();
100}
Rafael Espindola72dc1952017-03-17 13:05:04 +0000101static ExprValue bitAnd(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000102 moveAbsRight(A, B);
103 return {A.Sec, A.ForceAbsolute,
104 (A.getValue() & B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000105}
106static ExprValue bitOr(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000107 moveAbsRight(A, B);
108 return {A.Sec, A.ForceAbsolute,
109 (A.getValue() | B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000110}
111static ExprValue bitNot(ExprValue A) { return ~A.getValue(); }
112static ExprValue minus(ExprValue A) { return -A.getValue(); }
113
Meador Inge8f1f3c42017-01-09 18:36:57 +0000114template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000115 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +0000116 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000117 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
118 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
119 /*File*/ nullptr);
120 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000121 ExprValue Value = Cmd->Expression();
122 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
Rui Ueyama80474a22017-02-28 19:29:55 +0000123 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +0000124 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000125 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +0000126}
127
Rui Ueyama22375f22016-11-25 18:51:54 +0000128static bool isUnderSysroot(StringRef Path) {
129 if (Config->Sysroot == "")
130 return false;
131 for (; !Path.empty(); Path = sys::path::parent_path(Path))
132 if (sys::fs::equivalent(Config->Sysroot, Path))
133 return true;
134 return false;
135}
136
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000137OutputSection *LinkerScript::getOutputSection(const Twine &Loc,
138 StringRef Name) {
George Rimar851dc1e2017-03-14 10:15:53 +0000139 for (OutputSection *Sec : *OutputSections)
140 if (Sec->Name == Name)
141 return Sec;
142
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +0000143 static OutputSection Dummy("", 0, 0);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000144 if (ErrorOnMissingSection)
145 error(Loc + ": undefined section " + Name);
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +0000146 return &Dummy;
George Rimar851dc1e2017-03-14 10:15:53 +0000147}
148
George Rimard83ce1b2017-03-14 10:24:47 +0000149// This function is essentially the same as getOutputSection(Name)->Size,
150// but it won't print out an error message if a given section is not found.
151//
152// Linker script does not create an output section if its content is empty.
153// We want to allow SIZEOF(.foo) where .foo is a section which happened to
154// be empty. That is why this function is different from getOutputSection().
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000155uint64_t LinkerScript::getOutputSectionSize(StringRef Name) {
George Rimard83ce1b2017-03-14 10:24:47 +0000156 for (OutputSection *Sec : *OutputSections)
157 if (Sec->Name == Name)
158 return Sec->Size;
159 return 0;
160}
161
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000162void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000163 uint64_t Val = E().getValue();
Rafael Espindola679828f2017-02-17 16:26:13 +0000164 if (Val < Dot) {
165 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000166 error(Loc + ": unable to move location counter backward for: " +
167 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000168 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000169 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000170 }
171 Dot = Val;
172 // Update to location counter means update to section size.
173 if (InSec)
174 CurOutSec->Size = Dot - CurOutSec->Addr;
175}
176
George Rimarb2b70972017-02-07 10:23:28 +0000177// Sets value of a symbol. Two kinds of symbols are processed: synthetic
178// symbols, whose value is an offset from beginning of section and regular
179// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000180void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000181 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000182 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000183 return;
184 }
185
George Rimarb2b70972017-02-07 10:23:28 +0000186 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000187 return;
188
Rafael Espindola5616adf2017-03-08 22:36:28 +0000189 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000190 ExprValue V = Cmd->Expression();
191 if (V.isAbsolute()) {
192 Sym->Value = V.getValue();
193 } else {
194 Sym->Section = V.Sec;
195 if (Sym->Section->Flags & SHF_ALLOC)
196 Sym->Value = V.Val;
197 else
198 Sym->Value = V.getValue();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000199 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000200}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000201
George Rimara8dba482017-03-20 10:09:58 +0000202static SymbolBody *findSymbol(StringRef S) {
203 switch (Config->EKind) {
204 case ELF32LEKind:
205 return Symtab<ELF32LE>::X->find(S);
206 case ELF32BEKind:
207 return Symtab<ELF32BE>::X->find(S);
208 case ELF64LEKind:
209 return Symtab<ELF64LE>::X->find(S);
210 case ELF64BEKind:
211 return Symtab<ELF64BE>::X->find(S);
212 default:
213 llvm_unreachable("unknown Config->EKind");
214 }
215}
216
217static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
218 switch (Config->EKind) {
219 case ELF32LEKind:
220 return addRegular<ELF32LE>(Cmd);
221 case ELF32BEKind:
222 return addRegular<ELF32BE>(Cmd);
223 case ELF64LEKind:
224 return addRegular<ELF64LE>(Cmd);
225 case ELF64BEKind:
226 return addRegular<ELF64BE>(Cmd);
227 default:
228 llvm_unreachable("unknown Config->EKind");
229 }
230}
231
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000232void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000233 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000234 return;
235
236 // If a symbol was in PROVIDE(), we need to define it only when
237 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000238 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000239 if (Cmd->Provide && (!B || B->isDefined()))
240 return;
241
George Rimara8dba482017-03-20 10:09:58 +0000242 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000243}
244
George Rimar076fe152016-07-21 06:43:01 +0000245bool SymbolAssignment::classof(const BaseCommand *C) {
246 return C->Kind == AssignmentKind;
247}
248
249bool OutputSectionCommand::classof(const BaseCommand *C) {
250 return C->Kind == OutputSectionKind;
251}
252
George Rimareea31142016-07-21 14:26:59 +0000253bool InputSectionDescription::classof(const BaseCommand *C) {
254 return C->Kind == InputSectionKind;
255}
256
George Rimareefa7582016-08-04 09:29:31 +0000257bool AssertCommand::classof(const BaseCommand *C) {
258 return C->Kind == AssertKind;
259}
260
George Rimare38cbab2016-09-26 19:22:50 +0000261bool BytesDataCommand::classof(const BaseCommand *C) {
262 return C->Kind == BytesDataKind;
263}
264
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000265static StringRef basename(InputSectionBase *S) {
266 if (S->File)
267 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000268 return "";
269}
270
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000271bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000272 for (InputSectionDescription *ID : Opt.KeptSections)
273 if (ID->FilePat.match(basename(S)))
274 for (SectionPattern &P : ID->SectionPatterns)
275 if (P.SectionPat.match(S->Name))
276 return true;
George Rimareea31142016-07-21 14:26:59 +0000277 return false;
278}
279
Rafael Espindolac404d502017-02-23 02:32:18 +0000280static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
George Rimar575208c2016-09-15 19:15:12 +0000281 return getPriority(A->Name) < getPriority(B->Name);
282}
283
Rafael Espindolac404d502017-02-23 02:32:18 +0000284static bool compareName(InputSectionBase *A, InputSectionBase *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000285 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000286}
George Rimar350ece42016-08-03 08:35:59 +0000287
Rafael Espindolac404d502017-02-23 02:32:18 +0000288static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000289 // ">" is not a mistake. Larger alignments are placed before smaller
290 // alignments in order to reduce the amount of padding necessary.
291 // This is compatible with GNU.
292 return A->Alignment > B->Alignment;
293}
George Rimar350ece42016-08-03 08:35:59 +0000294
Rafael Espindolac404d502017-02-23 02:32:18 +0000295static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000296getComparator(SortSectionPolicy K) {
297 switch (K) {
298 case SortSectionPolicy::Alignment:
299 return compareAlignment;
300 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000301 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000302 case SortSectionPolicy::Priority:
303 return comparePriority;
304 default:
305 llvm_unreachable("unknown sort policy");
306 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000307}
George Rimar0702c4e2016-07-29 15:32:46 +0000308
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000309static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000310 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000311 if (Kind == ConstraintKind::NoConstraint)
312 return true;
Rafael Espindolac404d502017-02-23 02:32:18 +0000313 bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000314 auto *Sec = static_cast<InputSectionBase *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000315 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000316 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000317 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
318 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000319}
320
Rafael Espindolac404d502017-02-23 02:32:18 +0000321static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000322 SortSectionPolicy K) {
323 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000324 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000325}
326
Rafael Espindolad3190792016-09-16 15:10:23 +0000327// Compute and remember which sections the InputSectionDescription matches.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000328void LinkerScript::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000329 // Collects all sections that satisfy constraints of I
330 // and attach them to I.
331 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000332 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000333
Rui Ueyama536a2672017-02-27 02:32:08 +0000334 for (InputSectionBase *S : InputSections) {
Rafael Espindola3773bca2017-02-17 19:37:30 +0000335 if (S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000336 continue;
Rafael Espindola908a3d32017-02-16 14:36:09 +0000337 // For -emit-relocs we have to ignore entries like
338 // .rela.dyn : { *(.rela.data) }
339 // which are common because they are in the default bfd script.
340 if (S->Type == SHT_REL || S->Type == SHT_RELA)
341 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000342
Rui Ueyamae0be2902016-11-21 02:10:12 +0000343 StringRef Filename = basename(S);
344 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
345 continue;
346 if (!Pat.SectionPat.match(S->Name))
347 continue;
348 I->Sections.push_back(S);
349 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000350 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000351
George Rimar07171f22016-09-21 15:56:44 +0000352 // Sort sections as instructed by SORT-family commands and --sort-section
353 // option. Because SORT-family commands can be nested at most two depth
354 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
355 // line option is respected even if a SORT command is given, the exact
356 // behavior we have here is a bit complicated. Here are the rules.
357 //
358 // 1. If two SORT commands are given, --sort-section is ignored.
359 // 2. If one SORT command is given, and if it is not SORT_NONE,
360 // --sort-section is handled as an inner SORT command.
361 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
362 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindolac404d502017-02-23 02:32:18 +0000363 InputSectionBase **Begin = I->Sections.data() + SizeBefore;
364 InputSectionBase **End = I->Sections.data() + I->Sections.size();
George Rimar07171f22016-09-21 15:56:44 +0000365 if (Pat.SortOuter != SortSectionPolicy::None) {
366 if (Pat.SortInner == SortSectionPolicy::Default)
367 sortSections(Begin, End, Config->SortSection);
368 else
369 sortSections(Begin, End, Pat.SortInner);
370 sortSections(Begin, End, Pat.SortOuter);
371 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000372 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000373}
374
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000375void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000376 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000377 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000378 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000379 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000380 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000381 }
382}
383
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000384std::vector<InputSectionBase *>
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000385LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000386 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000387
George Rimar06ae6832016-08-12 09:07:57 +0000388 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000389 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
390 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000391 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000392 computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000393 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000394 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000395 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000396
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000397 return Ret;
398}
399
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000400void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000401 // A symbol can be assigned before any section is mentioned in the linker
402 // script. In an DSO, the symbol values are addresses, so the only important
403 // section values are:
404 // * SHN_UNDEF
405 // * SHN_ABS
406 // * Any value meaning a regular section.
407 // To handle that, create a dummy aether section that fills the void before
408 // the linker scripts switches to another section. It has an index of one
409 // which will map to whatever the first actual section is.
410 Aether = make<OutputSection>("", 0, SHF_ALLOC);
411 Aether->SectionIndex = 1;
412 CurOutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000413 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000414
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000415 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
416 auto Iter = Opt.Commands.begin() + I;
417 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000418
419 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000420 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000421 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000422 continue;
423 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000424
Eugene Leviantceabe802016-08-11 07:56:43 +0000425 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000426 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000427
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000428 // The output section name `/DISCARD/' is special.
429 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000430 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000431 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000432 continue;
433 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000434
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000435 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
436 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
437 // sections satisfy a given constraint. If not, a directive is handled
438 // as if it wasn't present from the beginning.
439 //
440 // Because we'll iterate over Commands many more times, the easiest
441 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000442 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000443 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000444 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000445 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000446 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000447 continue;
448 }
449
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000450 // A directive may contain symbol definitions like this:
451 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000452 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
453 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000454 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000455
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000456 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
457 // is given, input sections are aligned to that value, whether the
458 // given value is larger or smaller than the original section alignment.
459 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000460 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000461 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000462 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000463 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000464
465 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000466 for (InputSectionBase *S : V)
George Rimare21c3af2017-03-14 09:30:25 +0000467 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000468 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000469 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000470 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000471}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000472
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000473// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000474void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000475 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000476 if (S->Live && !S->OutSec)
George Rimare21c3af2017-03-14 09:30:25 +0000477 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000478}
479
George Rimarf7f0d082017-03-14 11:23:33 +0000480static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000481 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000482}
483
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000484void LinkerScript::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000485 if (!AlreadyOutputIS.insert(S).second)
486 return;
George Rimarf7f0d082017-03-14 11:23:33 +0000487 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000488
George Rimar0c1c8082017-03-14 10:00:19 +0000489 uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000490 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000491 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000492 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000493
494 // Update output section size after adding each section. This is so that
495 // SIZEOF works correctly in the case below:
496 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000497 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000498
Meador Ingeb8897442017-01-24 02:34:00 +0000499 // If there is a memory region associated with this input section, then
500 // place the section in that region and update the region index.
501 if (CurMemRegion) {
502 CurMemRegion->Offset += CurOutSec->Size;
503 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
504 if (CurSize > CurMemRegion->Length) {
505 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
506 error("section '" + CurOutSec->Name + "' will not fit in region '" +
507 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
508 " bytes");
509 }
510 }
511
Rafael Espindola7252ae52016-09-22 12:00:08 +0000512 if (IsTbss)
513 ThreadBssOffset = Pos - Dot;
514 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000515 Dot = Pos;
516}
517
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000518void LinkerScript::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000519 assert(CurOutSec);
520 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000521 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000522 for (InputSection *I : CurOutSec->Sections)
523 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000524}
525
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000526void LinkerScript::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000527 if (CurOutSec == Sec)
528 return;
529 if (AlreadyOutputOS.count(Sec))
530 return;
531
Rafael Espindolad3190792016-09-16 15:10:23 +0000532 CurOutSec = Sec;
533
Rafael Espindola37707632017-03-07 14:55:52 +0000534 Dot = alignTo(Dot, CurOutSec->Alignment);
George Rimarf7f0d082017-03-14 11:23:33 +0000535 CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000536
537 // If neither AT nor AT> is specified for an allocatable section, the linker
538 // will set the LMA such that the difference between VMA and LMA for the
539 // section is the same as the preceding output section in the same region
540 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000541 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000542 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000543}
544
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000545void LinkerScript::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000546 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000547 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000548 assignSymbol(AssignCmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000549 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000550 }
George Rimare38cbab2016-09-26 19:22:50 +0000551
552 // Handle BYTE(), SHORT(), LONG(), or QUAD().
553 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000554 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000555 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000556 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000557 return;
558 }
559
Meador Ingeb2d99d62016-11-22 18:01:50 +0000560 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000561 AssertCmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000562 return;
563 }
564
George Rimare38cbab2016-09-26 19:22:50 +0000565 // It handles single input section description command,
566 // calculates and assigns the offsets for each section and also
567 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000568 auto &ICmd = cast<InputSectionDescription>(Base);
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000569 for (InputSectionBase *IB : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000570 // We tentatively added all synthetic sections at the beginning and removed
571 // empty ones afterwards (because there is no way to know whether they were
572 // going be empty or not other than actually running linker scripts.)
573 // We need to ignore remains of empty sections.
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000574 if (auto *Sec = dyn_cast<SyntheticSection>(IB))
George Rimar3fb5a6d2016-11-29 16:05:27 +0000575 if (Sec->empty())
576 continue;
577
George Rimar78ef6452017-02-21 15:46:43 +0000578 if (!IB->Live)
579 continue;
Rafael Espindolabedccb5e2017-03-01 14:21:31 +0000580 assert(CurOutSec == IB->OutSec || AlreadyOutputOS.count(IB->OutSec));
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000581 output(cast<InputSection>(IB));
Eugene Leviantceabe802016-08-11 07:56:43 +0000582 }
583}
584
Rafael Espindola24e6f362017-02-24 15:07:30 +0000585static OutputSection *
586findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000587 auto End = Sections.end();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000588 auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
Rafael Espindola2b074552017-02-03 22:27:05 +0000589 auto I = std::find_if(Sections.begin(), End, HasName);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000590 std::vector<OutputSection *> Ret;
Rafael Espindola2b074552017-02-03 22:27:05 +0000591 if (I == End)
592 return nullptr;
593 assert(std::find_if(I + 1, End, HasName) == End);
594 return *I;
George Rimar8f66df92016-08-12 20:38:20 +0000595}
596
Meador Ingeb8897442017-01-24 02:34:00 +0000597// This function searches for a memory region to place the given output
598// section in. If found, a pointer to the appropriate memory region is
599// returned. Otherwise, a nullptr is returned.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000600MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd,
601 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000602 // If a memory region name was specified in the output section command,
603 // then try to find that region first.
604 if (!Cmd->MemoryRegionName.empty()) {
605 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
606 if (It != Opt.MemoryRegions.end())
607 return &It->second;
608 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
609 return nullptr;
610 }
611
612 // The memory region name is empty, thus a suitable region must be
613 // searched for in the region map. If the region map is empty, just
614 // return. Note that this check doesn't happen at the very beginning
615 // so that uses of undeclared regions can be caught.
616 if (!Opt.MemoryRegions.size())
617 return nullptr;
618
619 // See if a region can be found by matching section flags.
620 for (auto &MRI : Opt.MemoryRegions) {
621 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000622 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000623 return &MR;
624 }
625
626 // Otherwise, no suitable region was found.
627 if (Sec->Flags & SHF_ALLOC)
628 error("no memory region specified for section '" + Sec->Name + "'");
629 return nullptr;
630}
631
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000632// This function assigns offsets to input sections and an output section
633// for a single sections command (e.g. ".text { *(.text); }").
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000634void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar23e6a022017-03-14 11:31:28 +0000635 OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000636 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000637 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000638
Rafael Espindola679828f2017-02-17 16:26:13 +0000639 if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000640 setDot(Cmd->AddrExpr, Cmd->Location);
Rafael Espindola679828f2017-02-17 16:26:13 +0000641
Eugene Leviant5784e962017-03-14 08:57:09 +0000642 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000643 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000644 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000645 }
646
Petr Hosek165088a2017-02-07 23:42:31 +0000647 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
648 if (Cmd->AlignExpr)
Rafael Espindola72dc1952017-03-17 13:05:04 +0000649 Sec->updateAlignment(Cmd->AlignExpr().getValue());
Petr Hosek165088a2017-02-07 23:42:31 +0000650
Meador Ingeb8897442017-01-24 02:34:00 +0000651 // Try and find an appropriate memory region to assign offsets in.
652 CurMemRegion = findMemoryRegion(Cmd, Sec);
653 if (CurMemRegion)
654 Dot = CurMemRegion->Offset;
655 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000656
Rafael Espindolad3190792016-09-16 15:10:23 +0000657 // Find the last section output location. We will output orphan sections
658 // there so that end symbols point to the correct location.
659 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
660 [](const std::unique_ptr<BaseCommand> &Cmd) {
661 return !isa<SymbolAssignment>(*Cmd);
662 })
663 .base();
664 for (auto I = Cmd->Commands.begin(); I != E; ++I)
665 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000666 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000667 std::for_each(E, Cmd->Commands.end(),
668 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000669}
670
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000671void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000672 // It is common practice to use very generic linker scripts. So for any
673 // given run some of the output sections in the script will be empty.
674 // We could create corresponding empty output sections, but that would
675 // clutter the output.
676 // We instead remove trivially empty sections. The bfd linker seems even
677 // more aggressive at removing them.
678 auto Pos = std::remove_if(
679 Opt.Commands.begin(), Opt.Commands.end(),
680 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000681 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
George Rimar23e6a022017-03-14 11:31:28 +0000682 return !findSection(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000683 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000684 });
685 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000686}
687
Rafael Espindola6a537372016-11-14 14:33:49 +0000688static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
689 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
690 if (!isa<InputSectionDescription>(*I))
691 return false;
692 return true;
693}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000694
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000695void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000696 // If the output section contains only symbol assignments, create a
697 // corresponding output section. The bfd linker seems to only create them if
698 // '.' is assigned to, but creating these section should not have any bad
699 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000700 uint64_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000701 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000702 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
703 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
704 if (!Cmd)
705 continue;
George Rimar23e6a022017-03-14 11:31:28 +0000706 if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000707 Flags = Sec->Flags;
708 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000709 continue;
710 }
711
Rafael Espindola6a537372016-11-14 14:33:49 +0000712 if (isAllSectionDescription(*Cmd))
713 continue;
714
Rafael Espindola24e6f362017-02-24 15:07:30 +0000715 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000716 OutputSections->push_back(OutSec);
717 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000718}
719
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000720void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000721 placeOrphanSections();
722
723 // If output section command doesn't specify any segments,
724 // and we haven't previously assigned any section to segment,
725 // then we simply assign section to the very first load segment.
726 // Below is an example of such linker script:
727 // PHDRS { seg PT_LOAD; }
728 // SECTIONS { .aaa : { *(.aaa) } }
729 std::vector<StringRef> DefPhdrs;
730 auto FirstPtLoad =
731 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
732 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
733 if (FirstPtLoad != Opt.PhdrsCommands.end())
734 DefPhdrs.push_back(FirstPtLoad->Name);
735
736 // Walk the commands and propagate the program headers to commands that don't
737 // explicitly specify them.
738 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
739 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
740 if (!Cmd)
741 continue;
742 if (Cmd->Phdrs.empty())
743 Cmd->Phdrs = DefPhdrs;
744 else
745 DefPhdrs = Cmd->Phdrs;
746 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000747
748 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000749}
750
Rafael Espindola15c57952016-09-22 18:05:49 +0000751// When placing orphan sections, we want to place them after symbol assignments
752// so that an orphan after
753// begin_foo = .;
754// foo : { *(foo) }
755// end_foo = .;
756// doesn't break the intended meaning of the begin/end symbols.
757// We don't want to go over sections since Writer<ELFT>::sortSections is the
758// one in charge of deciding the order of the sections.
759// We don't want to go over alignments, since doing so in
760// rx_sec : { *(rx_sec) }
761// . = ALIGN(0x1000);
762// /* The RW PT_LOAD starts here*/
763// rw_sec : { *(rw_sec) }
764// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000765static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000766 if (isa<OutputSectionCommand>(Cmd))
767 return false;
768 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
769 if (!Assign)
770 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000771 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000772}
773
Rui Ueyama6697ec22017-02-02 23:26:12 +0000774// Orphan sections are sections present in the input files which are
775// not explicitly placed into the output file by the linker script.
776//
777// When the control reaches this function, Opt.Commands contains
778// output section commands for non-orphan sections only. This function
Rui Ueyama81cb7102017-03-24 00:15:57 +0000779// adds new elements for orphan sections so that all sections are
780// explicitly handled by Opt.Commands.
Rui Ueyama6697ec22017-02-02 23:26:12 +0000781//
782// Writer<ELFT>::sortSections has already sorted output sections.
783// What we need to do is to scan OutputSections vector and
784// Opt.Commands in parallel to find orphan sections. If there is an
785// output section that doesn't have a corresponding entry in
786// Opt.Commands, we will insert a new entry to Opt.Commands.
787//
788// There is some ambiguity as to where exactly a new entry should be
789// inserted, because Opt.Commands contains not only output section
Rui Ueyama81cb7102017-03-24 00:15:57 +0000790// commands but also other types of commands such as symbol assignment
Rui Ueyama6697ec22017-02-02 23:26:12 +0000791// expressions. There's no correct answer here due to the lack of the
792// formal specification of the linker script. We use heuristics to
793// determine whether a new output command should be added before or
794// after another commands. For the details, look at shouldSkip
795// function.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000796void LinkerScript::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000797 // The OutputSections are already in the correct order.
798 // This loops creates or moves commands as needed so that they are in the
799 // correct order.
800 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000801
802 // As a horrible special case, skip the first . assignment if it is before any
803 // section. We do this because it is common to set a load address by starting
804 // the script with ". = 0xabcd" and the expectation is that every section is
805 // after that.
806 auto FirstSectionOrDotAssignment =
807 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
808 [](const std::unique_ptr<BaseCommand> &Cmd) {
809 if (isa<OutputSectionCommand>(*Cmd))
810 return true;
811 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
812 if (!Assign)
813 return false;
814 return Assign->Name == ".";
815 });
816 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
817 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
818 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
819 ++CmdIndex;
820 }
821
Rafael Espindola24e6f362017-02-24 15:07:30 +0000822 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000823 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000824
825 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000826 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000827 auto CmdIter = Opt.Commands.begin() + CmdIndex;
828 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000829 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000830 ++CmdIter;
831 ++CmdIndex;
832 }
833
834 auto Pos =
835 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
836 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
837 return Cmd && Cmd->Name == Name;
838 });
839 if (Pos == E) {
840 Opt.Commands.insert(CmdIter,
841 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000842 ++CmdIndex;
843 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000844 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000845
846 // Continue from where we found it.
847 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000848 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000849}
850
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000851void LinkerScript::processNonSectionCommands() {
Petr Hosek02ad5162017-03-15 03:33:23 +0000852 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
853 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
854 assignSymbol(Cmd);
855 else if (auto *Cmd = dyn_cast<AssertCommand>(Base.get()))
856 Cmd->Expression();
857 }
858}
859
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000860void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000861 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000862 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000863 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000864 switchTo(Aether);
865
George Rimar076fe152016-07-21 06:43:01 +0000866 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
867 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000868 assignSymbol(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000869 continue;
870 }
871
George Rimareefa7582016-08-04 09:29:31 +0000872 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000873 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000874 continue;
875 }
876
George Rimar076fe152016-07-21 06:43:01 +0000877 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000878 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000879 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000880
George Rimar0c1c8082017-03-14 10:00:19 +0000881 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000882 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000883 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000884 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000885 else
886 Sec->Addr = 0;
887 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000888
George Rimar2d262102017-03-14 09:03:53 +0000889 allocateHeaders(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000890}
891
Rui Ueyama464daad2016-08-22 04:55:20 +0000892// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000893std::vector<PhdrEntry> LinkerScript::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000894 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000895
Rui Ueyama464daad2016-08-22 04:55:20 +0000896 // Process PHDRS and FILEHDR keywords because they are not
897 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000898 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000899 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000900 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000901
902 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000903 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000904 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000905 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000906
907 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000908 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000909 Phdr.HasLMA = true;
910 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000911 }
912
Rui Ueyama464daad2016-08-22 04:55:20 +0000913 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000914 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000915 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000916 break;
917
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000918 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000919 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000920 Ret[Id].add(Sec);
921 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000922 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000923 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000924 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000925 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000926}
927
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000928bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000929 // Ignore .interp section in case we have PHDRS specification
930 // and PT_INTERP isn't listed.
931 return !Opt.PhdrsCommands.empty() &&
932 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
933 return Cmd.Type == PT_INTERP;
934 }) == Opt.PhdrsCommands.end();
935}
936
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000937uint32_t LinkerScript::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000938 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
939 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
940 if (Cmd->Name == Name)
941 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000942 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000943}
944
George Rimare38cbab2016-09-26 19:22:50 +0000945static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
George Rimare38cbab2016-09-26 19:22:50 +0000946 switch (Size) {
947 case 1:
948 *Buf = (uint8_t)Data;
949 break;
950 case 2:
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000951 write16(Buf, Data, Config->Endianness);
George Rimare38cbab2016-09-26 19:22:50 +0000952 break;
953 case 4:
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000954 write32(Buf, Data, Config->Endianness);
George Rimare38cbab2016-09-26 19:22:50 +0000955 break;
956 case 8:
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000957 write64(Buf, Data, Config->Endianness);
George Rimare38cbab2016-09-26 19:22:50 +0000958 break;
959 default:
960 llvm_unreachable("unsupported Size argument");
961 }
962}
963
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000964void LinkerScript::writeDataBytes(StringRef Name, uint8_t *Buf) {
George Rimare38cbab2016-09-26 19:22:50 +0000965 int I = getSectionIndex(Name);
966 if (I == INT_MAX)
967 return;
968
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000969 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
970 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
971 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
George Rimara8dba482017-03-20 10:09:58 +0000972 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000973}
974
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000975bool LinkerScript::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000976 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
977 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000978 if (Cmd->LMAExpr && Cmd->Name == Name)
979 return true;
980 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000981}
982
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000983// Returns the index of the given section name in linker script
984// SECTIONS commands. Sections are laid out as the same order as they
985// were in the script. If a given name did not appear in the script,
986// it returns INT_MAX, so that it will be laid out at end of file.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000987int LinkerScript::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000988 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
989 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000990 if (Cmd->Name == Name)
991 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000992 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000993}
994
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000995ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000996 if (S == ".")
Rafael Espindola72dc1952017-03-17 13:05:04 +0000997 return {CurOutSec, Dot - CurOutSec->Addr};
George Rimara8dba482017-03-20 10:09:58 +0000998 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000999 if (auto *D = dyn_cast<DefinedRegular>(B))
1000 return {D->Section, D->Value};
Petr Hosek30f16b22017-03-23 03:52:34 +00001001 if (auto *C = dyn_cast<DefinedCommon>(B))
1002 return {InX::Common, C->Offset};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001003 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001004 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001005 return 0;
1006}
1007
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001008bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +00001009
Eugene Leviantbbe38602016-07-19 09:25:43 +00001010// Returns indices of ELF headers containing specific section, identified
1011// by Name. Each index is a zero based number of ELF header listed within
1012// PHDRS {} script block.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001013std::vector<size_t> LinkerScript::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +00001014 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1015 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001016 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +00001017 continue;
1018
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001019 std::vector<size_t> Ret;
1020 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001021 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001022 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001023 }
George Rimar31d842f2016-07-20 16:43:03 +00001024 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001025}
1026
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001027size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001028 size_t I = 0;
1029 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1030 if (Cmd.Name == PhdrName)
1031 return I;
1032 ++I;
1033 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001034 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001035 return 0;
1036}
1037
Rui Ueyama794366a2017-02-14 04:47:05 +00001038class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001039 typedef void (ScriptParser::*Handler)();
1040
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001041public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001042 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001043 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001044 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001045
George Rimar20b65982016-08-31 09:08:26 +00001046 void readLinkerScript();
1047 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001048 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001049
1050private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001051 void addFile(StringRef Path);
1052
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001053 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001054 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001055 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001056 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001057 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001058 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001059 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001060 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001061 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001062 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001063 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001064 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001065 void readVersion();
1066 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001067
Rui Ueyama113cdec2016-07-24 23:05:57 +00001068 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001069 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001070 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001071 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001072 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001073 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001074 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001075 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001076 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001077 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001078 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001079 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001080 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001081 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001082 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001083 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001084
Rui Ueyama24e626c2017-01-26 02:58:19 +00001085 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1086 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1087
Rui Ueyama708019c2016-07-24 18:19:40 +00001088 Expr readExpr();
1089 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001090 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001091 Expr readPrimary();
1092 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001093 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001094
George Rimar20b65982016-08-31 09:08:26 +00001095 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001096 std::vector<SymbolVersion> readVersionExtern();
1097 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001098 void readVersionDeclaration(StringRef VerStr);
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001099
1100 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1101 readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001102
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001103 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001104};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001105
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001106void ScriptParser::readDynamicList() {
1107 expect("{");
1108 readAnonymousDeclaration();
1109 if (!atEOF())
1110 setError("EOF expected, but got " + next());
1111}
1112
George Rimar20b65982016-08-31 09:08:26 +00001113void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001114 readVersionScriptCommand();
1115 if (!atEOF())
1116 setError("EOF expected, but got " + next());
1117}
1118
1119void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001120 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001121 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001122 return;
1123 }
1124
Rui Ueyama95769b42016-08-31 20:03:54 +00001125 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001126 StringRef VerStr = next();
1127 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001128 setError("anonymous version definition is used in "
1129 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001130 return;
1131 }
1132 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001133 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001134 }
1135}
1136
Rui Ueyama95769b42016-08-31 20:03:54 +00001137void ScriptParser::readVersion() {
1138 expect("{");
1139 readVersionScriptCommand();
1140 expect("}");
1141}
1142
George Rimar20b65982016-08-31 09:08:26 +00001143void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001144 while (!atEOF()) {
1145 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001146 if (Tok == ";")
1147 continue;
1148
Eugene Leviant20d03192016-09-16 15:30:47 +00001149 if (Tok == "ASSERT") {
Rui Ueyamaa34da932017-03-21 23:03:09 +00001150 Script->Opt.Commands.emplace_back(new AssertCommand(readAssert()));
Eugene Leviant20d03192016-09-16 15:30:47 +00001151 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001152 readEntry();
1153 } else if (Tok == "EXTERN") {
1154 readExtern();
1155 } else if (Tok == "GROUP" || Tok == "INPUT") {
1156 readGroup();
1157 } else if (Tok == "INCLUDE") {
1158 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001159 } else if (Tok == "MEMORY") {
1160 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001161 } else if (Tok == "OUTPUT") {
1162 readOutput();
1163 } else if (Tok == "OUTPUT_ARCH") {
1164 readOutputArch();
1165 } else if (Tok == "OUTPUT_FORMAT") {
1166 readOutputFormat();
1167 } else if (Tok == "PHDRS") {
1168 readPhdrs();
1169 } else if (Tok == "SEARCH_DIR") {
1170 readSearchDir();
1171 } else if (Tok == "SECTIONS") {
1172 readSections();
1173 } else if (Tok == "VERSION") {
1174 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001175 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Rui Ueyamaa34da932017-03-21 23:03:09 +00001176 Script->Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001177 } else {
George Rimar57610422016-03-11 14:43:02 +00001178 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001179 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001180 }
1181}
1182
Rui Ueyama717677a2016-02-11 21:17:59 +00001183void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001184 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001185 SmallString<128> PathData;
1186 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001187 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001188 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001189 return;
1190 }
1191 }
1192
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001193 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001194 Driver->addFile(S);
1195 } else if (S.startswith("=")) {
1196 if (Config->Sysroot.empty())
1197 Driver->addFile(S.substr(1));
1198 else
1199 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1200 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001201 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001202 } else if (sys::fs::exists(S)) {
1203 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001204 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001205 if (Optional<std::string> Path = findFromSearchPaths(S))
1206 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001207 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001208 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001209 }
1210}
1211
Rui Ueyama717677a2016-02-11 21:17:59 +00001212void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001213 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001214 bool Orig = Config->AsNeeded;
1215 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001216 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001217 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001218 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001219}
1220
Rui Ueyama717677a2016-02-11 21:17:59 +00001221void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001222 // -e <symbol> takes predecence over ENTRY(<symbol>).
1223 expect("(");
1224 StringRef Tok = next();
1225 if (Config->Entry.empty())
1226 Config->Entry = Tok;
1227 expect(")");
1228}
1229
Rui Ueyama717677a2016-02-11 21:17:59 +00001230void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001231 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001232 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001233 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001234}
1235
Rui Ueyama717677a2016-02-11 21:17:59 +00001236void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001237 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001238 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001239 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001240 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001241 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001242 else
George Rimarcd574a52016-09-09 14:35:36 +00001243 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001244 }
1245}
1246
Rui Ueyama717677a2016-02-11 21:17:59 +00001247void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001248 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001249
George Rimard4500652016-12-21 09:42:25 +00001250 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1251 // The file will be searched for in the current directory, and in any
1252 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001253 if (sys::fs::exists(Tok)) {
1254 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1255 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001256 return;
1257 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001258 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1259 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1260 tokenize(*MB);
1261 return;
1262 }
1263 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001264}
1265
Rui Ueyama717677a2016-02-11 21:17:59 +00001266void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001267 // -o <file> takes predecence over OUTPUT(<file>).
1268 expect("(");
1269 StringRef Tok = next();
1270 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001271 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001272 expect(")");
1273}
1274
Rui Ueyama717677a2016-02-11 21:17:59 +00001275void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001276 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001277 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001278 while (!Error && !consume(")"))
1279 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001280}
1281
Rui Ueyama717677a2016-02-11 21:17:59 +00001282void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001283 // Error checking only for now.
1284 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001285 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001286 StringRef Tok = next();
1287 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001288 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001289 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001290 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001291 return;
1292 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001293 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001294 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001295 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001296 expect(")");
1297}
1298
Eugene Leviantbbe38602016-07-19 09:25:43 +00001299void ScriptParser::readPhdrs() {
1300 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001301 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001302 StringRef Tok = next();
Rui Ueyamaa34da932017-03-21 23:03:09 +00001303 Script->Opt.PhdrsCommands.push_back(
Eugene Leviant56b21c82016-09-09 09:46:16 +00001304 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Rui Ueyamaa34da932017-03-21 23:03:09 +00001305 PhdrsCommand &PhdrCmd = Script->Opt.PhdrsCommands.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001306
1307 PhdrCmd.Type = readPhdrType();
1308 do {
1309 Tok = next();
1310 if (Tok == ";")
1311 break;
1312 if (Tok == "FILEHDR")
1313 PhdrCmd.HasFilehdr = true;
1314 else if (Tok == "PHDRS")
1315 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001316 else if (Tok == "AT")
1317 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001318 else if (Tok == "FLAGS") {
1319 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001320 // Passing 0 for the value of dot is a bit of a hack. It means that
1321 // we accept expressions like ".|1".
Rafael Espindola72dc1952017-03-17 13:05:04 +00001322 PhdrCmd.Flags = readExpr()().getValue();
Eugene Leviant865bf862016-07-21 10:43:25 +00001323 expect(")");
1324 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001325 setError("unexpected header attribute: " + Tok);
1326 } while (!Error);
1327 }
1328}
1329
Rui Ueyama717677a2016-02-11 21:17:59 +00001330void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001331 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001332 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001333 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001334 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001335 expect(")");
1336}
1337
Rui Ueyama717677a2016-02-11 21:17:59 +00001338void ScriptParser::readSections() {
Rui Ueyamaa34da932017-03-21 23:03:09 +00001339 Script->Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001340 // -no-rosegment is used to avoid placing read only non-executable sections in
1341 // their own segment. We do the same if SECTIONS command is present in linker
1342 // script. See comment for computeFlags().
1343 Config->SingleRoRx = true;
1344
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001345 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001346 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001347 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001348 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001349 if (!Cmd) {
1350 if (Tok == "ASSERT")
1351 Cmd = new AssertCommand(readAssert());
1352 else
1353 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001354 }
Rui Ueyamaa34da932017-03-21 23:03:09 +00001355 Script->Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001356 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001357}
1358
Rui Ueyama708019c2016-07-24 18:19:40 +00001359static int precedence(StringRef Op) {
1360 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001361 .Cases("*", "/", 5)
1362 .Cases("+", "-", 4)
1363 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001364 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001365 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001366 .Default(-1);
1367}
1368
Eugene Leviantdb688452016-11-03 10:54:58 +00001369StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001370 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001371 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001372 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001373 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001374}
1375
George Rimarbe394db2016-09-16 20:21:55 +00001376SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001377 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001378 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001379 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001380 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001381 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001382 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001383 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001384 return SortSectionPolicy::None;
1385 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001386}
1387
George Rimar395281c2016-09-16 17:42:10 +00001388// Method reads a list of sequence of excluded files and section globs given in
1389// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1390// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001391// The semantics of that is next:
1392// * Include .foo.1 from every file.
1393// * Include .foo.2 from every file but a.o
1394// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001395std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1396 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001397 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001398 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001399 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001400 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001401 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001402 }
1403
George Rimar601e9892016-09-21 08:53:21 +00001404 std::vector<StringRef> V;
1405 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1406 V.push_back(next());
1407
1408 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001409 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001410 else
1411 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001412 }
George Rimar07171f22016-09-21 15:56:44 +00001413 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001414}
1415
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001416// Reads contents of "SECTIONS" directive. That directive contains a
1417// list of glob patterns for input sections. The grammar is as follows.
1418//
1419// <patterns> ::= <section-list>
1420// | <sort> "(" <section-list> ")"
1421// | <sort> "(" <sort> "(" <section-list> ")" ")"
1422//
1423// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1424// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1425//
1426// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001427InputSectionDescription *
1428ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001429 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001430 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001431 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001432 SortSectionPolicy Outer = readSortKind();
1433 SortSectionPolicy Inner = SortSectionPolicy::Default;
1434 std::vector<SectionPattern> V;
1435 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001436 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001437 Inner = readSortKind();
1438 if (Inner != SortSectionPolicy::Default) {
1439 expect("(");
1440 V = readInputSectionsList();
1441 expect(")");
1442 } else {
1443 V = readInputSectionsList();
1444 }
George Rimar350ece42016-08-03 08:35:59 +00001445 expect(")");
1446 } else {
George Rimar07171f22016-09-21 15:56:44 +00001447 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001448 }
George Rimar0702c4e2016-07-29 15:32:46 +00001449
George Rimar07171f22016-09-21 15:56:44 +00001450 for (SectionPattern &Pat : V) {
1451 Pat.SortInner = Inner;
1452 Pat.SortOuter = Outer;
1453 }
1454
1455 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1456 }
Rui Ueyama10416562016-08-04 02:03:27 +00001457 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001458}
1459
George Rimara2496cb2016-08-30 09:46:59 +00001460InputSectionDescription *
1461ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001462 // Input section wildcard can be surrounded by KEEP.
1463 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001464 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001465 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001466 StringRef FilePattern = next();
1467 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001468 expect(")");
Rui Ueyamaa34da932017-03-21 23:03:09 +00001469 Script->Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001470 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001471 }
George Rimara2496cb2016-08-30 09:46:59 +00001472 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001473}
1474
George Rimar03fc0102016-07-28 07:18:23 +00001475void ScriptParser::readSort() {
1476 expect("(");
1477 expect("CONSTRUCTORS");
1478 expect(")");
1479}
1480
George Rimareefa7582016-08-04 09:29:31 +00001481Expr ScriptParser::readAssert() {
1482 expect("(");
1483 Expr E = readExpr();
1484 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001485 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001486 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001487 return [=] {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001488 if (!E().getValue())
George Rimareefa7582016-08-04 09:29:31 +00001489 error(Msg);
George Rimara8dba482017-03-20 10:09:58 +00001490 return Script->getDot();
George Rimareefa7582016-08-04 09:29:31 +00001491 };
1492}
1493
Rui Ueyama25150e82016-09-06 17:46:43 +00001494// Reads a FILL(expr) command. We handle the FILL command as an
1495// alias for =fillexp section attribute, which is different from
1496// what GNU linkers do.
1497// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001498uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001499 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001500 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001501 expect(")");
1502 expect(";");
1503 return V;
1504}
1505
Rui Ueyama10416562016-08-04 02:03:27 +00001506OutputSectionCommand *
1507ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001508 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001509 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001510
1511 // Read an address expression.
1512 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1513 if (peek() != ":")
1514 Cmd->AddrExpr = readExpr();
1515
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001516 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001517
Rui Ueyama83043f22016-10-17 16:01:53 +00001518 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001519 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001520 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001521 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001522 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001523 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001524
Davide Italiano246f6812016-07-22 03:36:24 +00001525 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001526 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001527 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001528 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001529 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001530 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001531
Rui Ueyama83043f22016-10-17 16:01:53 +00001532 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001533 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001534 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001535 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001536 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001537 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001538 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001539 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001540 } else if (Tok == "ASSERT") {
1541 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1542 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001543 } else if (Tok == "CONSTRUCTORS") {
1544 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1545 // by name. This is for very old file formats such as ECOFF/XCOFF.
1546 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001547 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001548 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001549 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001550 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001551 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001552 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001553 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001554 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001555 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001556 }
Meador Ingeb8897442017-01-24 02:34:00 +00001557
1558 if (consume(">"))
1559 Cmd->MemoryRegionName = next();
1560
George Rimar076fe152016-07-21 06:43:01 +00001561 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001562
Rui Ueyama83043f22016-10-17 16:01:53 +00001563 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001564 Cmd->Filler = readOutputSectionFiller(next());
1565 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001566 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001567
George Rimar7185a1a2017-01-17 15:32:12 +00001568 // Consume optional comma following output section command.
1569 consume(",");
1570
Rui Ueyama10416562016-08-04 02:03:27 +00001571 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001572}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001573
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001574// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1575// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1576//
1577// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1578// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1579// as 32-bit big-endian values. We will do the same as ld.gold does
1580// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001581uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001582 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001583 if (!Tok.getAsInteger(0, V))
1584 return V;
1585 setError("invalid filler expression: " + Tok);
1586 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001587}
1588
Petr Hoseka35e39c2016-08-16 01:11:16 +00001589SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001590 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001591 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001592 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001593 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001594 expect(")");
1595 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001596 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001597}
1598
Rafael Espindolac96da112016-11-01 11:30:45 +00001599SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001600 SymbolAssignment *Cmd = nullptr;
1601 if (peek() == "=" || peek() == "+=") {
1602 Cmd = readAssignment(Tok);
1603 expect(";");
1604 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001605 Cmd = readProvideHidden(true, false);
1606 } else if (Tok == "HIDDEN") {
1607 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001608 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001609 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001610 }
1611 return Cmd;
1612}
1613
George Rimar30835ea2016-07-28 21:08:56 +00001614SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1615 StringRef Op = next();
1616 assert(Op == "=" || Op == "+=");
Petr Hosek02ad5162017-03-15 03:33:23 +00001617 Expr E = readExpr();
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001618 if (Op == "+=") {
1619 std::string Loc = getCurrentLocation();
George Rimara8dba482017-03-20 10:09:58 +00001620 E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001621 }
George Rimar2ee2d2d2017-02-21 14:50:38 +00001622 return new SymbolAssignment(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001623}
1624
1625// This is an operator-precedence parser to parse a linker
1626// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001627Expr ScriptParser::readExpr() {
1628 // Our lexer is context-aware. Set the in-expression bit so that
1629 // they apply different tokenization rules.
1630 bool Orig = InExpr;
1631 InExpr = true;
1632 Expr E = readExpr1(readPrimary(), 0);
1633 InExpr = Orig;
1634 return E;
1635}
George Rimar30835ea2016-07-28 21:08:56 +00001636
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001637static Expr combine(StringRef Op, Expr L, Expr R) {
1638 if (Op == "*")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001639 return [=] { return mul(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001640 if (Op == "/") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001641 return [=] { return div(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001642 }
1643 if (Op == "+")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001644 return [=] { return add(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001645 if (Op == "-")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001646 return [=] { return sub(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001647 if (Op == "<<")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001648 return [=] { return leftShift(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001649 if (Op == ">>")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001650 return [=] { return rightShift(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001651 if (Op == "<")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001652 return [=] { return L().getValue() < R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001653 if (Op == ">")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001654 return [=] { return L().getValue() > R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001655 if (Op == ">=")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001656 return [=] { return L().getValue() >= R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001657 if (Op == "<=")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001658 return [=] { return L().getValue() <= R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001659 if (Op == "==")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001660 return [=] { return L().getValue() == R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001661 if (Op == "!=")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001662 return [=] { return L().getValue() != R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001663 if (Op == "&")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001664 return [=] { return bitAnd(L(), R()); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001665 if (Op == "|")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001666 return [=] { return bitOr(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001667 llvm_unreachable("invalid operator");
1668}
1669
Rui Ueyama708019c2016-07-24 18:19:40 +00001670// This is a part of the operator-precedence parser. This function
1671// assumes that the remaining token stream starts with an operator.
1672Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1673 while (!atEOF() && !Error) {
1674 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001675 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001676 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001677 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001678 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001679 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001680 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001681 Expr Rhs = readPrimary();
1682
1683 // Evaluate the remaining part of the expression first if the
1684 // next operator has greater precedence than the previous one.
1685 // For example, if we have read "+" and "3", and if the next
1686 // operator is "*", then we'll evaluate 3 * ... part first.
1687 while (!atEOF()) {
1688 StringRef Op2 = peek();
1689 if (precedence(Op2) <= precedence(Op1))
1690 break;
1691 Rhs = readExpr1(Rhs, precedence(Op2));
1692 }
1693
1694 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001695 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001696 return Lhs;
1697}
1698
1699uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001700 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001701 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001702 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001703 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001704 error("unknown constant: " + S);
1705 return 0;
1706}
1707
Rui Ueyama626e0b02016-09-02 18:19:00 +00001708// Parses Tok as an integer. Returns true if successful.
1709// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1710// and decimal numbers. Decimal numbers may have "K" (kilo) or
1711// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001712static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001713 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001714 if (Tok.startswith("-")) {
1715 if (!readInteger(Tok.substr(1), Result))
1716 return false;
1717 Result = -Result;
1718 return true;
1719 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001720
1721 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001722 if (Tok.startswith_lower("0x"))
1723 return !Tok.substr(2).getAsInteger(16, Result);
1724 if (Tok.endswith_lower("H"))
1725 return !Tok.drop_back().getAsInteger(16, Result);
1726
Rui Ueyama46247b82016-11-18 06:49:07 +00001727 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001728 int Suffix = 1;
1729 if (Tok.endswith_lower("K")) {
1730 Suffix = 1024;
1731 Tok = Tok.drop_back();
1732 } else if (Tok.endswith_lower("M")) {
1733 Suffix = 1024 * 1024;
1734 Tok = Tok.drop_back();
1735 }
1736 if (Tok.getAsInteger(10, Result))
1737 return false;
1738 Result *= Suffix;
1739 return true;
1740}
1741
George Rimare38cbab2016-09-26 19:22:50 +00001742BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1743 int Size = StringSwitch<unsigned>(Tok)
1744 .Case("BYTE", 1)
1745 .Case("SHORT", 2)
1746 .Case("LONG", 4)
1747 .Case("QUAD", 8)
1748 .Default(-1);
1749 if (Size == -1)
1750 return nullptr;
1751
Meador Inge95c7d8d2016-12-08 23:21:30 +00001752 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001753}
1754
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001755StringRef ScriptParser::readParenLiteral() {
1756 expect("(");
1757 StringRef Tok = next();
1758 expect(")");
1759 return Tok;
1760}
1761
Rui Ueyama708019c2016-07-24 18:19:40 +00001762Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001763 if (peek() == "(")
1764 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001765
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001766 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001767 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001768
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001769 if (Tok == "~") {
1770 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001771 return [=] { return bitNot(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001772 }
1773 if (Tok == "-") {
1774 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001775 return [=] { return minus(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001776 }
1777
Rui Ueyama708019c2016-07-24 18:19:40 +00001778 // Built-in functions are parsed here.
1779 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
Petr Hosek02ad5162017-03-15 03:33:23 +00001780 if (Tok == "ABSOLUTE") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001781 Expr Inner = readParenExpr();
1782 return [=] {
1783 ExprValue I = Inner();
1784 I.ForceAbsolute = true;
1785 return I;
1786 };
Petr Hosek02ad5162017-03-15 03:33:23 +00001787 }
George Rimar96659df2016-08-30 09:54:01 +00001788 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001789 StringRef Name = readParenLiteral();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001790 return [=]() -> ExprValue {
George Rimara8dba482017-03-20 10:09:58 +00001791 return {Script->getOutputSection(Location, Name), 0};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001792 };
George Rimar96659df2016-08-30 09:54:01 +00001793 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001794 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001795 expect("(");
1796 Expr E = readExpr();
1797 if (consume(",")) {
1798 Expr E2 = readExpr();
1799 expect(")");
Rafael Espindola72dc1952017-03-17 13:05:04 +00001800 return [=] { return alignTo(E().getValue(), E2().getValue()); };
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001801 }
1802 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001803 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001804 }
Rui Ueyamafc161732017-03-21 21:49:16 +00001805 if (Tok == "ALIGNOF") {
1806 StringRef Name = readParenLiteral();
1807 return [=] { return Script->getOutputSection(Location, Name)->Alignment; };
1808 }
1809 if (Tok == "ASSERT")
1810 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001811 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001812 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001813 return [=] { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001814 }
1815 if (Tok == "DATA_SEGMENT_ALIGN") {
1816 expect("(");
1817 Expr E = readExpr();
1818 expect(",");
1819 readExpr();
1820 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001821 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001822 }
1823 if (Tok == "DATA_SEGMENT_END") {
1824 expect("(");
1825 expect(".");
1826 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001827 return [] { return Script->getDot(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001828 }
George Rimar276b4e62016-07-26 17:58:44 +00001829 if (Tok == "DATA_SEGMENT_RELRO_END") {
Rui Ueyamafc161732017-03-21 21:49:16 +00001830 // GNU linkers implements more complicated logic to handle
1831 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1832 // just align to the next page boundary for simplicity.
George Rimar276b4e62016-07-26 17:58:44 +00001833 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001834 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001835 expect(",");
1836 readExpr();
1837 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001838 return [] { return alignTo(Script->getDot(), Target->PageSize); };
George Rimar276b4e62016-07-26 17:58:44 +00001839 }
Rui Ueyamafc161732017-03-21 21:49:16 +00001840 if (Tok == "DEFINED") {
1841 StringRef Name = readParenLiteral();
1842 return [=] { return Script->isDefined(Name) ? 1 : 0; };
1843 }
1844 if (Tok == "LOADADDR") {
1845 StringRef Name = readParenLiteral();
1846 return [=] { return Script->getOutputSection(Location, Name)->getLMA(); };
1847 }
1848 if (Tok == "SEGMENT_START") {
1849 expect("(");
1850 skip();
1851 expect(",");
1852 Expr E = readExpr();
1853 expect(")");
1854 return [=] { return E(); };
1855 }
George Rimar9e694502016-07-29 16:18:47 +00001856 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001857 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001858 return [=] { return Script->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001859 }
George Rimare32a3592016-08-10 07:59:34 +00001860 if (Tok == "SIZEOF_HEADERS")
George Rimar78aa2702017-03-13 14:40:58 +00001861 return [=] { return elf::getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001862
George Rimar9f2f7ad2016-09-02 16:01:42 +00001863 // Tok is a literal number.
1864 uint64_t V;
1865 if (readInteger(Tok, V))
Rafael Espindola4595df92017-03-10 16:04:26 +00001866 return [=] { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001867
1868 // Tok is a symbol name.
Petr Hosek30f16b22017-03-23 03:52:34 +00001869 if (Tok != ".") {
1870 if (!isValidCIdentifier(Tok))
1871 setError("malformed number: " + Tok);
1872 Script->Opt.UndefinedSymbols.push_back(Tok);
1873 }
George Rimara8dba482017-03-20 10:09:58 +00001874 return [=] { return Script->getSymbolValue(Location, Tok); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001875}
1876
1877Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001878 Expr L = readExpr();
1879 expect(":");
1880 Expr R = readExpr();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001881 return [=] { return Cond().getValue() ? L() : R(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001882}
1883
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001884Expr ScriptParser::readParenExpr() {
1885 expect("(");
1886 Expr E = readExpr();
1887 expect(")");
1888 return E;
1889}
1890
Eugene Leviantbbe38602016-07-19 09:25:43 +00001891std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1892 std::vector<StringRef> Phdrs;
1893 while (!Error && peek().startswith(":")) {
1894 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001895 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001896 }
1897 return Phdrs;
1898}
1899
George Rimar95dd7182016-10-18 10:49:50 +00001900// Read a program header type name. The next token must be a
1901// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001902unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001903 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001904 uint64_t Val;
1905 if (readInteger(Tok, Val))
1906 return Val;
1907
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001908 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001909 .Case("PT_NULL", PT_NULL)
1910 .Case("PT_LOAD", PT_LOAD)
1911 .Case("PT_DYNAMIC", PT_DYNAMIC)
1912 .Case("PT_INTERP", PT_INTERP)
1913 .Case("PT_NOTE", PT_NOTE)
1914 .Case("PT_SHLIB", PT_SHLIB)
1915 .Case("PT_PHDR", PT_PHDR)
1916 .Case("PT_TLS", PT_TLS)
1917 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1918 .Case("PT_GNU_STACK", PT_GNU_STACK)
1919 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001920 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001921 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001922 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001923 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001924
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001925 if (Ret == (unsigned)-1) {
1926 setError("invalid program header type: " + Tok);
1927 return PT_NULL;
1928 }
1929 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001930}
1931
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001932// Reads an anonymous version declaration.
Rui Ueyama12450b22016-11-18 06:30:09 +00001933void ScriptParser::readAnonymousDeclaration() {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001934 std::vector<SymbolVersion> Locals;
1935 std::vector<SymbolVersion> Globals;
1936 std::tie(Locals, Globals) = readSymbols();
1937
1938 for (SymbolVersion V : Locals) {
1939 if (V.Name == "*")
1940 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1941 else
1942 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001943 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001944
1945 for (SymbolVersion V : Globals)
1946 Config->VersionScriptGlobals.push_back(V);
1947
Rui Ueyama12450b22016-11-18 06:30:09 +00001948 expect(";");
1949}
1950
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001951// Reads a non-anonymous version definition,
1952// e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001953void ScriptParser::readVersionDeclaration(StringRef VerStr) {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001954 // Read a symbol list.
1955 std::vector<SymbolVersion> Locals;
1956 std::vector<SymbolVersion> Globals;
1957 std::tie(Locals, Globals) = readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001958
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001959 for (SymbolVersion V : Locals) {
1960 if (V.Name == "*")
1961 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1962 else
1963 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001964 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001965
1966 // Create a new version definition and add that to the global symbols.
1967 VersionDefinition Ver;
1968 Ver.Name = VerStr;
1969 Ver.Globals = Globals;
1970
1971 // User-defined version number starts from 2 because 0 and 1 are
1972 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1973 Ver.Id = Config->VersionDefinitions.size() + 2;
1974 Config->VersionDefinitions.push_back(Ver);
George Rimar20b65982016-08-31 09:08:26 +00001975
Rui Ueyama12450b22016-11-18 06:30:09 +00001976 // Each version may have a parent version. For example, "Ver2"
1977 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1978 // as a parent. This version hierarchy is, probably against your
1979 // instinct, purely for hint; the runtime doesn't care about it
1980 // at all. In LLD, we simply ignore it.
1981 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001982 skip();
George Rimar20b65982016-08-31 09:08:26 +00001983 expect(";");
1984}
1985
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001986// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1987std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1988ScriptParser::readSymbols() {
1989 std::vector<SymbolVersion> Locals;
1990 std::vector<SymbolVersion> Globals;
1991 std::vector<SymbolVersion> *V = &Globals;
1992
1993 while (!Error) {
1994 if (consume("}"))
1995 break;
1996 if (consumeLabel("local")) {
1997 V = &Locals;
1998 continue;
1999 }
2000 if (consumeLabel("global")) {
2001 V = &Globals;
Rafael Espindola1ef90d22016-12-09 16:44:05 +00002002 continue;
2003 }
George Rimare0fc2422016-11-16 17:59:10 +00002004
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002005 if (consume("extern")) {
2006 std::vector<SymbolVersion> Ext = readVersionExtern();
2007 V->insert(V->end(), Ext.begin(), Ext.end());
2008 } else {
2009 StringRef Tok = next();
2010 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
2011 }
George Rimare0fc2422016-11-16 17:59:10 +00002012 expect(";");
2013 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002014 return {Locals, Globals};
George Rimare0fc2422016-11-16 17:59:10 +00002015}
2016
Rui Ueyama12450b22016-11-18 06:30:09 +00002017// Reads an "extern C++" directive, e.g.,
2018// "extern "C++" { ns::*; "f(int, double)"; };"
2019std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002020 StringRef Tok = next();
2021 bool IsCXX = Tok == "\"C++\"";
2022 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002023 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002024 expect("{");
2025
Rui Ueyama12450b22016-11-18 06:30:09 +00002026 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002027 while (!Error && peek() != "}") {
2028 StringRef Tok = next();
2029 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002030 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002031 expect(";");
2032 }
2033
2034 expect("}");
Rui Ueyama12450b22016-11-18 06:30:09 +00002035 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002036}
2037
George Rimar009833d2017-03-20 09:51:18 +00002038uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
2039 StringRef S3) {
Rui Ueyama24e626c2017-01-26 02:58:19 +00002040 if (!(consume(S1) || consume(S2) || consume(S3))) {
2041 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2042 return 0;
2043 }
2044 expect("=");
2045
2046 // TODO: Fully support constant expressions.
2047 uint64_t Val;
2048 if (!readInteger(next(), Val))
George Rimar009833d2017-03-20 09:51:18 +00002049 setError("nonconstant expression for " + S1);
Rui Ueyama24e626c2017-01-26 02:58:19 +00002050 return Val;
2051}
2052
2053// Parse the MEMORY command as specified in:
2054// https://sourceware.org/binutils/docs/ld/MEMORY.html
2055//
2056// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002057void ScriptParser::readMemory() {
2058 expect("{");
2059 while (!Error && !consume("}")) {
2060 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002061
Meador Ingeb8897442017-01-24 02:34:00 +00002062 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002063 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002064 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002065 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002066 expect(")");
2067 }
2068 expect(":");
2069
Rui Ueyama24e626c2017-01-26 02:58:19 +00002070 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002071 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002072 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002073
Meador Ingeb8897442017-01-24 02:34:00 +00002074 // Add the memory region to the region map (if it doesn't already exist).
Rui Ueyamaa34da932017-03-21 23:03:09 +00002075 auto It = Script->Opt.MemoryRegions.find(Name);
2076 if (It != Script->Opt.MemoryRegions.end())
Meador Ingeb8897442017-01-24 02:34:00 +00002077 setError("region '" + Name + "' already defined");
2078 else
Rui Ueyamaa34da932017-03-21 23:03:09 +00002079 Script->Opt.MemoryRegions[Name] = {Name, Origin, Length,
2080 Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002081 }
2082}
2083
2084// This function parses the attributes used to match against section
2085// flags when placing output sections in a memory region. These flags
2086// are only used when an explicit memory region name is not used.
2087std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2088 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002089 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002090 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002091
2092 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002093 uint32_t Flag = 0;
2094 if (C == '!')
2095 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002096 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002097 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002098 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002099 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002100 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002101 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002102 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002103 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002104
Meador Ingeb8897442017-01-24 02:34:00 +00002105 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002106 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002107 else
2108 Flags |= Flag;
2109 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002110 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002111}
2112
Rui Ueyama07320e42016-04-20 20:13:41 +00002113void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002114 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002115}
2116
2117void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002118 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002119}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002120
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002121void elf::readDynamicList(MemoryBufferRef MB) {
2122 ScriptParser(MB).readDynamicList();
2123}