blob: b3a1c45ea2c0c7898092fd2a634f6771c3a754e6 [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 Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
Eugene Leviantceabe802016-08-11 07:56:43 +000046template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000047static void addRegular(SymbolAssignment *Cmd) {
48 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000053template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000054 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
55 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000056 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Rui Ueyama16024212016-08-11 23:22:52 +000059// If a symbol was in PROVIDE(), we need to define it only when
60// it is an undefined symbol.
61template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
62 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000063 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000064 if (!Cmd->Provide)
65 return true;
66 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
67 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
George Rimar076fe152016-07-21 06:43:01 +000070bool SymbolAssignment::classof(const BaseCommand *C) {
71 return C->Kind == AssignmentKind;
72}
73
74bool OutputSectionCommand::classof(const BaseCommand *C) {
75 return C->Kind == OutputSectionKind;
76}
77
George Rimareea31142016-07-21 14:26:59 +000078bool InputSectionDescription::classof(const BaseCommand *C) {
79 return C->Kind == InputSectionKind;
80}
81
George Rimareefa7582016-08-04 09:29:31 +000082bool AssertCommand::classof(const BaseCommand *C) {
83 return C->Kind == AssertKind;
84}
85
Rui Ueyama36a153c2016-07-23 14:09:58 +000086template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000087 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000088}
89
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000090template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
91template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
92
Rui Ueyama07320e42016-04-20 20:13:41 +000093template <class ELFT>
94bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000095 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000096 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000097 return true;
98 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000099}
100
Rui Ueyama63dc6502016-07-25 22:41:42 +0000101static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
102 for (StringRef Pat : Patterns)
103 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000104 return true;
105 return false;
106}
107
George Rimar06598002016-07-28 21:51:30 +0000108static bool fileMatches(const InputSectionDescription *Desc,
109 StringRef Filename) {
110 if (!globMatch(Desc->FilePattern, Filename))
111 return false;
112 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
113}
114
Rui Ueyama6b274812016-07-25 22:51:07 +0000115// Returns input sections filtered by given glob patterns.
116template <class ELFT>
117std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000118LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000119 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000120 std::vector<InputSectionBase<ELFT> *> Ret;
121 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000122 Symtab<ELFT>::X->getObjectFiles()) {
123 if (fileMatches(I, sys::path::filename(F->getName())))
124 for (InputSectionBase<ELFT> *S : F->getSections())
125 if (!isDiscarded(S) && !S->OutSec &&
126 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000127 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000128 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000129
Rui Ueyama7ad9d6d2016-08-12 03:25:25 +0000130 if (llvm::find(Patterns, "COMMON") != Patterns.end())
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000131 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000132
Rui Ueyama6b274812016-07-25 22:51:07 +0000133 return Ret;
134}
135
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000136// You can define new symbols using linker scripts. For example,
137// ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
138// foo just after abc.o's text section contents. This class is to
139// handle such symbol definitions.
140//
141// In order to handle scripts like the above one, we want to
142// keep symbol definitions in output sections. Because output sections
143// can contain only input sections, we wrap symbol definitions
144// with dummy input sections. This class serves that purpose.
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000145template <class ELFT>
146class elf::LayoutInputSection : public InputSectionBase<ELFT> {
Eugene Leviantceabe802016-08-11 07:56:43 +0000147public:
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000148 explicit LayoutInputSection(SymbolAssignment *Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000149 static bool classof(const InputSectionBase<ELFT> *S);
150 SymbolAssignment *Cmd;
151
152private:
153 typename ELFT::Shdr Hdr;
154};
155
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000156template <class ELFT>
157static InputSectionBase<ELFT> *
158getNonLayoutSection(std::vector<InputSectionBase<ELFT> *> &Vec) {
159 for (InputSectionBase<ELFT> *S : Vec)
160 if (!isa<LayoutInputSection<ELFT>>(S))
161 return S;
162 return nullptr;
163}
Eugene Leviantceabe802016-08-11 07:56:43 +0000164
165template <class T> static T *zero(T *Val) {
166 memset(Val, 0, sizeof(*Val));
167 return Val;
168}
169
170template <class ELFT>
171LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000172 : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
173 InputSectionBase<ELFT>::Layout),
174 Cmd(Cmd) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000175 this->Live = true;
Eugene Leviantceabe802016-08-11 07:56:43 +0000176 Hdr.sh_type = SHT_NOBITS;
177}
178
179template <class ELFT>
180bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
181 return S->SectionKind == InputSectionBase<ELFT>::Layout;
182}
183
184template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000185static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
186 return A->getSectionName() < B->getSectionName();
187}
George Rimar350ece42016-08-03 08:35:59 +0000188
Rui Ueyama742c3832016-08-04 22:27:00 +0000189template <class ELFT>
190static bool compareAlignment(InputSectionBase<ELFT> *A,
191 InputSectionBase<ELFT> *B) {
192 // ">" is not a mistake. Larger alignments are placed before smaller
193 // alignments in order to reduce the amount of padding necessary.
194 // This is compatible with GNU.
195 return A->Alignment > B->Alignment;
196}
George Rimar350ece42016-08-03 08:35:59 +0000197
Rui Ueyama742c3832016-08-04 22:27:00 +0000198template <class ELFT>
199static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
200getComparator(SortKind K) {
201 if (K == SortByName)
202 return compareName<ELFT>;
203 return compareAlignment<ELFT>;
204}
George Rimar0702c4e2016-07-29 15:32:46 +0000205
206template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000207void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
208 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
209 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
210 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
211 S->Live = false;
212 reportDiscarded(S);
213 }
214 }
215 }
216}
217
George Rimar8f66df92016-08-12 20:38:20 +0000218static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
219 bool RO = (Kind == ConstraintKind::ReadOnly);
220 bool RW = (Kind == ConstraintKind::ReadWrite);
221 bool Writable = Flags & SHF_WRITE;
222 return !((RO && Writable) || (RW && !Writable));
223}
224
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000225template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000226static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
227 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000228 if (Kind == ConstraintKind::NoConstraint)
229 return true;
230 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
231 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000232 });
233}
234
235template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000236std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000237LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000238 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000239
George Rimar06ae6832016-08-12 09:07:57 +0000240 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
241 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
242 if (shouldDefine<ELFT>(OutCmd))
243 addSynthetic<ELFT>(OutCmd);
244 Ret.push_back(new (LAlloc.Allocate()) LayoutInputSection<ELFT>(OutCmd));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000245 continue;
246 }
247
248 auto *Cmd = cast<InputSectionDescription>(Base.get());
249 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000250 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
251 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000252 if (Cmd->SortInner)
253 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
254 if (Cmd->SortOuter)
255 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
256 Ret.insert(Ret.end(), V.begin(), V.end());
257 }
258 return Ret;
259}
260
261template <class ELFT>
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000262void LinkerScript<ELFT>::createAssignments() {
263 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
264 if (shouldDefine<ELFT>(Cmd.get()))
265 addRegular<ELFT>(Cmd.get());
266 if (Cmd->Sym)
267 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
268 }
269}
270
271template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000272void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000273 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000274 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
275 if (shouldDefine<ELFT>(Cmd))
276 addRegular<ELFT>(Cmd);
277 continue;
278 }
279
Eugene Leviantceabe802016-08-11 07:56:43 +0000280 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000281 if (Cmd->Name == "/DISCARD/") {
282 discard(*Cmd);
283 continue;
284 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000285
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000286 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
287 InputSectionBase<ELFT> *Head = getNonLayoutSection<ELFT>(V);
288 if (!Head)
289 continue;
290
291 OutputSectionBase<ELFT> *OutSec;
292 bool IsNew;
293 std::tie(OutSec, IsNew) = Factory.create(Head, Cmd->Name);
294 if (IsNew)
295 OutputSections->push_back(OutSec);
George Rimardb24d9c2016-08-19 15:18:23 +0000296
297 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
298 for (InputSectionBase<ELFT> *Sec : V) {
299 if (Subalign)
300 Sec->Alignment = Subalign;
Eugene Leviant3f675e32016-08-18 07:27:37 +0000301 if (!Sec->OutSec)
302 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000303 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000304 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000305 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000306
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000307 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000308 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000309 Symtab<ELFT>::X->getObjectFiles()) {
310 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000311 if (isDiscarded(S) || S->OutSec)
312 continue;
313 OutputSectionBase<ELFT> *OutSec;
314 bool IsNew;
315 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
316 if (IsNew)
317 OutputSections->push_back(OutSec);
318 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000319 }
320 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000321}
322
Eugene Leviant20889c52016-08-31 08:13:33 +0000323// Linker script may define start and end symbols for special section types,
324// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
325// of regular input input sections, therefore our way of defining symbols for
326// regular sections will not work. The approach we use for special section types
327// is not perfect - it handles only start and end symbols.
328template <class ELFT>
329void addStartEndSymbols(OutputSectionCommand *Cmd,
330 OutputSectionBase<ELFT> *Sec) {
331 bool Start = true;
332 BaseCommand *PrevCmd = nullptr;
333
334 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
335 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
336 if (auto *Sym = cast_or_null<DefinedSynthetic<ELFT>>(AssignCmd->Sym)) {
337 Sym->Section = Sec;
338 Sym->Value =
339 AssignCmd->Expression(Sec->getVA() + (Start ? 0 : Sec->getSize())) -
340 Sec->getVA();
341 }
342 } else {
343 if (!Start && isa<SymbolAssignment>(PrevCmd))
344 error("section '" + Sec->getName() +
345 "' supports only start and end symbols");
346 Start = false;
347 }
348 PrevCmd = Base.get();
349 }
350}
351
352template <class ELFT>
353void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000354 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000355 if (!OutSec) {
356 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000357 // This section is not regular output section. However linker script may
358 // have defined start/end symbols for it. This case is handled below.
359 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000360 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000361 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000362
363 typedef typename ELFT::uint uintX_t;
364 uintX_t Off = 0;
365
366 for (InputSection<ELFT> *I : OutSec->Sections) {
367 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
368 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000369 if (L->Cmd->Name == ".") {
Eugene Leviantceabe802016-08-11 07:56:43 +0000370 Off = Value;
Eugene Leviantb6f1bb12016-08-15 09:19:51 +0000371 } else if (auto *Sym =
372 cast_or_null<DefinedSynthetic<ELFT>>(L->Cmd->Sym)) {
373 // shouldDefine could have returned false, so we need to check Sym,
374 // for non-null value.
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000375 Sym->Section = OutSec;
376 Sym->Value = Value;
377 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000378 } else {
379 Off = alignTo(Off, I->Alignment);
380 I->OutSecOff = Off;
381 Off += I->getSize();
382 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000383 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000384 // works correctly in the case below:
385 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
386 Sec->setSize(Off);
387 }
388}
389
George Rimar8f66df92016-08-12 20:38:20 +0000390template <class ELFT>
391static OutputSectionBase<ELFT> *
392findSection(OutputSectionCommand &Cmd,
393 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
394 for (OutputSectionBase<ELFT> *Sec : Sections) {
395 if (Sec->getName() != Cmd.Name)
396 continue;
397 if (checkConstraint(Sec->getFlags(), Cmd.Constraint))
398 return Sec;
399 }
400 return nullptr;
401}
402
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000403template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000404 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000405 // are not explicitly placed into the output file by the linker script.
406 // We place orphan sections at end of file.
407 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000408 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000409 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000410 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000411 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000412 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000413 }
George Rimar652852c2016-04-16 10:10:32 +0000414
Rui Ueyama7c18c282016-04-18 21:00:40 +0000415 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000416 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000417 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000418 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000419
George Rimar076fe152016-07-21 06:43:01 +0000420 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
421 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000422 if (Cmd->Name == ".") {
423 Dot = Cmd->Expression(Dot);
424 } else if (Cmd->Sym) {
425 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
426 }
George Rimar652852c2016-04-16 10:10:32 +0000427 continue;
428 }
429
George Rimareefa7582016-08-04 09:29:31 +0000430 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
431 Cmd->Expression(Dot);
432 continue;
433 }
434
George Rimar076fe152016-07-21 06:43:01 +0000435 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar8f66df92016-08-12 20:38:20 +0000436 OutputSectionBase<ELFT> *Sec = findSection<ELFT>(*Cmd, *OutputSections);
437 if (!Sec)
George Rimarb6c52e82016-08-12 19:32:45 +0000438 continue;
George Rimar652852c2016-04-16 10:10:32 +0000439
George Rimarb6c52e82016-08-12 19:32:45 +0000440 if (Cmd->AddrExpr)
441 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000442
George Rimarb6c52e82016-08-12 19:32:45 +0000443 if (Cmd->AlignExpr)
444 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000445
George Rimarb6c52e82016-08-12 19:32:45 +0000446 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
447 uintX_t TVA = Dot + ThreadBssOffset;
448 TVA = alignTo(TVA, Sec->getAlignment());
449 Sec->setVA(TVA);
Eugene Leviant20889c52016-08-31 08:13:33 +0000450 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000451 ThreadBssOffset = TVA - Dot + Sec->getSize();
452 continue;
George Rimar652852c2016-04-16 10:10:32 +0000453 }
George Rimarb6c52e82016-08-12 19:32:45 +0000454
455 if (!(Sec->getFlags() & SHF_ALLOC)) {
Eugene Leviant20889c52016-08-31 08:13:33 +0000456 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000457 continue;
458 }
459
460 Dot = alignTo(Dot, Sec->getAlignment());
461 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000462 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000463 MinVA = std::min(MinVA, Dot);
464 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000465 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000466
Rafael Espindola64c32d62016-07-07 14:28:47 +0000467 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000468 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000469 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
470 Out<ELFT>::ProgramHeaders->getSize(),
471 Target->PageSize);
472 Out<ELFT>::ElfHeader->setVA(MinVA);
473 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000474}
475
Rui Ueyama464daad2016-08-22 04:55:20 +0000476// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000477template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000478std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000479 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000480
Rui Ueyama464daad2016-08-22 04:55:20 +0000481 // Process PHDRS and FILEHDR keywords because they are not
482 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000483 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000484 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
485 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486
487 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000488 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000489 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000490 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000491 }
492
Rui Ueyama464daad2016-08-22 04:55:20 +0000493 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000494 PhdrEntry<ELFT> *Load = nullptr;
495 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000496 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000497 if (!(Sec->getFlags() & SHF_ALLOC))
498 break;
499
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000500 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000501 if (!PhdrIds.empty()) {
502 // Assign headers specified by linker script
503 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000504 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000505 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000506 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000507 }
508 } else {
509 // If we have no load segment or flags've changed then we want new load
510 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000511 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000512 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000513 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000514 Flags = NewFlags;
515 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000516 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000517 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000518 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000519 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000520}
521
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000522template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
523 // Ignore .interp section in case we have PHDRS specification
524 // and PT_INTERP isn't listed.
525 return !Opt.PhdrsCommands.empty() &&
526 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
527 return Cmd.Type == PT_INTERP;
528 }) == Opt.PhdrsCommands.end();
529}
530
Eugene Leviantbbe38602016-07-19 09:25:43 +0000531template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000532ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000533 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
534 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
535 if (Cmd->Name == Name)
536 return Cmd->Filler;
537 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000538}
539
George Rimar206fffa2016-08-17 08:16:57 +0000540template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000541 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
542 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
543 if (Cmd->LmaExpr && Cmd->Name == Name)
544 return Cmd->LmaExpr;
545 return {};
546}
547
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000548// Returns the index of the given section name in linker script
549// SECTIONS commands. Sections are laid out as the same order as they
550// were in the script. If a given name did not appear in the script,
551// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000552template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000553 int I = 0;
554 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
555 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
556 if (Cmd->Name == Name)
557 return I;
558 ++I;
559 }
560 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000561}
562
563// A compartor to sort output sections. Returns -1 or 1 if
564// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000565template <class ELFT>
566int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000567 int I = getSectionIndex(A);
568 int J = getSectionIndex(B);
569 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000570 return 0;
571 return I < J ? -1 : 1;
572}
573
Eugene Leviantbbe38602016-07-19 09:25:43 +0000574template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
575 return !Opt.PhdrsCommands.empty();
576}
577
George Rimar9e694502016-07-29 16:18:47 +0000578template <class ELFT>
George Rimar96659df2016-08-30 09:54:01 +0000579typename ELFT::uint
580LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
581 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
582 if (Sec->getName() == Name)
583 return Sec->getVA();
584 error("undefined section " + Name);
585 return 0;
586}
587
588template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000589typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
590 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
591 if (Sec->getName() == Name)
592 return Sec->getSize();
593 error("undefined section " + Name);
594 return 0;
595}
596
George Rimare32a3592016-08-10 07:59:34 +0000597template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000598typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000599 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
600}
601
Eugene Leviantbbe38602016-07-19 09:25:43 +0000602// Returns indices of ELF headers containing specific section, identified
603// by Name. Each index is a zero based number of ELF header listed within
604// PHDRS {} script block.
605template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000606std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000607 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
608 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000609 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000610 continue;
611
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000612 std::vector<size_t> Ret;
613 for (StringRef PhdrName : Cmd->Phdrs)
614 Ret.push_back(getPhdrIndex(PhdrName));
615 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000616 }
George Rimar31d842f2016-07-20 16:43:03 +0000617 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000618}
619
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000620template <class ELFT>
621size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
622 size_t I = 0;
623 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
624 if (Cmd.Name == PhdrName)
625 return I;
626 ++I;
627 }
628 error("section header '" + PhdrName + "' is not listed in PHDRS");
629 return 0;
630}
631
Rui Ueyama07320e42016-04-20 20:13:41 +0000632class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000633 typedef void (ScriptParser::*Handler)();
634
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000635public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000636 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000637
George Rimar20b65982016-08-31 09:08:26 +0000638 void readLinkerScript();
639 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000640
641private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000642 void addFile(StringRef Path);
643
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000644 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000645 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000646 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000647 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000648 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000649 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000650 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000651 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000652 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000653 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000654 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000655 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000656 void readVersion();
657 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000658
Rui Ueyama113cdec2016-07-24 23:05:57 +0000659 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000660 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000661 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000662 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000663 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000664 std::vector<StringRef> readInputFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000665 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000666 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000667 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000668 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000669 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000670 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000671 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000672
673 Expr readExpr();
674 Expr readExpr1(Expr Lhs, int MinPrec);
675 Expr readPrimary();
676 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000677 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000678
George Rimar20b65982016-08-31 09:08:26 +0000679 // For parsing version script.
680 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000681 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000682 void readGlobal(StringRef VerStr);
683 void readLocal();
684
George Rimarc3794e52016-02-24 09:21:47 +0000685 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000686 ScriptConfiguration &Opt = *ScriptConfig;
687 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000688 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000689};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000690
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000691const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000692 {"ENTRY", &ScriptParser::readEntry},
693 {"EXTERN", &ScriptParser::readExtern},
694 {"GROUP", &ScriptParser::readGroup},
695 {"INCLUDE", &ScriptParser::readInclude},
696 {"INPUT", &ScriptParser::readGroup},
697 {"OUTPUT", &ScriptParser::readOutput},
698 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
699 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000700 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000701 {"SEARCH_DIR", &ScriptParser::readSearchDir},
702 {"SECTIONS", &ScriptParser::readSections},
Rui Ueyama95769b42016-08-31 20:03:54 +0000703 {"VERSION", &ScriptParser::readVersion},
George Rimarc3794e52016-02-24 09:21:47 +0000704 {";", &ScriptParser::readNothing}};
705
George Rimar20b65982016-08-31 09:08:26 +0000706void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000707 readVersionScriptCommand();
708 if (!atEOF())
709 setError("EOF expected, but got " + next());
710}
711
712void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000713 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000714 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000715 return;
716 }
717
Rui Ueyama95769b42016-08-31 20:03:54 +0000718 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000719 StringRef VerStr = next();
720 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000721 setError("anonymous version definition is used in "
722 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000723 return;
724 }
725 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000726 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000727 }
728}
729
Rui Ueyama95769b42016-08-31 20:03:54 +0000730void ScriptParser::readVersion() {
731 expect("{");
732 readVersionScriptCommand();
733 expect("}");
734}
735
George Rimar20b65982016-08-31 09:08:26 +0000736void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000737 while (!atEOF()) {
738 StringRef Tok = next();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000739 if (Handler Fn = Cmd.lookup(Tok)) {
George Rimarc3794e52016-02-24 09:21:47 +0000740 (this->*Fn)();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000741 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
742 if (Opt.HasContents)
743 Opt.Commands.emplace_back(Cmd);
744 else
745 Opt.Assignments.emplace_back(Cmd);
746 } else {
George Rimar57610422016-03-11 14:43:02 +0000747 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000748 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000749 }
750}
751
Rui Ueyama717677a2016-02-11 21:17:59 +0000752void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000753 if (IsUnderSysroot && S.startswith("/")) {
754 SmallString<128> Path;
755 (Config->Sysroot + S).toStringRef(Path);
756 if (sys::fs::exists(Path)) {
757 Driver->addFile(Saver.save(Path.str()));
758 return;
759 }
760 }
761
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000762 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000763 Driver->addFile(S);
764 } else if (S.startswith("=")) {
765 if (Config->Sysroot.empty())
766 Driver->addFile(S.substr(1));
767 else
768 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
769 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000770 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000771 } else if (sys::fs::exists(S)) {
772 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000773 } else {
774 std::string Path = findFromSearchPaths(S);
775 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000776 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000777 else
778 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000779 }
780}
781
Rui Ueyama717677a2016-02-11 21:17:59 +0000782void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000783 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000784 bool Orig = Config->AsNeeded;
785 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000786 while (!Error && !skip(")"))
787 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000788 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000789}
790
Rui Ueyama717677a2016-02-11 21:17:59 +0000791void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000792 // -e <symbol> takes predecence over ENTRY(<symbol>).
793 expect("(");
794 StringRef Tok = next();
795 if (Config->Entry.empty())
796 Config->Entry = Tok;
797 expect(")");
798}
799
Rui Ueyama717677a2016-02-11 21:17:59 +0000800void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000801 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000802 while (!Error && !skip(")"))
803 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000804}
805
Rui Ueyama717677a2016-02-11 21:17:59 +0000806void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000807 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000808 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000809 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000810 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000811 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000812 else
813 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000814 }
815}
816
Rui Ueyama717677a2016-02-11 21:17:59 +0000817void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000818 StringRef Tok = next();
819 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000820 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000821 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000822 return;
823 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000824 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000825 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
826 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000827 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000828}
829
Rui Ueyama717677a2016-02-11 21:17:59 +0000830void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000831 // -o <file> takes predecence over OUTPUT(<file>).
832 expect("(");
833 StringRef Tok = next();
834 if (Config->OutputFile.empty())
835 Config->OutputFile = Tok;
836 expect(")");
837}
838
Rui Ueyama717677a2016-02-11 21:17:59 +0000839void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000840 // Error checking only for now.
841 expect("(");
842 next();
843 expect(")");
844}
845
Rui Ueyama717677a2016-02-11 21:17:59 +0000846void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000847 // Error checking only for now.
848 expect("(");
849 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000850 StringRef Tok = next();
851 if (Tok == ")")
852 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000853 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000854 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000855 return;
856 }
Davide Italiano6836c612015-10-12 21:08:41 +0000857 next();
858 expect(",");
859 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000860 expect(")");
861}
862
Eugene Leviantbbe38602016-07-19 09:25:43 +0000863void ScriptParser::readPhdrs() {
864 expect("{");
865 while (!Error && !skip("}")) {
866 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000867 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000868 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
869
870 PhdrCmd.Type = readPhdrType();
871 do {
872 Tok = next();
873 if (Tok == ";")
874 break;
875 if (Tok == "FILEHDR")
876 PhdrCmd.HasFilehdr = true;
877 else if (Tok == "PHDRS")
878 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000879 else if (Tok == "FLAGS") {
880 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000881 // Passing 0 for the value of dot is a bit of a hack. It means that
882 // we accept expressions like ".|1".
883 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000884 expect(")");
885 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000886 setError("unexpected header attribute: " + Tok);
887 } while (!Error);
888 }
889}
890
Rui Ueyama717677a2016-02-11 21:17:59 +0000891void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000892 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000893 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000894 expect(")");
895}
896
Rui Ueyama717677a2016-02-11 21:17:59 +0000897void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000898 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000899 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000900 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000901 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000902 BaseCommand *Cmd = readProvideOrAssignment(Tok);
903 if (!Cmd) {
904 if (Tok == "ASSERT")
905 Cmd = new AssertCommand(readAssert());
906 else
907 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000908 }
Rui Ueyama10416562016-08-04 02:03:27 +0000909 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000910 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000911}
912
Rui Ueyama708019c2016-07-24 18:19:40 +0000913static int precedence(StringRef Op) {
914 return StringSwitch<int>(Op)
915 .Case("*", 4)
916 .Case("/", 4)
917 .Case("+", 3)
918 .Case("-", 3)
919 .Case("<", 2)
920 .Case(">", 2)
921 .Case(">=", 2)
922 .Case("<=", 2)
923 .Case("==", 2)
924 .Case("!=", 2)
925 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000926 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000927 .Default(-1);
928}
929
Rui Ueyama10416562016-08-04 02:03:27 +0000930std::vector<StringRef> ScriptParser::readInputFilePatterns() {
931 std::vector<StringRef> V;
932 while (!Error && !skip(")"))
933 V.push_back(next());
934 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000935}
936
Rui Ueyama742c3832016-08-04 22:27:00 +0000937SortKind ScriptParser::readSortKind() {
938 if (skip("SORT") || skip("SORT_BY_NAME"))
939 return SortByName;
940 if (skip("SORT_BY_ALIGNMENT"))
941 return SortByAlignment;
942 return SortNone;
943}
944
George Rimara2496cb2016-08-30 09:46:59 +0000945InputSectionDescription *
946ScriptParser::readInputSectionRules(StringRef FilePattern) {
Rui Ueyama10416562016-08-04 02:03:27 +0000947 auto *Cmd = new InputSectionDescription;
George Rimara2496cb2016-08-30 09:46:59 +0000948 Cmd->FilePattern = FilePattern;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000949 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000950
Rui Ueyama742c3832016-08-04 22:27:00 +0000951 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000952 if (skip("EXCLUDE_FILE")) {
953 expect("(");
954 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000955 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000956 }
George Rimar06598002016-07-28 21:51:30 +0000957
Rui Ueyama742c3832016-08-04 22:27:00 +0000958 // Read SORT().
959 if (SortKind K1 = readSortKind()) {
960 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000961 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000962 if (SortKind K2 = readSortKind()) {
963 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000964 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000965 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000966 expect(")");
967 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000968 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000969 }
George Rimar0702c4e2016-07-29 15:32:46 +0000970 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000971 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000972 }
George Rimar0702c4e2016-07-29 15:32:46 +0000973
Rui Ueyama10416562016-08-04 02:03:27 +0000974 Cmd->SectionPatterns = readInputFilePatterns();
975 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000976}
977
George Rimara2496cb2016-08-30 09:46:59 +0000978InputSectionDescription *
979ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000980 // Input section wildcard can be surrounded by KEEP.
981 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000982 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000983 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000984 StringRef FilePattern = next();
985 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000986 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000987 Opt.KeptSections.insert(Opt.KeptSections.end(),
988 Cmd->SectionPatterns.begin(),
989 Cmd->SectionPatterns.end());
990 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000991 }
George Rimara2496cb2016-08-30 09:46:59 +0000992 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000993}
994
George Rimar03fc0102016-07-28 07:18:23 +0000995void ScriptParser::readSort() {
996 expect("(");
997 expect("CONSTRUCTORS");
998 expect(")");
999}
1000
George Rimareefa7582016-08-04 09:29:31 +00001001Expr ScriptParser::readAssert() {
1002 expect("(");
1003 Expr E = readExpr();
1004 expect(",");
1005 StringRef Msg = next();
1006 expect(")");
1007 return [=](uint64_t Dot) {
1008 uint64_t V = E(Dot);
1009 if (!V)
1010 error(Msg);
1011 return V;
1012 };
1013}
1014
Rui Ueyama10416562016-08-04 02:03:27 +00001015OutputSectionCommand *
1016ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001017 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001018
1019 // Read an address expression.
1020 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1021 if (peek() != ":")
1022 Cmd->AddrExpr = readExpr();
1023
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001024 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001025
George Rimar8ceadb32016-08-17 07:44:19 +00001026 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001027 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001028 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001029 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001030 if (skip("SUBALIGN"))
1031 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001032
Davide Italiano246f6812016-07-22 03:36:24 +00001033 // Parse constraints.
1034 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001035 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001036 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001037 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001038 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001039
Rui Ueyama025d59b2016-02-02 20:27:59 +00001040 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001041 StringRef Tok = next();
1042 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1043 Cmd->Commands.emplace_back(Assignment);
1044 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001045 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001046 else if (peek() == "(")
1047 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001048 else
1049 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001050 }
George Rimar076fe152016-07-21 06:43:01 +00001051 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001052 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +00001053 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001054}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001055
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001056// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1057// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1058//
1059// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1060// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1061// as 32-bit big-endian values. We will do the same as ld.gold does
1062// because it's simpler than what ld.bfd does.
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001063std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001064 if (!peek().startswith("="))
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001065 return {};
Rui Ueyama965827d2016-08-03 23:25:15 +00001066
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001067 StringRef Tok = next();
Rui Ueyama965827d2016-08-03 23:25:15 +00001068 uint32_t V;
1069 if (Tok.substr(1).getAsInteger(0, V)) {
1070 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001071 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001072 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001073 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001074}
1075
Petr Hoseka35e39c2016-08-16 01:11:16 +00001076SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001077 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001078 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001079 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001080 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001081 expect(")");
1082 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001083 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001084}
1085
Eugene Leviantceabe802016-08-11 07:56:43 +00001086SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1087 SymbolAssignment *Cmd = nullptr;
1088 if (peek() == "=" || peek() == "+=") {
1089 Cmd = readAssignment(Tok);
1090 expect(";");
1091 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001092 Cmd = readProvideHidden(true, false);
1093 } else if (Tok == "HIDDEN") {
1094 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001095 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001096 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001097 }
1098 return Cmd;
1099}
1100
George Rimar30835ea2016-07-28 21:08:56 +00001101static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1102 if (S == ".")
1103 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001104
George Rimara9c5a522016-07-26 18:18:58 +00001105 switch (Config->EKind) {
1106 case ELF32LEKind:
1107 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1108 return B->getVA<ELF32LE>();
1109 break;
1110 case ELF32BEKind:
1111 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1112 return B->getVA<ELF32BE>();
1113 break;
1114 case ELF64LEKind:
1115 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1116 return B->getVA<ELF64LE>();
1117 break;
1118 case ELF64BEKind:
1119 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1120 return B->getVA<ELF64BE>();
1121 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001122 default:
George Rimarb567b622016-07-26 18:46:13 +00001123 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001124 }
1125 error("symbol not found: " + S);
1126 return 0;
1127}
1128
George Rimar9e694502016-07-29 16:18:47 +00001129static uint64_t getSectionSize(StringRef Name) {
1130 switch (Config->EKind) {
1131 case ELF32LEKind:
1132 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1133 case ELF32BEKind:
1134 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1135 case ELF64LEKind:
1136 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1137 case ELF64BEKind:
1138 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1139 default:
1140 llvm_unreachable("unsupported target");
1141 }
George Rimar9e694502016-07-29 16:18:47 +00001142}
1143
George Rimar96659df2016-08-30 09:54:01 +00001144static uint64_t getSectionAddress(StringRef Name) {
1145 switch (Config->EKind) {
1146 case ELF32LEKind:
1147 return Script<ELF32LE>::X->getOutputSectionAddress(Name);
1148 case ELF32BEKind:
1149 return Script<ELF32BE>::X->getOutputSectionAddress(Name);
1150 case ELF64LEKind:
1151 return Script<ELF64LE>::X->getOutputSectionAddress(Name);
1152 case ELF64BEKind:
1153 return Script<ELF64BE>::X->getOutputSectionAddress(Name);
1154 default:
1155 llvm_unreachable("unsupported target");
1156 }
1157}
1158
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001159static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001160 switch (Config->EKind) {
1161 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001162 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001163 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001164 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001165 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001166 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001167 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001168 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001169 default:
1170 llvm_unreachable("unsupported target");
1171 }
1172}
1173
George Rimar30835ea2016-07-28 21:08:56 +00001174SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1175 StringRef Op = next();
1176 assert(Op == "=" || Op == "+=");
1177 Expr E = readExpr();
1178 if (Op == "+=")
1179 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001180 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001181}
1182
1183// This is an operator-precedence parser to parse a linker
1184// script expression.
1185Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1186
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001187static Expr combine(StringRef Op, Expr L, Expr R) {
1188 if (Op == "*")
1189 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1190 if (Op == "/") {
1191 return [=](uint64_t Dot) -> uint64_t {
1192 uint64_t RHS = R(Dot);
1193 if (RHS == 0) {
1194 error("division by zero");
1195 return 0;
1196 }
1197 return L(Dot) / RHS;
1198 };
1199 }
1200 if (Op == "+")
1201 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1202 if (Op == "-")
1203 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1204 if (Op == "<")
1205 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1206 if (Op == ">")
1207 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1208 if (Op == ">=")
1209 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1210 if (Op == "<=")
1211 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1212 if (Op == "==")
1213 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1214 if (Op == "!=")
1215 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1216 if (Op == "&")
1217 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001218 if (Op == "|")
1219 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001220 llvm_unreachable("invalid operator");
1221}
1222
Rui Ueyama708019c2016-07-24 18:19:40 +00001223// This is a part of the operator-precedence parser. This function
1224// assumes that the remaining token stream starts with an operator.
1225Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1226 while (!atEOF() && !Error) {
1227 // Read an operator and an expression.
1228 StringRef Op1 = peek();
1229 if (Op1 == "?")
1230 return readTernary(Lhs);
1231 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001232 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001233 next();
1234 Expr Rhs = readPrimary();
1235
1236 // Evaluate the remaining part of the expression first if the
1237 // next operator has greater precedence than the previous one.
1238 // For example, if we have read "+" and "3", and if the next
1239 // operator is "*", then we'll evaluate 3 * ... part first.
1240 while (!atEOF()) {
1241 StringRef Op2 = peek();
1242 if (precedence(Op2) <= precedence(Op1))
1243 break;
1244 Rhs = readExpr1(Rhs, precedence(Op2));
1245 }
1246
1247 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001248 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001249 return Lhs;
1250}
1251
1252uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001253 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001254 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001255 if (S == "MAXPAGESIZE")
1256 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001257 error("unknown constant: " + S);
1258 return 0;
1259}
1260
1261Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001262 if (peek() == "(")
1263 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001264
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001265 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001266
1267 // Built-in functions are parsed here.
1268 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001269 if (Tok == "ADDR") {
1270 expect("(");
1271 StringRef Name = next();
1272 expect(")");
1273 return [=](uint64_t Dot) { return getSectionAddress(Name); };
1274 }
George Rimareefa7582016-08-04 09:29:31 +00001275 if (Tok == "ASSERT")
1276 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001277 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001278 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001279 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1280 }
1281 if (Tok == "CONSTANT") {
1282 expect("(");
1283 StringRef Tok = next();
1284 expect(")");
1285 return [=](uint64_t Dot) { return getConstant(Tok); };
1286 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001287 if (Tok == "SEGMENT_START") {
1288 expect("(");
1289 next();
1290 expect(",");
1291 uint64_t Val;
1292 next().getAsInteger(0, Val);
1293 expect(")");
1294 return [=](uint64_t Dot) { return Val; };
1295 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001296 if (Tok == "DATA_SEGMENT_ALIGN") {
1297 expect("(");
1298 Expr E = readExpr();
1299 expect(",");
1300 readExpr();
1301 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001302 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001303 }
1304 if (Tok == "DATA_SEGMENT_END") {
1305 expect("(");
1306 expect(".");
1307 expect(")");
1308 return [](uint64_t Dot) { return Dot; };
1309 }
George Rimar276b4e62016-07-26 17:58:44 +00001310 // GNU linkers implements more complicated logic to handle
1311 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1312 // the next page boundary for simplicity.
1313 if (Tok == "DATA_SEGMENT_RELRO_END") {
1314 expect("(");
1315 next();
1316 expect(",");
1317 readExpr();
1318 expect(")");
1319 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1320 }
George Rimar9e694502016-07-29 16:18:47 +00001321 if (Tok == "SIZEOF") {
1322 expect("(");
1323 StringRef Name = next();
1324 expect(")");
1325 return [=](uint64_t Dot) { return getSectionSize(Name); };
1326 }
George Rimare32a3592016-08-10 07:59:34 +00001327 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001328 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001329
George Rimara9c5a522016-07-26 18:18:58 +00001330 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001331 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001332 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001333 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001334 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001335 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001336 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001337 return [=](uint64_t Dot) { return V; };
1338}
1339
1340Expr ScriptParser::readTernary(Expr Cond) {
1341 next();
1342 Expr L = readExpr();
1343 expect(":");
1344 Expr R = readExpr();
1345 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1346}
1347
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001348Expr ScriptParser::readParenExpr() {
1349 expect("(");
1350 Expr E = readExpr();
1351 expect(")");
1352 return E;
1353}
1354
Eugene Leviantbbe38602016-07-19 09:25:43 +00001355std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1356 std::vector<StringRef> Phdrs;
1357 while (!Error && peek().startswith(":")) {
1358 StringRef Tok = next();
1359 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1360 if (Tok.empty()) {
1361 setError("section header name is empty");
1362 break;
1363 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001364 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001365 }
1366 return Phdrs;
1367}
1368
1369unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001370 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001371 unsigned Ret = StringSwitch<unsigned>(Tok)
1372 .Case("PT_NULL", PT_NULL)
1373 .Case("PT_LOAD", PT_LOAD)
1374 .Case("PT_DYNAMIC", PT_DYNAMIC)
1375 .Case("PT_INTERP", PT_INTERP)
1376 .Case("PT_NOTE", PT_NOTE)
1377 .Case("PT_SHLIB", PT_SHLIB)
1378 .Case("PT_PHDR", PT_PHDR)
1379 .Case("PT_TLS", PT_TLS)
1380 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1381 .Case("PT_GNU_STACK", PT_GNU_STACK)
1382 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1383 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001384
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001385 if (Ret == (unsigned)-1) {
1386 setError("invalid program header type: " + Tok);
1387 return PT_NULL;
1388 }
1389 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001390}
1391
Rui Ueyama95769b42016-08-31 20:03:54 +00001392void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001393 // Identifiers start at 2 because 0 and 1 are reserved
1394 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1395 size_t VersionId = Config->VersionDefinitions.size() + 2;
1396 Config->VersionDefinitions.push_back({VerStr, VersionId});
1397
1398 if (skip("global:") || peek() != "local:")
1399 readGlobal(VerStr);
1400 if (skip("local:"))
1401 readLocal();
1402 expect("}");
1403
1404 // Each version may have a parent version. For example, "Ver2" defined as
1405 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1406 // version hierarchy is, probably against your instinct, purely for human; the
1407 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1408 if (!VerStr.empty() && peek() != ";")
1409 next();
1410 expect(";");
1411}
1412
1413void ScriptParser::readLocal() {
1414 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1415 expect("*");
1416 expect(";");
1417}
1418
1419void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1420 expect("C++");
1421 expect("{");
1422
1423 for (;;) {
1424 if (peek() == "}" || Error)
1425 break;
1426 Globals->push_back({next(), true});
1427 expect(";");
1428 }
1429
1430 expect("}");
1431 expect(";");
1432}
1433
1434void ScriptParser::readGlobal(StringRef VerStr) {
1435 std::vector<SymbolVersion> *Globals;
1436 if (VerStr.empty())
1437 Globals = &Config->VersionScriptGlobals;
1438 else
1439 Globals = &Config->VersionDefinitions.back().Globals;
1440
1441 for (;;) {
1442 if (skip("extern"))
1443 readExtern(Globals);
1444
1445 StringRef Cur = peek();
1446 if (Cur == "}" || Cur == "local:" || Error)
1447 return;
1448 next();
1449 Globals->push_back({Cur, false});
1450 expect(";");
1451 }
1452}
1453
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001454static bool isUnderSysroot(StringRef Path) {
1455 if (Config->Sysroot == "")
1456 return false;
1457 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1458 if (sys::fs::equivalent(Config->Sysroot, Path))
1459 return true;
1460 return false;
1461}
1462
Rui Ueyama07320e42016-04-20 20:13:41 +00001463void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001464 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001465 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1466}
1467
1468void elf::readVersionScript(MemoryBufferRef MB) {
1469 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001470}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001471
Rui Ueyama07320e42016-04-20 20:13:41 +00001472template class elf::LinkerScript<ELF32LE>;
1473template class elf::LinkerScript<ELF32BE>;
1474template class elf::LinkerScript<ELF64LE>;
1475template class elf::LinkerScript<ELF64BE>;