blob: 9403233018560e844de9766cc1fd175ae022080e [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();
656
Rui Ueyama113cdec2016-07-24 23:05:57 +0000657 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000658 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000659 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000660 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000661 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000662 std::vector<StringRef> readInputFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000663 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000664 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000665 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000666 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000667 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000668 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000669 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000670
671 Expr readExpr();
672 Expr readExpr1(Expr Lhs, int MinPrec);
673 Expr readPrimary();
674 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000675 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000676
George Rimar20b65982016-08-31 09:08:26 +0000677 // For parsing version script.
678 void readExtern(std::vector<SymbolVersion> *Globals);
679 void readVersion(StringRef VerStr);
680 void readGlobal(StringRef VerStr);
681 void readLocal();
682
George Rimarc3794e52016-02-24 09:21:47 +0000683 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000684 ScriptConfiguration &Opt = *ScriptConfig;
685 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000686 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000687};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000688
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000689const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000690 {"ENTRY", &ScriptParser::readEntry},
691 {"EXTERN", &ScriptParser::readExtern},
692 {"GROUP", &ScriptParser::readGroup},
693 {"INCLUDE", &ScriptParser::readInclude},
694 {"INPUT", &ScriptParser::readGroup},
695 {"OUTPUT", &ScriptParser::readOutput},
696 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
697 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000698 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000699 {"SEARCH_DIR", &ScriptParser::readSearchDir},
700 {"SECTIONS", &ScriptParser::readSections},
701 {";", &ScriptParser::readNothing}};
702
George Rimar20b65982016-08-31 09:08:26 +0000703void ScriptParser::readVersionScript() {
704 StringRef Msg = "anonymous version definition is used in "
705 "combination with other version definitions";
706 if (skip("{")) {
707 readVersion("");
708 if (!atEOF())
709 setError(Msg);
710 return;
711 }
712
713 while (!atEOF() && !Error) {
714 StringRef VerStr = next();
715 if (VerStr == "{") {
716 setError(Msg);
717 return;
718 }
719 expect("{");
720 readVersion(VerStr);
721 }
722}
723
724void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000725 while (!atEOF()) {
726 StringRef Tok = next();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000727 if (Handler Fn = Cmd.lookup(Tok)) {
George Rimarc3794e52016-02-24 09:21:47 +0000728 (this->*Fn)();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000729 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
730 if (Opt.HasContents)
731 Opt.Commands.emplace_back(Cmd);
732 else
733 Opt.Assignments.emplace_back(Cmd);
734 } else {
George Rimar57610422016-03-11 14:43:02 +0000735 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000736 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000737 }
738}
739
Rui Ueyama717677a2016-02-11 21:17:59 +0000740void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000741 if (IsUnderSysroot && S.startswith("/")) {
742 SmallString<128> Path;
743 (Config->Sysroot + S).toStringRef(Path);
744 if (sys::fs::exists(Path)) {
745 Driver->addFile(Saver.save(Path.str()));
746 return;
747 }
748 }
749
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000750 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000751 Driver->addFile(S);
752 } else if (S.startswith("=")) {
753 if (Config->Sysroot.empty())
754 Driver->addFile(S.substr(1));
755 else
756 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
757 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000758 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000759 } else if (sys::fs::exists(S)) {
760 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000761 } else {
762 std::string Path = findFromSearchPaths(S);
763 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000764 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000765 else
766 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000767 }
768}
769
Rui Ueyama717677a2016-02-11 21:17:59 +0000770void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000771 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000772 bool Orig = Config->AsNeeded;
773 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000774 while (!Error && !skip(")"))
775 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000776 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000777}
778
Rui Ueyama717677a2016-02-11 21:17:59 +0000779void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000780 // -e <symbol> takes predecence over ENTRY(<symbol>).
781 expect("(");
782 StringRef Tok = next();
783 if (Config->Entry.empty())
784 Config->Entry = Tok;
785 expect(")");
786}
787
Rui Ueyama717677a2016-02-11 21:17:59 +0000788void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000789 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000790 while (!Error && !skip(")"))
791 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000792}
793
Rui Ueyama717677a2016-02-11 21:17:59 +0000794void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000795 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000796 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000797 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000798 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000799 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000800 else
801 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000802 }
803}
804
Rui Ueyama717677a2016-02-11 21:17:59 +0000805void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000806 StringRef Tok = next();
807 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000808 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000809 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000810 return;
811 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000812 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000813 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
814 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000815 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000816}
817
Rui Ueyama717677a2016-02-11 21:17:59 +0000818void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000819 // -o <file> takes predecence over OUTPUT(<file>).
820 expect("(");
821 StringRef Tok = next();
822 if (Config->OutputFile.empty())
823 Config->OutputFile = Tok;
824 expect(")");
825}
826
Rui Ueyama717677a2016-02-11 21:17:59 +0000827void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000828 // Error checking only for now.
829 expect("(");
830 next();
831 expect(")");
832}
833
Rui Ueyama717677a2016-02-11 21:17:59 +0000834void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000835 // Error checking only for now.
836 expect("(");
837 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000838 StringRef Tok = next();
839 if (Tok == ")")
840 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000841 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000842 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000843 return;
844 }
Davide Italiano6836c612015-10-12 21:08:41 +0000845 next();
846 expect(",");
847 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000848 expect(")");
849}
850
Eugene Leviantbbe38602016-07-19 09:25:43 +0000851void ScriptParser::readPhdrs() {
852 expect("{");
853 while (!Error && !skip("}")) {
854 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000855 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000856 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
857
858 PhdrCmd.Type = readPhdrType();
859 do {
860 Tok = next();
861 if (Tok == ";")
862 break;
863 if (Tok == "FILEHDR")
864 PhdrCmd.HasFilehdr = true;
865 else if (Tok == "PHDRS")
866 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000867 else if (Tok == "FLAGS") {
868 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000869 // Passing 0 for the value of dot is a bit of a hack. It means that
870 // we accept expressions like ".|1".
871 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000872 expect(")");
873 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000874 setError("unexpected header attribute: " + Tok);
875 } while (!Error);
876 }
877}
878
Rui Ueyama717677a2016-02-11 21:17:59 +0000879void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000880 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000881 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000882 expect(")");
883}
884
Rui Ueyama717677a2016-02-11 21:17:59 +0000885void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000886 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000887 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000888 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000889 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000890 BaseCommand *Cmd = readProvideOrAssignment(Tok);
891 if (!Cmd) {
892 if (Tok == "ASSERT")
893 Cmd = new AssertCommand(readAssert());
894 else
895 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000896 }
Rui Ueyama10416562016-08-04 02:03:27 +0000897 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000898 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000899}
900
Rui Ueyama708019c2016-07-24 18:19:40 +0000901static int precedence(StringRef Op) {
902 return StringSwitch<int>(Op)
903 .Case("*", 4)
904 .Case("/", 4)
905 .Case("+", 3)
906 .Case("-", 3)
907 .Case("<", 2)
908 .Case(">", 2)
909 .Case(">=", 2)
910 .Case("<=", 2)
911 .Case("==", 2)
912 .Case("!=", 2)
913 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000914 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000915 .Default(-1);
916}
917
Rui Ueyama10416562016-08-04 02:03:27 +0000918std::vector<StringRef> ScriptParser::readInputFilePatterns() {
919 std::vector<StringRef> V;
920 while (!Error && !skip(")"))
921 V.push_back(next());
922 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000923}
924
Rui Ueyama742c3832016-08-04 22:27:00 +0000925SortKind ScriptParser::readSortKind() {
926 if (skip("SORT") || skip("SORT_BY_NAME"))
927 return SortByName;
928 if (skip("SORT_BY_ALIGNMENT"))
929 return SortByAlignment;
930 return SortNone;
931}
932
George Rimara2496cb2016-08-30 09:46:59 +0000933InputSectionDescription *
934ScriptParser::readInputSectionRules(StringRef FilePattern) {
Rui Ueyama10416562016-08-04 02:03:27 +0000935 auto *Cmd = new InputSectionDescription;
George Rimara2496cb2016-08-30 09:46:59 +0000936 Cmd->FilePattern = FilePattern;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000937 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000938
Rui Ueyama742c3832016-08-04 22:27:00 +0000939 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000940 if (skip("EXCLUDE_FILE")) {
941 expect("(");
942 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000943 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000944 }
George Rimar06598002016-07-28 21:51:30 +0000945
Rui Ueyama742c3832016-08-04 22:27:00 +0000946 // Read SORT().
947 if (SortKind K1 = readSortKind()) {
948 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000949 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000950 if (SortKind K2 = readSortKind()) {
951 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000952 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000953 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000954 expect(")");
955 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000956 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000957 }
George Rimar0702c4e2016-07-29 15:32:46 +0000958 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000959 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000960 }
George Rimar0702c4e2016-07-29 15:32:46 +0000961
Rui Ueyama10416562016-08-04 02:03:27 +0000962 Cmd->SectionPatterns = readInputFilePatterns();
963 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000964}
965
George Rimara2496cb2016-08-30 09:46:59 +0000966InputSectionDescription *
967ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000968 // Input section wildcard can be surrounded by KEEP.
969 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000970 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000971 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000972 StringRef FilePattern = next();
973 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000974 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000975 Opt.KeptSections.insert(Opt.KeptSections.end(),
976 Cmd->SectionPatterns.begin(),
977 Cmd->SectionPatterns.end());
978 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000979 }
George Rimara2496cb2016-08-30 09:46:59 +0000980 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000981}
982
George Rimar03fc0102016-07-28 07:18:23 +0000983void ScriptParser::readSort() {
984 expect("(");
985 expect("CONSTRUCTORS");
986 expect(")");
987}
988
George Rimareefa7582016-08-04 09:29:31 +0000989Expr ScriptParser::readAssert() {
990 expect("(");
991 Expr E = readExpr();
992 expect(",");
993 StringRef Msg = next();
994 expect(")");
995 return [=](uint64_t Dot) {
996 uint64_t V = E(Dot);
997 if (!V)
998 error(Msg);
999 return V;
1000 };
1001}
1002
Rui Ueyama10416562016-08-04 02:03:27 +00001003OutputSectionCommand *
1004ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001005 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001006
1007 // Read an address expression.
1008 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1009 if (peek() != ":")
1010 Cmd->AddrExpr = readExpr();
1011
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001012 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001013
George Rimar8ceadb32016-08-17 07:44:19 +00001014 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001015 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001016 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001017 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001018 if (skip("SUBALIGN"))
1019 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001020
Davide Italiano246f6812016-07-22 03:36:24 +00001021 // Parse constraints.
1022 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001023 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001024 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001025 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001026 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001027
Rui Ueyama025d59b2016-02-02 20:27:59 +00001028 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001029 StringRef Tok = next();
1030 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1031 Cmd->Commands.emplace_back(Assignment);
1032 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001033 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001034 else if (peek() == "(")
1035 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001036 else
1037 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001038 }
George Rimar076fe152016-07-21 06:43:01 +00001039 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001040 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +00001041 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001042}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001043
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001044// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1045// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1046//
1047// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1048// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1049// as 32-bit big-endian values. We will do the same as ld.gold does
1050// because it's simpler than what ld.bfd does.
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001051std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001052 if (!peek().startswith("="))
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001053 return {};
Rui Ueyama965827d2016-08-03 23:25:15 +00001054
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001055 StringRef Tok = next();
Rui Ueyama965827d2016-08-03 23:25:15 +00001056 uint32_t V;
1057 if (Tok.substr(1).getAsInteger(0, V)) {
1058 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001059 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001060 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001061 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001062}
1063
Petr Hoseka35e39c2016-08-16 01:11:16 +00001064SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001065 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001066 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001067 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001068 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001069 expect(")");
1070 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001071 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001072}
1073
Eugene Leviantceabe802016-08-11 07:56:43 +00001074SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1075 SymbolAssignment *Cmd = nullptr;
1076 if (peek() == "=" || peek() == "+=") {
1077 Cmd = readAssignment(Tok);
1078 expect(";");
1079 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001080 Cmd = readProvideHidden(true, false);
1081 } else if (Tok == "HIDDEN") {
1082 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001083 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001084 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001085 }
1086 return Cmd;
1087}
1088
George Rimar30835ea2016-07-28 21:08:56 +00001089static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1090 if (S == ".")
1091 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001092
George Rimara9c5a522016-07-26 18:18:58 +00001093 switch (Config->EKind) {
1094 case ELF32LEKind:
1095 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1096 return B->getVA<ELF32LE>();
1097 break;
1098 case ELF32BEKind:
1099 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1100 return B->getVA<ELF32BE>();
1101 break;
1102 case ELF64LEKind:
1103 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1104 return B->getVA<ELF64LE>();
1105 break;
1106 case ELF64BEKind:
1107 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1108 return B->getVA<ELF64BE>();
1109 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001110 default:
George Rimarb567b622016-07-26 18:46:13 +00001111 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001112 }
1113 error("symbol not found: " + S);
1114 return 0;
1115}
1116
George Rimar9e694502016-07-29 16:18:47 +00001117static uint64_t getSectionSize(StringRef Name) {
1118 switch (Config->EKind) {
1119 case ELF32LEKind:
1120 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1121 case ELF32BEKind:
1122 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1123 case ELF64LEKind:
1124 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1125 case ELF64BEKind:
1126 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1127 default:
1128 llvm_unreachable("unsupported target");
1129 }
George Rimar9e694502016-07-29 16:18:47 +00001130}
1131
George Rimar96659df2016-08-30 09:54:01 +00001132static uint64_t getSectionAddress(StringRef Name) {
1133 switch (Config->EKind) {
1134 case ELF32LEKind:
1135 return Script<ELF32LE>::X->getOutputSectionAddress(Name);
1136 case ELF32BEKind:
1137 return Script<ELF32BE>::X->getOutputSectionAddress(Name);
1138 case ELF64LEKind:
1139 return Script<ELF64LE>::X->getOutputSectionAddress(Name);
1140 case ELF64BEKind:
1141 return Script<ELF64BE>::X->getOutputSectionAddress(Name);
1142 default:
1143 llvm_unreachable("unsupported target");
1144 }
1145}
1146
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001147static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001148 switch (Config->EKind) {
1149 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001150 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001151 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001152 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001153 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001154 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001155 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001156 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001157 default:
1158 llvm_unreachable("unsupported target");
1159 }
1160}
1161
George Rimar30835ea2016-07-28 21:08:56 +00001162SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1163 StringRef Op = next();
1164 assert(Op == "=" || Op == "+=");
1165 Expr E = readExpr();
1166 if (Op == "+=")
1167 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001168 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001169}
1170
1171// This is an operator-precedence parser to parse a linker
1172// script expression.
1173Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1174
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001175static Expr combine(StringRef Op, Expr L, Expr R) {
1176 if (Op == "*")
1177 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1178 if (Op == "/") {
1179 return [=](uint64_t Dot) -> uint64_t {
1180 uint64_t RHS = R(Dot);
1181 if (RHS == 0) {
1182 error("division by zero");
1183 return 0;
1184 }
1185 return L(Dot) / RHS;
1186 };
1187 }
1188 if (Op == "+")
1189 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1190 if (Op == "-")
1191 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1192 if (Op == "<")
1193 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1194 if (Op == ">")
1195 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1196 if (Op == ">=")
1197 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1198 if (Op == "<=")
1199 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
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); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001206 if (Op == "|")
1207 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001208 llvm_unreachable("invalid operator");
1209}
1210
Rui Ueyama708019c2016-07-24 18:19:40 +00001211// This is a part of the operator-precedence parser. This function
1212// assumes that the remaining token stream starts with an operator.
1213Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1214 while (!atEOF() && !Error) {
1215 // Read an operator and an expression.
1216 StringRef Op1 = peek();
1217 if (Op1 == "?")
1218 return readTernary(Lhs);
1219 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001220 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001221 next();
1222 Expr Rhs = readPrimary();
1223
1224 // Evaluate the remaining part of the expression first if the
1225 // next operator has greater precedence than the previous one.
1226 // For example, if we have read "+" and "3", and if the next
1227 // operator is "*", then we'll evaluate 3 * ... part first.
1228 while (!atEOF()) {
1229 StringRef Op2 = peek();
1230 if (precedence(Op2) <= precedence(Op1))
1231 break;
1232 Rhs = readExpr1(Rhs, precedence(Op2));
1233 }
1234
1235 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001236 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001237 return Lhs;
1238}
1239
1240uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001241 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001242 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001243 if (S == "MAXPAGESIZE")
1244 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001245 error("unknown constant: " + S);
1246 return 0;
1247}
1248
1249Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001250 if (peek() == "(")
1251 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001252
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001253 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001254
1255 // Built-in functions are parsed here.
1256 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001257 if (Tok == "ADDR") {
1258 expect("(");
1259 StringRef Name = next();
1260 expect(")");
1261 return [=](uint64_t Dot) { return getSectionAddress(Name); };
1262 }
George Rimareefa7582016-08-04 09:29:31 +00001263 if (Tok == "ASSERT")
1264 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001265 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001266 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001267 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1268 }
1269 if (Tok == "CONSTANT") {
1270 expect("(");
1271 StringRef Tok = next();
1272 expect(")");
1273 return [=](uint64_t Dot) { return getConstant(Tok); };
1274 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001275 if (Tok == "SEGMENT_START") {
1276 expect("(");
1277 next();
1278 expect(",");
1279 uint64_t Val;
1280 next().getAsInteger(0, Val);
1281 expect(")");
1282 return [=](uint64_t Dot) { return Val; };
1283 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001284 if (Tok == "DATA_SEGMENT_ALIGN") {
1285 expect("(");
1286 Expr E = readExpr();
1287 expect(",");
1288 readExpr();
1289 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001290 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001291 }
1292 if (Tok == "DATA_SEGMENT_END") {
1293 expect("(");
1294 expect(".");
1295 expect(")");
1296 return [](uint64_t Dot) { return Dot; };
1297 }
George Rimar276b4e62016-07-26 17:58:44 +00001298 // GNU linkers implements more complicated logic to handle
1299 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1300 // the next page boundary for simplicity.
1301 if (Tok == "DATA_SEGMENT_RELRO_END") {
1302 expect("(");
1303 next();
1304 expect(",");
1305 readExpr();
1306 expect(")");
1307 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1308 }
George Rimar9e694502016-07-29 16:18:47 +00001309 if (Tok == "SIZEOF") {
1310 expect("(");
1311 StringRef Name = next();
1312 expect(")");
1313 return [=](uint64_t Dot) { return getSectionSize(Name); };
1314 }
George Rimare32a3592016-08-10 07:59:34 +00001315 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001316 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001317
George Rimara9c5a522016-07-26 18:18:58 +00001318 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001319 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001320 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001321 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001322 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001323 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001324 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001325 return [=](uint64_t Dot) { return V; };
1326}
1327
1328Expr ScriptParser::readTernary(Expr Cond) {
1329 next();
1330 Expr L = readExpr();
1331 expect(":");
1332 Expr R = readExpr();
1333 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1334}
1335
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001336Expr ScriptParser::readParenExpr() {
1337 expect("(");
1338 Expr E = readExpr();
1339 expect(")");
1340 return E;
1341}
1342
Eugene Leviantbbe38602016-07-19 09:25:43 +00001343std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1344 std::vector<StringRef> Phdrs;
1345 while (!Error && peek().startswith(":")) {
1346 StringRef Tok = next();
1347 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1348 if (Tok.empty()) {
1349 setError("section header name is empty");
1350 break;
1351 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001352 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001353 }
1354 return Phdrs;
1355}
1356
1357unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001358 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001359 unsigned Ret = StringSwitch<unsigned>(Tok)
1360 .Case("PT_NULL", PT_NULL)
1361 .Case("PT_LOAD", PT_LOAD)
1362 .Case("PT_DYNAMIC", PT_DYNAMIC)
1363 .Case("PT_INTERP", PT_INTERP)
1364 .Case("PT_NOTE", PT_NOTE)
1365 .Case("PT_SHLIB", PT_SHLIB)
1366 .Case("PT_PHDR", PT_PHDR)
1367 .Case("PT_TLS", PT_TLS)
1368 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1369 .Case("PT_GNU_STACK", PT_GNU_STACK)
1370 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1371 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001372
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001373 if (Ret == (unsigned)-1) {
1374 setError("invalid program header type: " + Tok);
1375 return PT_NULL;
1376 }
1377 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001378}
1379
George Rimar20b65982016-08-31 09:08:26 +00001380void ScriptParser::readVersion(StringRef VerStr) {
1381 // Identifiers start at 2 because 0 and 1 are reserved
1382 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1383 size_t VersionId = Config->VersionDefinitions.size() + 2;
1384 Config->VersionDefinitions.push_back({VerStr, VersionId});
1385
1386 if (skip("global:") || peek() != "local:")
1387 readGlobal(VerStr);
1388 if (skip("local:"))
1389 readLocal();
1390 expect("}");
1391
1392 // Each version may have a parent version. For example, "Ver2" defined as
1393 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1394 // version hierarchy is, probably against your instinct, purely for human; the
1395 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1396 if (!VerStr.empty() && peek() != ";")
1397 next();
1398 expect(";");
1399}
1400
1401void ScriptParser::readLocal() {
1402 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1403 expect("*");
1404 expect(";");
1405}
1406
1407void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1408 expect("C++");
1409 expect("{");
1410
1411 for (;;) {
1412 if (peek() == "}" || Error)
1413 break;
1414 Globals->push_back({next(), true});
1415 expect(";");
1416 }
1417
1418 expect("}");
1419 expect(";");
1420}
1421
1422void ScriptParser::readGlobal(StringRef VerStr) {
1423 std::vector<SymbolVersion> *Globals;
1424 if (VerStr.empty())
1425 Globals = &Config->VersionScriptGlobals;
1426 else
1427 Globals = &Config->VersionDefinitions.back().Globals;
1428
1429 for (;;) {
1430 if (skip("extern"))
1431 readExtern(Globals);
1432
1433 StringRef Cur = peek();
1434 if (Cur == "}" || Cur == "local:" || Error)
1435 return;
1436 next();
1437 Globals->push_back({Cur, false});
1438 expect(";");
1439 }
1440}
1441
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001442static bool isUnderSysroot(StringRef Path) {
1443 if (Config->Sysroot == "")
1444 return false;
1445 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1446 if (sys::fs::equivalent(Config->Sysroot, Path))
1447 return true;
1448 return false;
1449}
1450
Rui Ueyama07320e42016-04-20 20:13:41 +00001451void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001452 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001453 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1454}
1455
1456void elf::readVersionScript(MemoryBufferRef MB) {
1457 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001458}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001459
Rui Ueyama07320e42016-04-20 20:13:41 +00001460template class elf::LinkerScript<ELF32LE>;
1461template class elf::LinkerScript<ELF32BE>;
1462template class elf::LinkerScript<ELF64LE>;
1463template class elf::LinkerScript<ELF64BE>;