blob: e2483a995fab42cd2a8b2e538220802cc07acf92 [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}
Rui Ueyama5f20b632017-04-05 00:43:05 +000083
Rafael Espindola72dc1952017-03-17 13:05:04 +000084static ExprValue sub(ExprValue A, ExprValue B) {
85 return {A.Sec, A.Val - B.getValue()};
86}
Rui Ueyama5f20b632017-04-05 00:43:05 +000087
Rafael Espindola72dc1952017-03-17 13:05:04 +000088static ExprValue mul(ExprValue A, ExprValue B) {
89 return A.getValue() * B.getValue();
90}
Rui Ueyama5f20b632017-04-05 00:43:05 +000091
Rafael Espindola72dc1952017-03-17 13:05:04 +000092static ExprValue div(ExprValue A, ExprValue B) {
93 if (uint64_t BV = B.getValue())
94 return A.getValue() / BV;
95 error("division by zero");
96 return 0;
97}
Rui Ueyama5f20b632017-04-05 00:43:05 +000098
Rafael Espindola72dc1952017-03-17 13:05:04 +000099static ExprValue leftShift(ExprValue A, ExprValue B) {
100 return A.getValue() << B.getValue();
101}
Rui Ueyama5f20b632017-04-05 00:43:05 +0000102
Rafael Espindola72dc1952017-03-17 13:05:04 +0000103static ExprValue rightShift(ExprValue A, ExprValue B) {
104 return A.getValue() >> B.getValue();
105}
Rui Ueyama5f20b632017-04-05 00:43:05 +0000106
Rafael Espindola72dc1952017-03-17 13:05:04 +0000107static ExprValue bitAnd(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000108 moveAbsRight(A, B);
109 return {A.Sec, A.ForceAbsolute,
110 (A.getValue() & B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000111}
Rui Ueyama5f20b632017-04-05 00:43:05 +0000112
Rafael Espindola72dc1952017-03-17 13:05:04 +0000113static ExprValue bitOr(ExprValue A, ExprValue B) {
Rafael Espindola7ba5f472017-03-17 14:55:36 +0000114 moveAbsRight(A, B);
115 return {A.Sec, A.ForceAbsolute,
116 (A.getValue() | B.getValue()) - A.getSecAddr()};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000117}
Rui Ueyama5f20b632017-04-05 00:43:05 +0000118
Rafael Espindola72dc1952017-03-17 13:05:04 +0000119static ExprValue bitNot(ExprValue A) { return ~A.getValue(); }
120static ExprValue minus(ExprValue A) { return -A.getValue(); }
121
Meador Inge8f1f3c42017-01-09 18:36:57 +0000122template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000123 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +0000124 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +0000125 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
126 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
127 /*File*/ nullptr);
128 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000129 ExprValue Value = Cmd->Expression();
130 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
Rui Ueyama80474a22017-02-28 19:29:55 +0000131 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +0000132 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000133 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +0000134}
135
Rui Ueyama22375f22016-11-25 18:51:54 +0000136static bool isUnderSysroot(StringRef Path) {
137 if (Config->Sysroot == "")
138 return false;
139 for (; !Path.empty(); Path = sys::path::parent_path(Path))
140 if (sys::fs::equivalent(Config->Sysroot, Path))
141 return true;
142 return false;
143}
144
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000145OutputSection *LinkerScript::getOutputSection(const Twine &Loc,
146 StringRef Name) {
George Rimar851dc1e2017-03-14 10:15:53 +0000147 for (OutputSection *Sec : *OutputSections)
148 if (Sec->Name == Name)
149 return Sec;
150
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +0000151 static OutputSection Dummy("", 0, 0);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000152 if (ErrorOnMissingSection)
153 error(Loc + ": undefined section " + Name);
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +0000154 return &Dummy;
George Rimar851dc1e2017-03-14 10:15:53 +0000155}
156
George Rimard83ce1b2017-03-14 10:24:47 +0000157// This function is essentially the same as getOutputSection(Name)->Size,
158// but it won't print out an error message if a given section is not found.
159//
160// Linker script does not create an output section if its content is empty.
161// We want to allow SIZEOF(.foo) where .foo is a section which happened to
162// be empty. That is why this function is different from getOutputSection().
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000163uint64_t LinkerScript::getOutputSectionSize(StringRef Name) {
George Rimard83ce1b2017-03-14 10:24:47 +0000164 for (OutputSection *Sec : *OutputSections)
165 if (Sec->Name == Name)
166 return Sec->Size;
167 return 0;
168}
169
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000170void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000171 uint64_t Val = E().getValue();
Rafael Espindola679828f2017-02-17 16:26:13 +0000172 if (Val < Dot) {
173 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000174 error(Loc + ": unable to move location counter backward for: " +
175 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000176 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000177 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000178 }
179 Dot = Val;
180 // Update to location counter means update to section size.
181 if (InSec)
182 CurOutSec->Size = Dot - CurOutSec->Addr;
183}
184
George Rimarb2b70972017-02-07 10:23:28 +0000185// Sets value of a symbol. Two kinds of symbols are processed: synthetic
186// symbols, whose value is an offset from beginning of section and regular
187// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000188void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000189 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000190 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000191 return;
192 }
193
George Rimarb2b70972017-02-07 10:23:28 +0000194 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000195 return;
196
Rafael Espindola5616adf2017-03-08 22:36:28 +0000197 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000198 ExprValue V = Cmd->Expression();
199 if (V.isAbsolute()) {
200 Sym->Value = V.getValue();
201 } else {
202 Sym->Section = V.Sec;
203 if (Sym->Section->Flags & SHF_ALLOC)
204 Sym->Value = V.Val;
205 else
206 Sym->Value = V.getValue();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000207 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000208}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000209
George Rimara8dba482017-03-20 10:09:58 +0000210static SymbolBody *findSymbol(StringRef S) {
211 switch (Config->EKind) {
212 case ELF32LEKind:
213 return Symtab<ELF32LE>::X->find(S);
214 case ELF32BEKind:
215 return Symtab<ELF32BE>::X->find(S);
216 case ELF64LEKind:
217 return Symtab<ELF64LE>::X->find(S);
218 case ELF64BEKind:
219 return Symtab<ELF64BE>::X->find(S);
220 default:
221 llvm_unreachable("unknown Config->EKind");
222 }
223}
224
225static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
226 switch (Config->EKind) {
227 case ELF32LEKind:
228 return addRegular<ELF32LE>(Cmd);
229 case ELF32BEKind:
230 return addRegular<ELF32BE>(Cmd);
231 case ELF64LEKind:
232 return addRegular<ELF64LE>(Cmd);
233 case ELF64BEKind:
234 return addRegular<ELF64BE>(Cmd);
235 default:
236 llvm_unreachable("unknown Config->EKind");
237 }
238}
239
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000240void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000241 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000242 return;
243
244 // If a symbol was in PROVIDE(), we need to define it only when
245 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000246 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000247 if (Cmd->Provide && (!B || B->isDefined()))
248 return;
249
George Rimara8dba482017-03-20 10:09:58 +0000250 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000251}
252
George Rimar076fe152016-07-21 06:43:01 +0000253bool SymbolAssignment::classof(const BaseCommand *C) {
254 return C->Kind == AssignmentKind;
255}
256
257bool OutputSectionCommand::classof(const BaseCommand *C) {
258 return C->Kind == OutputSectionKind;
259}
260
George Rimareea31142016-07-21 14:26:59 +0000261bool InputSectionDescription::classof(const BaseCommand *C) {
262 return C->Kind == InputSectionKind;
263}
264
George Rimareefa7582016-08-04 09:29:31 +0000265bool AssertCommand::classof(const BaseCommand *C) {
266 return C->Kind == AssertKind;
267}
268
George Rimare38cbab2016-09-26 19:22:50 +0000269bool BytesDataCommand::classof(const BaseCommand *C) {
270 return C->Kind == BytesDataKind;
271}
272
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000273static StringRef basename(InputSectionBase *S) {
274 if (S->File)
275 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000276 return "";
277}
278
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000279bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000280 for (InputSectionDescription *ID : Opt.KeptSections)
281 if (ID->FilePat.match(basename(S)))
282 for (SectionPattern &P : ID->SectionPatterns)
283 if (P.SectionPat.match(S->Name))
284 return true;
George Rimareea31142016-07-21 14:26:59 +0000285 return false;
286}
287
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000288// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000289static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000290getComparator(SortSectionPolicy K) {
291 switch (K) {
292 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000293 return [](InputSectionBase *A, InputSectionBase *B) {
294 // ">" is not a mistake. Sections with larger alignments are placed
295 // before sections with smaller alignments in order to reduce the
296 // amount of padding necessary. This is compatible with GNU.
297 return A->Alignment > B->Alignment;
298 };
George Rimarbe394db2016-09-16 20:21:55 +0000299 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000300 return [](InputSectionBase *A, InputSectionBase *B) {
301 return A->Name < B->Name;
302 };
George Rimarbe394db2016-09-16 20:21:55 +0000303 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000304 return [](InputSectionBase *A, InputSectionBase *B) {
305 return getPriority(A->Name) < getPriority(B->Name);
306 };
George Rimarbe394db2016-09-16 20:21:55 +0000307 default:
308 llvm_unreachable("unknown sort policy");
309 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000310}
George Rimar0702c4e2016-07-29 15:32:46 +0000311
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000312// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000313static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000314 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000315 if (Kind == ConstraintKind::NoConstraint)
316 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000317
318 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
319 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000320 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000321
Rafael Espindolae746e522016-09-21 18:33:44 +0000322 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
323 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000324}
325
Rafael Espindolac404d502017-02-23 02:32:18 +0000326static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000327 SortSectionPolicy K) {
328 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000329 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000330}
331
Rafael Espindolad3190792016-09-16 15:10:23 +0000332// Compute and remember which sections the InputSectionDescription matches.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000333std::vector<InputSectionBase *>
334LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
335 std::vector<InputSectionBase *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000336
Rui Ueyama72e107f2017-04-05 02:05:48 +0000337 // Collects all sections that satisfy constraints of Cmd.
338 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
339 size_t SizeBefore = Ret.size();
340
341 for (InputSectionBase *Sec : InputSections) {
342 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000343 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000344
Rafael Espindola908a3d32017-02-16 14:36:09 +0000345 // For -emit-relocs we have to ignore entries like
346 // .rela.dyn : { *(.rela.data) }
347 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000348 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000349 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000350
Rui Ueyama72e107f2017-04-05 02:05:48 +0000351 StringRef Filename = basename(Sec);
352 if (!Cmd->FilePat.match(Filename) ||
353 Pat.ExcludedFilePat.match(Filename) ||
354 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000355 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000356
357 Ret.push_back(Sec);
358 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000359 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000360
George Rimar07171f22016-09-21 15:56:44 +0000361 // Sort sections as instructed by SORT-family commands and --sort-section
362 // option. Because SORT-family commands can be nested at most two depth
363 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
364 // line option is respected even if a SORT command is given, the exact
365 // behavior we have here is a bit complicated. Here are the rules.
366 //
367 // 1. If two SORT commands are given, --sort-section is ignored.
368 // 2. If one SORT command is given, and if it is not SORT_NONE,
369 // --sort-section is handled as an inner SORT command.
370 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
371 // 4. If no SORT command is given, sort according to --sort-section.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000372 InputSectionBase **Begin = Ret.data() + SizeBefore;
373 InputSectionBase **End = Ret.data() + Ret.size();
George Rimar07171f22016-09-21 15:56:44 +0000374 if (Pat.SortOuter != SortSectionPolicy::None) {
375 if (Pat.SortInner == SortSectionPolicy::Default)
376 sortSections(Begin, End, Config->SortSection);
377 else
378 sortSections(Begin, End, Pat.SortInner);
379 sortSections(Begin, End, Pat.SortOuter);
380 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000381 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000382 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000383}
384
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000385void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000386 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000387 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000388 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000389 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000390 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000391 }
392}
393
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000394std::vector<InputSectionBase *>
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000395LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000396 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000397
Rui Ueyama8f99f732017-04-05 03:20:42 +0000398 for (BaseCommand *Base : OutCmd.Commands) {
399 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000400 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000401 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000402
403 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000404 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000405 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000406 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000407
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000408 return Ret;
409}
410
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000411void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000412 // A symbol can be assigned before any section is mentioned in the linker
413 // script. In an DSO, the symbol values are addresses, so the only important
414 // section values are:
415 // * SHN_UNDEF
416 // * SHN_ABS
417 // * Any value meaning a regular section.
418 // To handle that, create a dummy aether section that fills the void before
419 // the linker scripts switches to another section. It has an index of one
420 // which will map to whatever the first actual section is.
421 Aether = make<OutputSection>("", 0, SHF_ALLOC);
422 Aether->SectionIndex = 1;
423 CurOutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000424 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000425
Rui Ueyamac8124ee2017-04-05 03:21:01 +0000426 for (auto It = Opt.Commands.begin(); It != Opt.Commands.end(); ++It) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000427 // Handle symbol assignments outside of any output section.
Rui Ueyamac8124ee2017-04-05 03:21:01 +0000428 if (auto *Cmd = dyn_cast<SymbolAssignment>(*It)) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000429 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000430 continue;
431 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000432
Rui Ueyamac8124ee2017-04-05 03:21:01 +0000433 if (auto *Cmd = dyn_cast<OutputSectionCommand>(*It)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000434 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000435
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000436 // The output section name `/DISCARD/' is special.
437 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000438 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000439 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000440 continue;
441 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000442
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000443 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
444 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
445 // sections satisfy a given constraint. If not, a directive is handled
Rui Ueyamac8124ee2017-04-05 03:21:01 +0000446 // as if it weren't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000447 //
448 // Because we'll iterate over Commands many more times, the easiest
Rui Ueyamac8124ee2017-04-05 03:21:01 +0000449 // way to "make it as if it weren't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000450 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000451 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000452 S->Assigned = false;
Rui Ueyamac8124ee2017-04-05 03:21:01 +0000453 --It;
454 Opt.Commands.erase(It + 1);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000455 continue;
456 }
457
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000458 // A directive may contain symbol definitions like this:
459 // ".foo : { ...; bar = .; }". Handle them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000460 for (BaseCommand *Base : Cmd->Commands)
461 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000462 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000463
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000464 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
465 // is given, input sections are aligned to that value, whether the
466 // given value is larger or smaller than the original section alignment.
467 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000468 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000469 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000470 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000471 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000472
473 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000474 for (InputSectionBase *S : V)
George Rimare21c3af2017-03-14 09:30:25 +0000475 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000476 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000477 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000478 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000479}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000480
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000481// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000482void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000483 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000484 if (S->Live && !S->OutSec)
George Rimare21c3af2017-03-14 09:30:25 +0000485 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000486}
487
George Rimarf7f0d082017-03-14 11:23:33 +0000488static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000489 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000490}
491
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000492void LinkerScript::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000493 if (!AlreadyOutputIS.insert(S).second)
494 return;
George Rimarf7f0d082017-03-14 11:23:33 +0000495 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000496
George Rimar0c1c8082017-03-14 10:00:19 +0000497 uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000498 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000499 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000500 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000501
502 // Update output section size after adding each section. This is so that
503 // SIZEOF works correctly in the case below:
504 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000505 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000506
Meador Ingeb8897442017-01-24 02:34:00 +0000507 // If there is a memory region associated with this input section, then
508 // place the section in that region and update the region index.
509 if (CurMemRegion) {
510 CurMemRegion->Offset += CurOutSec->Size;
511 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
512 if (CurSize > CurMemRegion->Length) {
513 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
514 error("section '" + CurOutSec->Name + "' will not fit in region '" +
515 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
516 " bytes");
517 }
518 }
519
Rafael Espindola7252ae52016-09-22 12:00:08 +0000520 if (IsTbss)
521 ThreadBssOffset = Pos - Dot;
522 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000523 Dot = Pos;
524}
525
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000526void LinkerScript::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000527 assert(CurOutSec);
528 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000529 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000530 for (InputSection *I : CurOutSec->Sections)
531 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000532}
533
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000534void LinkerScript::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000535 if (CurOutSec == Sec)
536 return;
537 if (AlreadyOutputOS.count(Sec))
538 return;
539
Rafael Espindolad3190792016-09-16 15:10:23 +0000540 CurOutSec = Sec;
541
Rafael Espindola37707632017-03-07 14:55:52 +0000542 Dot = alignTo(Dot, CurOutSec->Alignment);
George Rimarf7f0d082017-03-14 11:23:33 +0000543 CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000544
545 // If neither AT nor AT> is specified for an allocatable section, the linker
546 // will set the LMA such that the difference between VMA and LMA for the
547 // section is the same as the preceding output section in the same region
548 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000549 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000550 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000551}
552
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000553void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000554 // This handles the assignments to symbol or to the dot.
555 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
556 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000557 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000558 }
George Rimare38cbab2016-09-26 19:22:50 +0000559
560 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000561 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
562 Cmd->Offset = Dot - CurOutSec->Addr;
563 Dot += Cmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000564 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000565 return;
566 }
567
Rui Ueyama2e081a42017-04-05 03:18:46 +0000568 // Handle ASSERT().
569 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
570 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000571 return;
572 }
573
Rui Ueyama2e081a42017-04-05 03:18:46 +0000574 // Handle a single input section description command.
575 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000576 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000577 auto &Cmd = cast<InputSectionDescription>(Base);
578 for (InputSectionBase *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000579 // We tentatively added all synthetic sections at the beginning and removed
580 // empty ones afterwards (because there is no way to know whether they were
581 // going be empty or not other than actually running linker scripts.)
582 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000583 if (auto *S = dyn_cast<SyntheticSection>(Sec))
584 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000585 continue;
586
Rui Ueyama2e081a42017-04-05 03:18:46 +0000587 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000588 continue;
Rui Ueyama2e081a42017-04-05 03:18:46 +0000589 assert(CurOutSec == Sec->OutSec || AlreadyOutputOS.count(Sec->OutSec));
590 output(cast<InputSection>(Sec));
Eugene Leviantceabe802016-08-11 07:56:43 +0000591 }
592}
593
Rafael Espindola24e6f362017-02-24 15:07:30 +0000594static OutputSection *
595findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rui Ueyama0b2381e2017-04-05 03:19:06 +0000596 for (OutputSection *Sec : Sections)
597 if (Sec->Name == Name)
598 return Sec;
599 return nullptr;
George Rimar8f66df92016-08-12 20:38:20 +0000600}
601
Meador Ingeb8897442017-01-24 02:34:00 +0000602// This function searches for a memory region to place the given output
603// section in. If found, a pointer to the appropriate memory region is
604// returned. Otherwise, a nullptr is returned.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000605MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd,
606 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000607 // If a memory region name was specified in the output section command,
608 // then try to find that region first.
609 if (!Cmd->MemoryRegionName.empty()) {
610 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
611 if (It != Opt.MemoryRegions.end())
612 return &It->second;
613 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
614 return nullptr;
615 }
616
Rui Ueyamad7c54002017-04-05 03:19:43 +0000617 // If at least one memory region is defined, all sections must
618 // belong to some memory region. Otherwise, we don't need to do
619 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000620 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000621 return nullptr;
622
623 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000624 for (auto &Pair : Opt.MemoryRegions) {
625 MemoryRegion &M = Pair.second;
626 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
627 return &M;
Meador Ingeb8897442017-01-24 02:34:00 +0000628 }
629
630 // Otherwise, no suitable region was found.
631 if (Sec->Flags & SHF_ALLOC)
632 error("no memory region specified for section '" + Sec->Name + "'");
633 return nullptr;
634}
635
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000636// This function assigns offsets to input sections and an output section
637// for a single sections command (e.g. ".text { *(.text); }").
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000638void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar23e6a022017-03-14 11:31:28 +0000639 OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000640 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000641 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000642
Rui Ueyamacba41012017-04-05 03:20:03 +0000643 if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
Rui Ueyamad379f732017-04-05 03:20:22 +0000644 setDot(Cmd->AddrExpr, Cmd->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000645
Eugene Leviant5784e962017-03-14 08:57:09 +0000646 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000647 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000648 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000649 }
650
Petr Hosek165088a2017-02-07 23:42:31 +0000651 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
652 if (Cmd->AlignExpr)
Rafael Espindola72dc1952017-03-17 13:05:04 +0000653 Sec->updateAlignment(Cmd->AlignExpr().getValue());
Petr Hosek165088a2017-02-07 23:42:31 +0000654
Meador Ingeb8897442017-01-24 02:34:00 +0000655 // Try and find an appropriate memory region to assign offsets in.
656 CurMemRegion = findMemoryRegion(Cmd, Sec);
657 if (CurMemRegion)
658 Dot = CurMemRegion->Offset;
659 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000660
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000661 // flush() may add orphan sections, so the order of flush() and
662 // symbol assignments is important. We want to call flush() first so
663 // that symbols pointing the end of the current section points to
664 // the location after orphan sections.
665 auto Mid =
Rui Ueyama8f99f732017-04-05 03:20:42 +0000666 std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
667 [](BaseCommand *Cmd) { return !isa<SymbolAssignment>(Cmd); })
668 .base();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000669 for (auto I = Cmd->Commands.begin(); I != Mid; ++I)
Rafael Espindolad3190792016-09-16 15:10:23 +0000670 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000671 flush();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000672 for (auto I = Mid, E = Cmd->Commands.end(); I != E; ++I)
673 process(**I);
Rafael Espindolad3190792016-09-16 15:10:23 +0000674}
675
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000676void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000677 // It is common practice to use very generic linker scripts. So for any
678 // given run some of the output sections in the script will be empty.
679 // We could create corresponding empty output sections, but that would
680 // clutter the output.
681 // We instead remove trivially empty sections. The bfd linker seems even
682 // more aggressive at removing them.
683 auto Pos = std::remove_if(
Rui Ueyama8f99f732017-04-05 03:20:42 +0000684 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
685 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
George Rimar23e6a022017-03-14 11:31:28 +0000686 return !findSection(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000687 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000688 });
689 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000690}
691
Rafael Espindola6a537372016-11-14 14:33:49 +0000692static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000693 for (BaseCommand *Base : Cmd.Commands)
694 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000695 return false;
696 return true;
697}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000698
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000699void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000700 // If the output section contains only symbol assignments, create a
701 // corresponding output section. The bfd linker seems to only create them if
702 // '.' is assigned to, but creating these section should not have any bad
703 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000704 uint64_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000705 uint32_t Type = SHT_NOBITS;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000706 for (BaseCommand *Base : Opt.Commands) {
707 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000708 if (!Cmd)
709 continue;
George Rimar23e6a022017-03-14 11:31:28 +0000710 if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000711 Flags = Sec->Flags;
712 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000713 continue;
714 }
715
Rafael Espindola6a537372016-11-14 14:33:49 +0000716 if (isAllSectionDescription(*Cmd))
717 continue;
718
Rafael Espindola24e6f362017-02-24 15:07:30 +0000719 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000720 OutputSections->push_back(OutSec);
721 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000722}
723
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000724void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000725 placeOrphanSections();
726
727 // If output section command doesn't specify any segments,
728 // and we haven't previously assigned any section to segment,
729 // then we simply assign section to the very first load segment.
730 // Below is an example of such linker script:
731 // PHDRS { seg PT_LOAD; }
732 // SECTIONS { .aaa : { *(.aaa) } }
733 std::vector<StringRef> DefPhdrs;
734 auto FirstPtLoad =
735 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
736 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
737 if (FirstPtLoad != Opt.PhdrsCommands.end())
738 DefPhdrs.push_back(FirstPtLoad->Name);
739
740 // Walk the commands and propagate the program headers to commands that don't
741 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000742 for (BaseCommand *Base : Opt.Commands) {
743 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000744 if (!Cmd)
745 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000746
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000747 if (Cmd->Phdrs.empty())
748 Cmd->Phdrs = DefPhdrs;
749 else
750 DefPhdrs = Cmd->Phdrs;
751 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000752
753 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000754}
755
Rafael Espindola15c57952016-09-22 18:05:49 +0000756// When placing orphan sections, we want to place them after symbol assignments
757// so that an orphan after
758// begin_foo = .;
759// foo : { *(foo) }
760// end_foo = .;
761// doesn't break the intended meaning of the begin/end symbols.
762// We don't want to go over sections since Writer<ELFT>::sortSections is the
763// one in charge of deciding the order of the sections.
764// We don't want to go over alignments, since doing so in
765// rx_sec : { *(rx_sec) }
766// . = ALIGN(0x1000);
767// /* The RW PT_LOAD starts here*/
768// rw_sec : { *(rw_sec) }
769// would mean that the RW PT_LOAD would become unaligned.
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000770static bool shouldSkip(BaseCommand *Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000771 if (isa<OutputSectionCommand>(Cmd))
772 return false;
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000773 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
774 return Assign->Name != ".";
775 return true;
Rafael Espindola15c57952016-09-22 18:05:49 +0000776}
777
Rui Ueyama6697ec22017-02-02 23:26:12 +0000778// Orphan sections are sections present in the input files which are
779// not explicitly placed into the output file by the linker script.
780//
781// When the control reaches this function, Opt.Commands contains
782// output section commands for non-orphan sections only. This function
Rui Ueyama81cb7102017-03-24 00:15:57 +0000783// adds new elements for orphan sections so that all sections are
784// explicitly handled by Opt.Commands.
Rui Ueyama6697ec22017-02-02 23:26:12 +0000785//
786// Writer<ELFT>::sortSections has already sorted output sections.
787// What we need to do is to scan OutputSections vector and
788// Opt.Commands in parallel to find orphan sections. If there is an
789// output section that doesn't have a corresponding entry in
790// Opt.Commands, we will insert a new entry to Opt.Commands.
791//
792// There is some ambiguity as to where exactly a new entry should be
793// inserted, because Opt.Commands contains not only output section
Rui Ueyama81cb7102017-03-24 00:15:57 +0000794// commands but also other types of commands such as symbol assignment
Rui Ueyama6697ec22017-02-02 23:26:12 +0000795// expressions. There's no correct answer here due to the lack of the
796// formal specification of the linker script. We use heuristics to
797// determine whether a new output command should be added before or
798// after another commands. For the details, look at shouldSkip
799// function.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000800void LinkerScript::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000801 // The OutputSections are already in the correct order.
802 // This loops creates or moves commands as needed so that they are in the
803 // correct order.
804 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000805
806 // As a horrible special case, skip the first . assignment if it is before any
807 // section. We do this because it is common to set a load address by starting
808 // the script with ". = 0xabcd" and the expectation is that every section is
809 // after that.
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000810 auto FirstSectionOrDotAssignment =
811 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
812 [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000813 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
814 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
815 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
816 ++CmdIndex;
817 }
818
Rafael Espindola24e6f362017-02-24 15:07:30 +0000819 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000820 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000821
822 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000823 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000824 auto CmdIter = Opt.Commands.begin() + CmdIndex;
825 auto E = Opt.Commands.end();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000826 while (CmdIter != E && shouldSkip(*CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000827 ++CmdIter;
828 ++CmdIndex;
829 }
830
Rui Ueyama8f99f732017-04-05 03:20:42 +0000831 auto Pos = std::find_if(CmdIter, E, [&](BaseCommand *Base) {
832 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
833 return Cmd && Cmd->Name == Name;
834 });
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000835 if (Pos == E) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000836 Opt.Commands.insert(CmdIter, make<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000837 ++CmdIndex;
838 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000839 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000840
841 // Continue from where we found it.
842 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000843 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000844}
845
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000846void LinkerScript::processNonSectionCommands() {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000847 for (BaseCommand *Base : Opt.Commands) {
848 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
Rui Ueyamad379f732017-04-05 03:20:22 +0000849 assignSymbol(Cmd, false);
Rui Ueyama8f99f732017-04-05 03:20:42 +0000850 else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
Petr Hosek02ad5162017-03-15 03:33:23 +0000851 Cmd->Expression();
852 }
853}
854
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000855void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000856 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000857 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000858 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000859 switchTo(Aether);
860
Rui Ueyama8f99f732017-04-05 03:20:42 +0000861 for (BaseCommand *Base : Opt.Commands) {
862 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000863 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000864 continue;
865 }
866
Rui Ueyama8f99f732017-04-05 03:20:42 +0000867 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000868 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000869 continue;
870 }
871
Rui Ueyama8f99f732017-04-05 03:20:42 +0000872 auto *Cmd = cast<OutputSectionCommand>(Base);
Rafael Espindolad3190792016-09-16 15:10:23 +0000873 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000874 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000875
George Rimar0c1c8082017-03-14 10:00:19 +0000876 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000877 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000878 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000879 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000880 else
881 Sec->Addr = 0;
882 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000883
George Rimar2d262102017-03-14 09:03:53 +0000884 allocateHeaders(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000885}
886
Rui Ueyama464daad2016-08-22 04:55:20 +0000887// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000888std::vector<PhdrEntry> LinkerScript::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000889 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000890
Rui Ueyama464daad2016-08-22 04:55:20 +0000891 // Process PHDRS and FILEHDR keywords because they are not
892 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000893 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000894 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000895 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000896
897 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000898 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000899 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000900 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000901
902 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000903 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000904 Phdr.HasLMA = true;
905 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000906 }
907
Rui Ueyama464daad2016-08-22 04:55:20 +0000908 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000909 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000910 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000911 break;
912
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000913 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000914 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000915 Ret[Id].add(Sec);
916 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000917 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000918 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000919 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000920 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000921}
922
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000923bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000924 // Ignore .interp section in case we have PHDRS specification
925 // and PT_INTERP isn't listed.
926 return !Opt.PhdrsCommands.empty() &&
927 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
928 return Cmd.Type == PT_INTERP;
929 }) == Opt.PhdrsCommands.end();
930}
931
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000932uint32_t LinkerScript::getFiller(StringRef Name) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000933 for (BaseCommand *Base : Opt.Commands)
934 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
George Rimarf6c3cce2016-07-21 07:48:54 +0000935 if (Cmd->Name == Name)
936 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000937 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000938}
939
George Rimare38cbab2016-09-26 19:22:50 +0000940static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
George Rimare38cbab2016-09-26 19:22:50 +0000941 switch (Size) {
942 case 1:
943 *Buf = (uint8_t)Data;
944 break;
945 case 2:
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000946 write16(Buf, Data, Config->Endianness);
George Rimare38cbab2016-09-26 19:22:50 +0000947 break;
948 case 4:
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000949 write32(Buf, Data, Config->Endianness);
George Rimare38cbab2016-09-26 19:22:50 +0000950 break;
951 case 8:
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000952 write64(Buf, Data, Config->Endianness);
George Rimare38cbab2016-09-26 19:22:50 +0000953 break;
954 default:
955 llvm_unreachable("unsupported Size argument");
956 }
957}
958
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000959void LinkerScript::writeDataBytes(StringRef Name, uint8_t *Buf) {
George Rimare38cbab2016-09-26 19:22:50 +0000960 int I = getSectionIndex(Name);
961 if (I == INT_MAX)
962 return;
963
Rui Ueyama8f99f732017-04-05 03:20:42 +0000964 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
965 for (BaseCommand *Base : Cmd->Commands)
966 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
George Rimara8dba482017-03-20 10:09:58 +0000967 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000968}
969
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000970bool LinkerScript::hasLMA(StringRef Name) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000971 for (BaseCommand *Base : Opt.Commands)
972 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000973 if (Cmd->LMAExpr && Cmd->Name == Name)
974 return true;
975 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000976}
977
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000978// Returns the index of the given section name in linker script
979// SECTIONS commands. Sections are laid out as the same order as they
980// were in the script. If a given name did not appear in the script,
981// it returns INT_MAX, so that it will be laid out at end of file.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000982int LinkerScript::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000983 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
Rui Ueyama8f99f732017-04-05 03:20:42 +0000984 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000985 if (Cmd->Name == Name)
986 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000987 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000988}
989
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000990ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000991 if (S == ".")
Rafael Espindola72dc1952017-03-17 13:05:04 +0000992 return {CurOutSec, Dot - CurOutSec->Addr};
George Rimara8dba482017-03-20 10:09:58 +0000993 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000994 if (auto *D = dyn_cast<DefinedRegular>(B))
995 return {D->Section, D->Value};
Petr Hosek30f16b22017-03-23 03:52:34 +0000996 if (auto *C = dyn_cast<DefinedCommon>(B))
997 return {InX::Common, C->Offset};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000998 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000999 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001000 return 0;
1001}
1002
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001003bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +00001004
Eugene Leviantbbe38602016-07-19 09:25:43 +00001005// Returns indices of ELF headers containing specific section, identified
1006// by Name. Each index is a zero based number of ELF header listed within
1007// PHDRS {} script block.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001008std::vector<size_t> LinkerScript::getPhdrIndices(StringRef SectionName) {
Rui Ueyama8f99f732017-04-05 03:20:42 +00001009 for (BaseCommand *Base : Opt.Commands) {
1010 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001011 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +00001012 continue;
1013
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001014 std::vector<size_t> Ret;
1015 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001016 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001017 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001018 }
George Rimar31d842f2016-07-20 16:43:03 +00001019 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001020}
1021
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001022size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001023 size_t I = 0;
1024 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1025 if (Cmd.Name == PhdrName)
1026 return I;
1027 ++I;
1028 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001029 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001030 return 0;
1031}
1032
Rui Ueyama794366a2017-02-14 04:47:05 +00001033class elf::ScriptParser final : public ScriptLexer {
George Rimarc3794e52016-02-24 09:21:47 +00001034 typedef void (ScriptParser::*Handler)();
1035
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001036public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001037 ScriptParser(MemoryBufferRef MB)
Rui Ueyama794366a2017-02-14 04:47:05 +00001038 : ScriptLexer(MB),
Rui Ueyama22375f22016-11-25 18:51:54 +00001039 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001040
George Rimar20b65982016-08-31 09:08:26 +00001041 void readLinkerScript();
1042 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001043 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001044
1045private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001046 void addFile(StringRef Path);
1047
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001048 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001049 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001050 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001051 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001052 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001053 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001054 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001055 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001056 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001057 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001058 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001059 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001060 void readVersion();
1061 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001062
Rui Ueyama113cdec2016-07-24 23:05:57 +00001063 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001064 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001065 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001066 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001067 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001068 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001069 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001070 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001071 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001072 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001073 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001074 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001075 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001076 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001077 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001078 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001079
Rui Ueyama24e626c2017-01-26 02:58:19 +00001080 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1081 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1082
Rui Ueyama708019c2016-07-24 18:19:40 +00001083 Expr readExpr();
1084 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001085 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001086 Expr readPrimary();
1087 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001088 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001089
George Rimar20b65982016-08-31 09:08:26 +00001090 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001091 std::vector<SymbolVersion> readVersionExtern();
1092 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001093 void readVersionDeclaration(StringRef VerStr);
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001094
1095 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1096 readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001097
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001098 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001099};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001100
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001101void ScriptParser::readDynamicList() {
1102 expect("{");
1103 readAnonymousDeclaration();
1104 if (!atEOF())
1105 setError("EOF expected, but got " + next());
1106}
1107
George Rimar20b65982016-08-31 09:08:26 +00001108void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001109 readVersionScriptCommand();
1110 if (!atEOF())
1111 setError("EOF expected, but got " + next());
1112}
1113
1114void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001115 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001116 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001117 return;
1118 }
1119
Rui Ueyama95769b42016-08-31 20:03:54 +00001120 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001121 StringRef VerStr = next();
1122 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001123 setError("anonymous version definition is used in "
1124 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001125 return;
1126 }
1127 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001128 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001129 }
1130}
1131
Rui Ueyama95769b42016-08-31 20:03:54 +00001132void ScriptParser::readVersion() {
1133 expect("{");
1134 readVersionScriptCommand();
1135 expect("}");
1136}
1137
George Rimar20b65982016-08-31 09:08:26 +00001138void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001139 while (!atEOF()) {
1140 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001141 if (Tok == ";")
1142 continue;
1143
Eugene Leviant20d03192016-09-16 15:30:47 +00001144 if (Tok == "ASSERT") {
Rui Ueyama8f99f732017-04-05 03:20:42 +00001145 Script->Opt.Commands.push_back(make<AssertCommand>(readAssert()));
Eugene Leviant20d03192016-09-16 15:30:47 +00001146 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001147 readEntry();
1148 } else if (Tok == "EXTERN") {
1149 readExtern();
1150 } else if (Tok == "GROUP" || Tok == "INPUT") {
1151 readGroup();
1152 } else if (Tok == "INCLUDE") {
1153 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001154 } else if (Tok == "MEMORY") {
1155 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001156 } else if (Tok == "OUTPUT") {
1157 readOutput();
1158 } else if (Tok == "OUTPUT_ARCH") {
1159 readOutputArch();
1160 } else if (Tok == "OUTPUT_FORMAT") {
1161 readOutputFormat();
1162 } else if (Tok == "PHDRS") {
1163 readPhdrs();
1164 } else if (Tok == "SEARCH_DIR") {
1165 readSearchDir();
1166 } else if (Tok == "SECTIONS") {
1167 readSections();
1168 } else if (Tok == "VERSION") {
1169 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001170 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Rui Ueyama01aacc92017-04-05 03:52:47 +00001171 Script->Opt.Commands.push_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001172 } else {
George Rimar57610422016-03-11 14:43:02 +00001173 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001174 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001175 }
1176}
1177
Rui Ueyama717677a2016-02-11 21:17:59 +00001178void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001179 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001180 SmallString<128> PathData;
1181 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001182 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001183 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001184 return;
1185 }
1186 }
1187
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001188 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001189 Driver->addFile(S);
1190 } else if (S.startswith("=")) {
1191 if (Config->Sysroot.empty())
1192 Driver->addFile(S.substr(1));
1193 else
1194 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1195 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001196 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001197 } else if (sys::fs::exists(S)) {
1198 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001199 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001200 if (Optional<std::string> Path = findFromSearchPaths(S))
1201 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001202 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001203 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001204 }
1205}
1206
Rui Ueyama717677a2016-02-11 21:17:59 +00001207void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001208 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001209 bool Orig = Config->AsNeeded;
1210 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001211 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001212 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001213 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001214}
1215
Rui Ueyama717677a2016-02-11 21:17:59 +00001216void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001217 // -e <symbol> takes predecence over ENTRY(<symbol>).
1218 expect("(");
1219 StringRef Tok = next();
1220 if (Config->Entry.empty())
1221 Config->Entry = Tok;
1222 expect(")");
1223}
1224
Rui Ueyama717677a2016-02-11 21:17:59 +00001225void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001226 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001227 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001228 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001229}
1230
Rui Ueyama717677a2016-02-11 21:17:59 +00001231void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001232 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001233 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001234 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001235 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001236 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001237 else
George Rimarcd574a52016-09-09 14:35:36 +00001238 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001239 }
1240}
1241
Rui Ueyama717677a2016-02-11 21:17:59 +00001242void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001243 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001244
George Rimard4500652016-12-21 09:42:25 +00001245 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1246 // The file will be searched for in the current directory, and in any
1247 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001248 if (sys::fs::exists(Tok)) {
1249 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1250 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001251 return;
1252 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001253 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1254 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1255 tokenize(*MB);
1256 return;
1257 }
1258 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001259}
1260
Rui Ueyama717677a2016-02-11 21:17:59 +00001261void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001262 // -o <file> takes predecence over OUTPUT(<file>).
1263 expect("(");
1264 StringRef Tok = next();
1265 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001266 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001267 expect(")");
1268}
1269
Rui Ueyama717677a2016-02-11 21:17:59 +00001270void ScriptParser::readOutputArch() {
George Rimar4e01c3e2017-02-08 09:59:06 +00001271 // OUTPUT_ARCH is ignored for now.
Davide Italiano9159ce92015-10-12 21:50:08 +00001272 expect("(");
George Rimar4e01c3e2017-02-08 09:59:06 +00001273 while (!Error && !consume(")"))
1274 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001275}
1276
Rui Ueyama717677a2016-02-11 21:17:59 +00001277void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001278 // Error checking only for now.
1279 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001280 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001281 StringRef Tok = next();
1282 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001283 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001284 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001285 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001286 return;
1287 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001288 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001289 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001290 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001291 expect(")");
1292}
1293
Eugene Leviantbbe38602016-07-19 09:25:43 +00001294void ScriptParser::readPhdrs() {
1295 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001296 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001297 StringRef Tok = next();
Rui Ueyamaa34da932017-03-21 23:03:09 +00001298 Script->Opt.PhdrsCommands.push_back(
Eugene Leviant56b21c82016-09-09 09:46:16 +00001299 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Rui Ueyamaa34da932017-03-21 23:03:09 +00001300 PhdrsCommand &PhdrCmd = Script->Opt.PhdrsCommands.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001301
1302 PhdrCmd.Type = readPhdrType();
1303 do {
1304 Tok = next();
1305 if (Tok == ";")
1306 break;
1307 if (Tok == "FILEHDR")
1308 PhdrCmd.HasFilehdr = true;
1309 else if (Tok == "PHDRS")
1310 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001311 else if (Tok == "AT")
1312 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001313 else if (Tok == "FLAGS") {
1314 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001315 // Passing 0 for the value of dot is a bit of a hack. It means that
1316 // we accept expressions like ".|1".
Rafael Espindola72dc1952017-03-17 13:05:04 +00001317 PhdrCmd.Flags = readExpr()().getValue();
Eugene Leviant865bf862016-07-21 10:43:25 +00001318 expect(")");
1319 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001320 setError("unexpected header attribute: " + Tok);
1321 } while (!Error);
1322 }
1323}
1324
Rui Ueyama717677a2016-02-11 21:17:59 +00001325void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001326 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001327 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001328 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001329 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001330 expect(")");
1331}
1332
Rui Ueyama717677a2016-02-11 21:17:59 +00001333void ScriptParser::readSections() {
Rui Ueyamaa34da932017-03-21 23:03:09 +00001334 Script->Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001335 // -no-rosegment is used to avoid placing read only non-executable sections in
1336 // their own segment. We do the same if SECTIONS command is present in linker
1337 // script. See comment for computeFlags().
1338 Config->SingleRoRx = true;
1339
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001340 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001341 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001342 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001343 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001344 if (!Cmd) {
1345 if (Tok == "ASSERT")
Rui Ueyama8f99f732017-04-05 03:20:42 +00001346 Cmd = make<AssertCommand>(readAssert());
Eugene Leviantceabe802016-08-11 07:56:43 +00001347 else
1348 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001349 }
Rui Ueyama8f99f732017-04-05 03:20:42 +00001350 Script->Opt.Commands.push_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001351 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001352}
1353
Rui Ueyama708019c2016-07-24 18:19:40 +00001354static int precedence(StringRef Op) {
1355 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001356 .Cases("*", "/", 5)
1357 .Cases("+", "-", 4)
1358 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001359 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001360 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001361 .Default(-1);
1362}
1363
Eugene Leviantdb688452016-11-03 10:54:58 +00001364StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001365 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001366 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001367 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001368 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001369}
1370
George Rimarbe394db2016-09-16 20:21:55 +00001371SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001372 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001373 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001374 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001375 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001376 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001377 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001378 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001379 return SortSectionPolicy::None;
1380 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001381}
1382
George Rimar395281c2016-09-16 17:42:10 +00001383// Method reads a list of sequence of excluded files and section globs given in
1384// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1385// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001386// The semantics of that is next:
1387// * Include .foo.1 from every file.
1388// * Include .foo.2 from every file but a.o
1389// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001390std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1391 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001392 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001393 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001394 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001395 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001396 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001397 }
1398
George Rimar601e9892016-09-21 08:53:21 +00001399 std::vector<StringRef> V;
1400 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1401 V.push_back(next());
1402
1403 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001404 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001405 else
1406 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001407 }
George Rimar07171f22016-09-21 15:56:44 +00001408 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001409}
1410
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001411// Reads contents of "SECTIONS" directive. That directive contains a
1412// list of glob patterns for input sections. The grammar is as follows.
1413//
1414// <patterns> ::= <section-list>
1415// | <sort> "(" <section-list> ")"
1416// | <sort> "(" <sort> "(" <section-list> ")" ")"
1417//
1418// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1419// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1420//
1421// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001422InputSectionDescription *
1423ScriptParser::readInputSectionRules(StringRef FilePattern) {
Rui Ueyama8f99f732017-04-05 03:20:42 +00001424 auto *Cmd = make<InputSectionDescription>(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001425 expect("(");
Rui Ueyama8f99f732017-04-05 03:20:42 +00001426
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001427 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001428 SortSectionPolicy Outer = readSortKind();
1429 SortSectionPolicy Inner = SortSectionPolicy::Default;
1430 std::vector<SectionPattern> V;
1431 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001432 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001433 Inner = readSortKind();
1434 if (Inner != SortSectionPolicy::Default) {
1435 expect("(");
1436 V = readInputSectionsList();
1437 expect(")");
1438 } else {
1439 V = readInputSectionsList();
1440 }
George Rimar350ece42016-08-03 08:35:59 +00001441 expect(")");
1442 } else {
George Rimar07171f22016-09-21 15:56:44 +00001443 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001444 }
George Rimar0702c4e2016-07-29 15:32:46 +00001445
George Rimar07171f22016-09-21 15:56:44 +00001446 for (SectionPattern &Pat : V) {
1447 Pat.SortInner = Inner;
1448 Pat.SortOuter = Outer;
1449 }
1450
1451 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1452 }
Rui Ueyama10416562016-08-04 02:03:27 +00001453 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001454}
1455
George Rimara2496cb2016-08-30 09:46:59 +00001456InputSectionDescription *
1457ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001458 // Input section wildcard can be surrounded by KEEP.
1459 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001460 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001461 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001462 StringRef FilePattern = next();
1463 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001464 expect(")");
Rui Ueyamaa34da932017-03-21 23:03:09 +00001465 Script->Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001466 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001467 }
George Rimara2496cb2016-08-30 09:46:59 +00001468 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001469}
1470
George Rimar03fc0102016-07-28 07:18:23 +00001471void ScriptParser::readSort() {
1472 expect("(");
1473 expect("CONSTRUCTORS");
1474 expect(")");
1475}
1476
George Rimareefa7582016-08-04 09:29:31 +00001477Expr ScriptParser::readAssert() {
1478 expect("(");
1479 Expr E = readExpr();
1480 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001481 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001482 expect(")");
Rafael Espindola4595df92017-03-10 16:04:26 +00001483 return [=] {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001484 if (!E().getValue())
George Rimareefa7582016-08-04 09:29:31 +00001485 error(Msg);
George Rimara8dba482017-03-20 10:09:58 +00001486 return Script->getDot();
George Rimareefa7582016-08-04 09:29:31 +00001487 };
1488}
1489
Rui Ueyama25150e82016-09-06 17:46:43 +00001490// Reads a FILL(expr) command. We handle the FILL command as an
1491// alias for =fillexp section attribute, which is different from
1492// what GNU linkers do.
1493// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001494uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001495 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001496 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001497 expect(")");
1498 expect(";");
1499 return V;
1500}
1501
Rui Ueyama10416562016-08-04 02:03:27 +00001502OutputSectionCommand *
1503ScriptParser::readOutputSectionDescription(StringRef OutSec) {
Rui Ueyama8f99f732017-04-05 03:20:42 +00001504 OutputSectionCommand *Cmd = make<OutputSectionCommand>(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001505 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001506
1507 // Read an address expression.
1508 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1509 if (peek() != ":")
1510 Cmd->AddrExpr = readExpr();
1511
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001512 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001513
Rui Ueyama83043f22016-10-17 16:01:53 +00001514 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001515 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001516 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001517 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001518 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001519 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001520
Davide Italiano246f6812016-07-22 03:36:24 +00001521 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001522 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001523 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001524 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001525 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001526 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001527
Rui Ueyama83043f22016-10-17 16:01:53 +00001528 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001529 StringRef Tok = next();
George Rimar2fe07922017-01-31 08:50:11 +00001530 if (Tok == ";") {
George Rimar69750752017-02-01 09:14:22 +00001531 // Empty commands are allowed. Do nothing here.
George Rimar2fe07922017-01-31 08:50:11 +00001532 } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Rui Ueyama01aacc92017-04-05 03:52:47 +00001533 Cmd->Commands.push_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001534 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
Rui Ueyama01aacc92017-04-05 03:52:47 +00001535 Cmd->Commands.push_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001536 } else if (Tok == "ASSERT") {
Rui Ueyama01aacc92017-04-05 03:52:47 +00001537 Cmd->Commands.push_back(make<AssertCommand>(readAssert()));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001538 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001539 } else if (Tok == "CONSTRUCTORS") {
1540 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1541 // by name. This is for very old file formats such as ECOFF/XCOFF.
1542 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001543 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001544 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001545 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001546 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001547 } else if (peek() == "(") {
Rui Ueyama01aacc92017-04-05 03:52:47 +00001548 Cmd->Commands.push_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001549 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001550 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001551 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001552 }
Meador Ingeb8897442017-01-24 02:34:00 +00001553
1554 if (consume(">"))
1555 Cmd->MemoryRegionName = next();
1556
George Rimar076fe152016-07-21 06:43:01 +00001557 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001558
Rui Ueyama83043f22016-10-17 16:01:53 +00001559 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001560 Cmd->Filler = readOutputSectionFiller(next());
1561 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001562 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001563
George Rimar7185a1a2017-01-17 15:32:12 +00001564 // Consume optional comma following output section command.
1565 consume(",");
1566
Rui Ueyama10416562016-08-04 02:03:27 +00001567 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001568}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001569
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001570// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1571// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1572//
1573// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1574// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1575// as 32-bit big-endian values. We will do the same as ld.gold does
1576// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001577uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001578 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001579 if (!Tok.getAsInteger(0, V))
1580 return V;
1581 setError("invalid filler expression: " + Tok);
1582 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001583}
1584
Petr Hoseka35e39c2016-08-16 01:11:16 +00001585SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001586 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001587 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001588 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001589 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001590 expect(")");
1591 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001592 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001593}
1594
Rafael Espindolac96da112016-11-01 11:30:45 +00001595SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001596 SymbolAssignment *Cmd = nullptr;
1597 if (peek() == "=" || peek() == "+=") {
1598 Cmd = readAssignment(Tok);
1599 expect(";");
1600 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001601 Cmd = readProvideHidden(true, false);
1602 } else if (Tok == "HIDDEN") {
1603 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001604 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001605 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001606 }
1607 return Cmd;
1608}
1609
George Rimar30835ea2016-07-28 21:08:56 +00001610SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1611 StringRef Op = next();
1612 assert(Op == "=" || Op == "+=");
Petr Hosek02ad5162017-03-15 03:33:23 +00001613 Expr E = readExpr();
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001614 if (Op == "+=") {
1615 std::string Loc = getCurrentLocation();
George Rimara8dba482017-03-20 10:09:58 +00001616 E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001617 }
Rui Ueyama8f99f732017-04-05 03:20:42 +00001618 return make<SymbolAssignment>(Name, E, getCurrentLocation());
George Rimar30835ea2016-07-28 21:08:56 +00001619}
1620
1621// This is an operator-precedence parser to parse a linker
1622// script expression.
Rui Ueyama731a66a2017-02-15 19:58:17 +00001623Expr ScriptParser::readExpr() {
1624 // Our lexer is context-aware. Set the in-expression bit so that
1625 // they apply different tokenization rules.
1626 bool Orig = InExpr;
1627 InExpr = true;
1628 Expr E = readExpr1(readPrimary(), 0);
1629 InExpr = Orig;
1630 return E;
1631}
George Rimar30835ea2016-07-28 21:08:56 +00001632
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001633static Expr combine(StringRef Op, Expr L, Expr R) {
1634 if (Op == "*")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001635 return [=] { return mul(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001636 if (Op == "/") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001637 return [=] { return div(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001638 }
1639 if (Op == "+")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001640 return [=] { return add(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001641 if (Op == "-")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001642 return [=] { return sub(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001643 if (Op == "<<")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001644 return [=] { return leftShift(L(), R()); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001645 if (Op == ">>")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001646 return [=] { return rightShift(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001647 if (Op == "<")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001648 return [=] { return L().getValue() < R().getValue(); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001649 if (Op == ">")
Rafael Espindola195f23c2017-03-20 14:35:41 +00001650 return [=] { return L().getValue() > R().getValue(); };
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 Espindola72dc1952017-03-17 13:05:04 +00001660 return [=] { return bitAnd(L(), R()); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001661 if (Op == "|")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001662 return [=] { return bitOr(L(), R()); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001663 llvm_unreachable("invalid operator");
1664}
1665
Rui Ueyama708019c2016-07-24 18:19:40 +00001666// This is a part of the operator-precedence parser. This function
1667// assumes that the remaining token stream starts with an operator.
1668Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1669 while (!atEOF() && !Error) {
1670 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001671 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001672 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001673 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001674 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001675 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001676 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001677 Expr Rhs = readPrimary();
1678
1679 // Evaluate the remaining part of the expression first if the
1680 // next operator has greater precedence than the previous one.
1681 // For example, if we have read "+" and "3", and if the next
1682 // operator is "*", then we'll evaluate 3 * ... part first.
1683 while (!atEOF()) {
1684 StringRef Op2 = peek();
1685 if (precedence(Op2) <= precedence(Op1))
1686 break;
1687 Rhs = readExpr1(Rhs, precedence(Op2));
1688 }
1689
1690 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001691 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001692 return Lhs;
1693}
1694
1695uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001696 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001697 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001698 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001699 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001700 error("unknown constant: " + S);
1701 return 0;
1702}
1703
Rui Ueyama626e0b02016-09-02 18:19:00 +00001704// Parses Tok as an integer. Returns true if successful.
1705// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1706// and decimal numbers. Decimal numbers may have "K" (kilo) or
1707// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001708static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001709 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001710 if (Tok.startswith("-")) {
1711 if (!readInteger(Tok.substr(1), Result))
1712 return false;
1713 Result = -Result;
1714 return true;
1715 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001716
1717 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001718 if (Tok.startswith_lower("0x"))
1719 return !Tok.substr(2).getAsInteger(16, Result);
1720 if (Tok.endswith_lower("H"))
1721 return !Tok.drop_back().getAsInteger(16, Result);
1722
Rui Ueyama46247b82016-11-18 06:49:07 +00001723 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001724 int Suffix = 1;
1725 if (Tok.endswith_lower("K")) {
1726 Suffix = 1024;
1727 Tok = Tok.drop_back();
1728 } else if (Tok.endswith_lower("M")) {
1729 Suffix = 1024 * 1024;
1730 Tok = Tok.drop_back();
1731 }
1732 if (Tok.getAsInteger(10, Result))
1733 return false;
1734 Result *= Suffix;
1735 return true;
1736}
1737
George Rimare38cbab2016-09-26 19:22:50 +00001738BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1739 int Size = StringSwitch<unsigned>(Tok)
1740 .Case("BYTE", 1)
1741 .Case("SHORT", 2)
1742 .Case("LONG", 4)
1743 .Case("QUAD", 8)
1744 .Default(-1);
1745 if (Size == -1)
1746 return nullptr;
1747
Rui Ueyama8f99f732017-04-05 03:20:42 +00001748 return make<BytesDataCommand>(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001749}
1750
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001751StringRef ScriptParser::readParenLiteral() {
1752 expect("(");
1753 StringRef Tok = next();
1754 expect(")");
1755 return Tok;
1756}
1757
Rui Ueyama708019c2016-07-24 18:19:40 +00001758Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001759 if (peek() == "(")
1760 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001761
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001762 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001763 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001764
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001765 if (Tok == "~") {
1766 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001767 return [=] { return bitNot(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001768 }
1769 if (Tok == "-") {
1770 Expr E = readPrimary();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001771 return [=] { return minus(E()); };
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001772 }
1773
Rui Ueyama708019c2016-07-24 18:19:40 +00001774 // Built-in functions are parsed here.
1775 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
Petr Hosek02ad5162017-03-15 03:33:23 +00001776 if (Tok == "ABSOLUTE") {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001777 Expr Inner = readParenExpr();
1778 return [=] {
1779 ExprValue I = Inner();
1780 I.ForceAbsolute = true;
1781 return I;
1782 };
Petr Hosek02ad5162017-03-15 03:33:23 +00001783 }
George Rimar96659df2016-08-30 09:54:01 +00001784 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001785 StringRef Name = readParenLiteral();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001786 return [=]() -> ExprValue {
George Rimara8dba482017-03-20 10:09:58 +00001787 return {Script->getOutputSection(Location, Name), 0};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001788 };
George Rimar96659df2016-08-30 09:54:01 +00001789 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001790 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001791 expect("(");
1792 Expr E = readExpr();
1793 if (consume(",")) {
1794 Expr E2 = readExpr();
1795 expect(")");
Rafael Espindola72dc1952017-03-17 13:05:04 +00001796 return [=] { return alignTo(E().getValue(), E2().getValue()); };
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001797 }
1798 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001799 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001800 }
Rui Ueyamafc161732017-03-21 21:49:16 +00001801 if (Tok == "ALIGNOF") {
1802 StringRef Name = readParenLiteral();
1803 return [=] { return Script->getOutputSection(Location, Name)->Alignment; };
1804 }
1805 if (Tok == "ASSERT")
1806 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001807 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001808 StringRef Name = readParenLiteral();
Rafael Espindola4595df92017-03-10 16:04:26 +00001809 return [=] { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001810 }
1811 if (Tok == "DATA_SEGMENT_ALIGN") {
1812 expect("(");
1813 Expr E = readExpr();
1814 expect(",");
1815 readExpr();
1816 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001817 return [=] { return alignTo(Script->getDot(), E().getValue()); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001818 }
1819 if (Tok == "DATA_SEGMENT_END") {
1820 expect("(");
1821 expect(".");
1822 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001823 return [] { return Script->getDot(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001824 }
George Rimar276b4e62016-07-26 17:58:44 +00001825 if (Tok == "DATA_SEGMENT_RELRO_END") {
Rui Ueyamafc161732017-03-21 21:49:16 +00001826 // GNU linkers implements more complicated logic to handle
1827 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1828 // just align to the next page boundary for simplicity.
George Rimar276b4e62016-07-26 17:58:44 +00001829 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001830 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001831 expect(",");
1832 readExpr();
1833 expect(")");
George Rimara8dba482017-03-20 10:09:58 +00001834 return [] { return alignTo(Script->getDot(), Target->PageSize); };
George Rimar276b4e62016-07-26 17:58:44 +00001835 }
Rui Ueyamafc161732017-03-21 21:49:16 +00001836 if (Tok == "DEFINED") {
1837 StringRef Name = readParenLiteral();
1838 return [=] { return Script->isDefined(Name) ? 1 : 0; };
1839 }
1840 if (Tok == "LOADADDR") {
1841 StringRef Name = readParenLiteral();
1842 return [=] { return Script->getOutputSection(Location, Name)->getLMA(); };
1843 }
1844 if (Tok == "SEGMENT_START") {
1845 expect("(");
1846 skip();
1847 expect(",");
1848 Expr E = readExpr();
1849 expect(")");
1850 return [=] { return E(); };
1851 }
George Rimar9e694502016-07-29 16:18:47 +00001852 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001853 StringRef Name = readParenLiteral();
George Rimara8dba482017-03-20 10:09:58 +00001854 return [=] { return Script->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001855 }
George Rimare32a3592016-08-10 07:59:34 +00001856 if (Tok == "SIZEOF_HEADERS")
George Rimar78aa2702017-03-13 14:40:58 +00001857 return [=] { return elf::getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001858
George Rimar9f2f7ad2016-09-02 16:01:42 +00001859 // Tok is a literal number.
1860 uint64_t V;
1861 if (readInteger(Tok, V))
Rafael Espindola4595df92017-03-10 16:04:26 +00001862 return [=] { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001863
1864 // Tok is a symbol name.
Petr Hosek30f16b22017-03-23 03:52:34 +00001865 if (Tok != ".") {
1866 if (!isValidCIdentifier(Tok))
1867 setError("malformed number: " + Tok);
1868 Script->Opt.UndefinedSymbols.push_back(Tok);
1869 }
George Rimara8dba482017-03-20 10:09:58 +00001870 return [=] { return Script->getSymbolValue(Location, Tok); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001871}
1872
1873Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001874 Expr L = readExpr();
1875 expect(":");
1876 Expr R = readExpr();
Rafael Espindola72dc1952017-03-17 13:05:04 +00001877 return [=] { return Cond().getValue() ? L() : R(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001878}
1879
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001880Expr ScriptParser::readParenExpr() {
1881 expect("(");
1882 Expr E = readExpr();
1883 expect(")");
1884 return E;
1885}
1886
Eugene Leviantbbe38602016-07-19 09:25:43 +00001887std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1888 std::vector<StringRef> Phdrs;
1889 while (!Error && peek().startswith(":")) {
1890 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001891 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001892 }
1893 return Phdrs;
1894}
1895
George Rimar95dd7182016-10-18 10:49:50 +00001896// Read a program header type name. The next token must be a
1897// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001898unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001899 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001900 uint64_t Val;
1901 if (readInteger(Tok, Val))
1902 return Val;
1903
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001904 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001905 .Case("PT_NULL", PT_NULL)
1906 .Case("PT_LOAD", PT_LOAD)
1907 .Case("PT_DYNAMIC", PT_DYNAMIC)
1908 .Case("PT_INTERP", PT_INTERP)
1909 .Case("PT_NOTE", PT_NOTE)
1910 .Case("PT_SHLIB", PT_SHLIB)
1911 .Case("PT_PHDR", PT_PHDR)
1912 .Case("PT_TLS", PT_TLS)
1913 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1914 .Case("PT_GNU_STACK", PT_GNU_STACK)
1915 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001916 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001917 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001918 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001919 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001920
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001921 if (Ret == (unsigned)-1) {
1922 setError("invalid program header type: " + Tok);
1923 return PT_NULL;
1924 }
1925 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001926}
1927
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001928// Reads an anonymous version declaration.
Rui Ueyama12450b22016-11-18 06:30:09 +00001929void ScriptParser::readAnonymousDeclaration() {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001930 std::vector<SymbolVersion> Locals;
1931 std::vector<SymbolVersion> Globals;
1932 std::tie(Locals, Globals) = readSymbols();
1933
1934 for (SymbolVersion V : Locals) {
1935 if (V.Name == "*")
1936 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1937 else
1938 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001939 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001940
1941 for (SymbolVersion V : Globals)
1942 Config->VersionScriptGlobals.push_back(V);
1943
Rui Ueyama12450b22016-11-18 06:30:09 +00001944 expect(";");
1945}
1946
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001947// Reads a non-anonymous version definition,
1948// e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001949void ScriptParser::readVersionDeclaration(StringRef VerStr) {
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001950 // Read a symbol list.
1951 std::vector<SymbolVersion> Locals;
1952 std::vector<SymbolVersion> Globals;
1953 std::tie(Locals, Globals) = readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001954
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001955 for (SymbolVersion V : Locals) {
1956 if (V.Name == "*")
1957 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1958 else
1959 Config->VersionScriptLocals.push_back(V);
Rafael Espindola45242682017-02-03 13:24:01 +00001960 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001961
1962 // Create a new version definition and add that to the global symbols.
1963 VersionDefinition Ver;
1964 Ver.Name = VerStr;
1965 Ver.Globals = Globals;
1966
1967 // User-defined version number starts from 2 because 0 and 1 are
1968 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1969 Ver.Id = Config->VersionDefinitions.size() + 2;
1970 Config->VersionDefinitions.push_back(Ver);
George Rimar20b65982016-08-31 09:08:26 +00001971
Rui Ueyama12450b22016-11-18 06:30:09 +00001972 // Each version may have a parent version. For example, "Ver2"
1973 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1974 // as a parent. This version hierarchy is, probably against your
1975 // instinct, purely for hint; the runtime doesn't care about it
1976 // at all. In LLD, we simply ignore it.
1977 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001978 skip();
George Rimar20b65982016-08-31 09:08:26 +00001979 expect(";");
1980}
1981
Rui Ueyamaf5fce482017-03-09 19:23:00 +00001982// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1983std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1984ScriptParser::readSymbols() {
1985 std::vector<SymbolVersion> Locals;
1986 std::vector<SymbolVersion> Globals;
1987 std::vector<SymbolVersion> *V = &Globals;
1988
1989 while (!Error) {
1990 if (consume("}"))
1991 break;
1992 if (consumeLabel("local")) {
1993 V = &Locals;
1994 continue;
1995 }
1996 if (consumeLabel("global")) {
1997 V = &Globals;
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001998 continue;
1999 }
George Rimare0fc2422016-11-16 17:59:10 +00002000
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002001 if (consume("extern")) {
2002 std::vector<SymbolVersion> Ext = readVersionExtern();
2003 V->insert(V->end(), Ext.begin(), Ext.end());
2004 } else {
2005 StringRef Tok = next();
2006 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
2007 }
George Rimare0fc2422016-11-16 17:59:10 +00002008 expect(";");
2009 }
Rui Ueyamaf5fce482017-03-09 19:23:00 +00002010 return {Locals, Globals};
George Rimare0fc2422016-11-16 17:59:10 +00002011}
2012
Rui Ueyama12450b22016-11-18 06:30:09 +00002013// Reads an "extern C++" directive, e.g.,
2014// "extern "C++" { ns::*; "f(int, double)"; };"
2015std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00002016 StringRef Tok = next();
2017 bool IsCXX = Tok == "\"C++\"";
2018 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002019 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00002020 expect("{");
2021
Rui Ueyama12450b22016-11-18 06:30:09 +00002022 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00002023 while (!Error && peek() != "}") {
2024 StringRef Tok = next();
2025 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00002026 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00002027 expect(";");
2028 }
2029
2030 expect("}");
Rui Ueyama12450b22016-11-18 06:30:09 +00002031 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002032}
2033
George Rimar009833d2017-03-20 09:51:18 +00002034uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
2035 StringRef S3) {
Rui Ueyama24e626c2017-01-26 02:58:19 +00002036 if (!(consume(S1) || consume(S2) || consume(S3))) {
2037 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2038 return 0;
2039 }
2040 expect("=");
2041
2042 // TODO: Fully support constant expressions.
2043 uint64_t Val;
2044 if (!readInteger(next(), Val))
George Rimar009833d2017-03-20 09:51:18 +00002045 setError("nonconstant expression for " + S1);
Rui Ueyama24e626c2017-01-26 02:58:19 +00002046 return Val;
2047}
2048
2049// Parse the MEMORY command as specified in:
2050// https://sourceware.org/binutils/docs/ld/MEMORY.html
2051//
2052// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002053void ScriptParser::readMemory() {
2054 expect("{");
2055 while (!Error && !consume("}")) {
2056 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002057
Meador Ingeb8897442017-01-24 02:34:00 +00002058 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002059 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002060 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002061 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002062 expect(")");
2063 }
2064 expect(":");
2065
Rui Ueyama24e626c2017-01-26 02:58:19 +00002066 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002067 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002068 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002069
Meador Ingeb8897442017-01-24 02:34:00 +00002070 // Add the memory region to the region map (if it doesn't already exist).
Rui Ueyamaa34da932017-03-21 23:03:09 +00002071 auto It = Script->Opt.MemoryRegions.find(Name);
2072 if (It != Script->Opt.MemoryRegions.end())
Meador Ingeb8897442017-01-24 02:34:00 +00002073 setError("region '" + Name + "' already defined");
2074 else
Rui Ueyamaa34da932017-03-21 23:03:09 +00002075 Script->Opt.MemoryRegions[Name] = {Name, Origin, Length,
2076 Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002077 }
2078}
2079
2080// This function parses the attributes used to match against section
2081// flags when placing output sections in a memory region. These flags
2082// are only used when an explicit memory region name is not used.
2083std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2084 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002085 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002086 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002087
2088 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002089 uint32_t Flag = 0;
2090 if (C == '!')
2091 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002092 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002093 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002094 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002095 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002096 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002097 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002098 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002099 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002100
Meador Ingeb8897442017-01-24 02:34:00 +00002101 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002102 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002103 else
2104 Flags |= Flag;
2105 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002106 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002107}
2108
Rui Ueyama07320e42016-04-20 20:13:41 +00002109void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002110 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002111}
2112
2113void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002114 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002115}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002116
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002117void elf::readDynamicList(MemoryBufferRef MB) {
2118 ScriptParser(MB).readDynamicList();
2119}