blob: 5fc7e35ecacb31bb59804e0332f93739e43229f1 [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
53template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000054static void addSynthetic(SymbolAssignment *Cmd,
55 OutputSectionBase<ELFT> *Section) {
56 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(Cmd->Name, Section, 0);
57 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
58 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000059}
60
Rui Ueyama16024212016-08-11 23:22:52 +000061// If a symbol was in PROVIDE(), we need to define it only when
62// it is an undefined symbol.
63template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
64 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000065 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000066 if (!Cmd->Provide)
67 return true;
68 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
69 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000070}
71
George Rimar076fe152016-07-21 06:43:01 +000072bool SymbolAssignment::classof(const BaseCommand *C) {
73 return C->Kind == AssignmentKind;
74}
75
76bool OutputSectionCommand::classof(const BaseCommand *C) {
77 return C->Kind == OutputSectionKind;
78}
79
George Rimareea31142016-07-21 14:26:59 +000080bool InputSectionDescription::classof(const BaseCommand *C) {
81 return C->Kind == InputSectionKind;
82}
83
George Rimareefa7582016-08-04 09:29:31 +000084bool AssertCommand::classof(const BaseCommand *C) {
85 return C->Kind == AssertKind;
86}
87
Rui Ueyama36a153c2016-07-23 14:09:58 +000088template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000089 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000090}
91
Rui Ueyama07320e42016-04-20 20:13:41 +000092template <class ELFT>
93bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000094 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000095 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000096 return true;
97 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000098}
99
Rui Ueyama63dc6502016-07-25 22:41:42 +0000100static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
101 for (StringRef Pat : Patterns)
102 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000103 return true;
104 return false;
105}
106
George Rimar06598002016-07-28 21:51:30 +0000107static bool fileMatches(const InputSectionDescription *Desc,
108 StringRef Filename) {
109 if (!globMatch(Desc->FilePattern, Filename))
110 return false;
111 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
112}
113
Rui Ueyama6b274812016-07-25 22:51:07 +0000114// Returns input sections filtered by given glob patterns.
115template <class ELFT>
116std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000117LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000118 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000119 std::vector<InputSectionBase<ELFT> *> Ret;
120 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000121 Symtab<ELFT>::X->getObjectFiles()) {
122 if (fileMatches(I, sys::path::filename(F->getName())))
123 for (InputSectionBase<ELFT> *S : F->getSections())
124 if (!isDiscarded(S) && !S->OutSec &&
125 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000126 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000127 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000128
129 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000130 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000131
Rui Ueyama6b274812016-07-25 22:51:07 +0000132 return Ret;
133}
134
Eugene Leviantceabe802016-08-11 07:56:43 +0000135namespace {
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000136
137// You can define new symbols using linker scripts. For example,
138// ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
139// foo just after abc.o's text section contents. This class is to
140// handle such symbol definitions.
141//
142// In order to handle scripts like the above one, we want to
143// keep symbol definitions in output sections. Because output sections
144// can contain only input sections, we wrap symbol definitions
145// with dummy input sections. This class serves that purpose.
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000146template <class ELFT> class LayoutInputSection : public InputSectionBase<ELFT> {
Eugene Leviantceabe802016-08-11 07:56:43 +0000147public:
148 LayoutInputSection(SymbolAssignment *Cmd);
149 static bool classof(const InputSectionBase<ELFT> *S);
150 SymbolAssignment *Cmd;
151
152private:
153 typename ELFT::Shdr Hdr;
154};
155
156// Helper class, which builds output section list, also
157// creating symbol sections, when needed
158template <class ELFT> class OutputSectionBuilder {
159public:
160 OutputSectionBuilder(OutputSectionFactory<ELFT> &F,
161 std::vector<OutputSectionBase<ELFT> *> *Out)
162 : Factory(F), OutputSections(Out) {}
163
164 void addSection(StringRef OutputName, InputSectionBase<ELFT> *I);
165 void addSymbol(SymbolAssignment *Cmd) {
166 PendingSymbols.emplace_back(new LayoutInputSection<ELFT>(Cmd));
167 }
168 void flushSymbols();
169 void flushSection();
Eugene Leviantceabe802016-08-11 07:56:43 +0000170
171private:
172 OutputSectionFactory<ELFT> &Factory;
173 std::vector<OutputSectionBase<ELFT> *> *OutputSections;
174 OutputSectionBase<ELFT> *Current = nullptr;
175 std::vector<std::unique_ptr<LayoutInputSection<ELFT>>> PendingSymbols;
176 static std::vector<std::unique_ptr<LayoutInputSection<ELFT>>> OwningSections;
177};
178
George Rimarc3cb8842016-07-29 15:12:48 +0000179template <class ELFT>
Eugene Leviantceabe802016-08-11 07:56:43 +0000180std::vector<std::unique_ptr<LayoutInputSection<ELFT>>>
181 OutputSectionBuilder<ELFT>::OwningSections;
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000182
183} // anonymous namespace
Eugene Leviantceabe802016-08-11 07:56:43 +0000184
185template <class T> static T *zero(T *Val) {
186 memset(Val, 0, sizeof(*Val));
187 return Val;
188}
189
190template <class ELFT>
191LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000192 : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
193 InputSectionBase<ELFT>::Layout),
194 Cmd(Cmd) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000195 this->Live = true;
Eugene Leviantceabe802016-08-11 07:56:43 +0000196 Hdr.sh_type = SHT_NOBITS;
197}
198
199template <class ELFT>
200bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
201 return S->SectionKind == InputSectionBase<ELFT>::Layout;
202}
203
204template <class ELFT>
205void OutputSectionBuilder<ELFT>::addSection(StringRef OutputName,
206 InputSectionBase<ELFT> *C) {
George Rimarc3cb8842016-07-29 15:12:48 +0000207 bool IsNew;
Eugene Leviantceabe802016-08-11 07:56:43 +0000208 std::tie(Current, IsNew) = Factory.create(C, OutputName);
George Rimarc3cb8842016-07-29 15:12:48 +0000209 if (IsNew)
Eugene Leviantceabe802016-08-11 07:56:43 +0000210 OutputSections->push_back(Current);
211 flushSymbols();
212 Current->addSection(C);
213}
214
215template <class ELFT> void OutputSectionBuilder<ELFT>::flushSymbols() {
Rui Ueyama16024212016-08-11 23:22:52 +0000216 // Only regular output sections are supported.
217 if (dyn_cast_or_null<OutputSection<ELFT>>(Current)) {
218 for (std::unique_ptr<LayoutInputSection<ELFT>> &I : PendingSymbols) {
219 if (I->Cmd->Name == ".") {
220 Current->addSection(I.get());
221 OwningSections.push_back(std::move(I));
222 } else if (shouldDefine<ELFT>(I->Cmd)) {
223 addSynthetic<ELFT>(I->Cmd, Current);
Eugene Leviantceabe802016-08-11 07:56:43 +0000224 Current->addSection(I.get());
225 OwningSections.push_back(std::move(I));
226 }
227 }
Rui Ueyama16024212016-08-11 23:22:52 +0000228 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000229
230 PendingSymbols.clear();
231}
232
233template <class ELFT> void OutputSectionBuilder<ELFT>::flushSection() {
234 flushSymbols();
235 Current = nullptr;
236}
237
Rui Ueyama742c3832016-08-04 22:27:00 +0000238template <class ELFT>
239static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
240 return A->getSectionName() < B->getSectionName();
241}
George Rimar350ece42016-08-03 08:35:59 +0000242
Rui Ueyama742c3832016-08-04 22:27:00 +0000243template <class ELFT>
244static bool compareAlignment(InputSectionBase<ELFT> *A,
245 InputSectionBase<ELFT> *B) {
246 // ">" is not a mistake. Larger alignments are placed before smaller
247 // alignments in order to reduce the amount of padding necessary.
248 // This is compatible with GNU.
249 return A->Alignment > B->Alignment;
250}
George Rimar350ece42016-08-03 08:35:59 +0000251
Rui Ueyama742c3832016-08-04 22:27:00 +0000252template <class ELFT>
253static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
254getComparator(SortKind K) {
255 if (K == SortByName)
256 return compareName<ELFT>;
257 return compareAlignment<ELFT>;
258}
George Rimar0702c4e2016-07-29 15:32:46 +0000259
260template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000261void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
262 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
263 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
264 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
265 S->Live = false;
266 reportDiscarded(S);
267 }
268 }
269 }
270}
271
272template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000273void LinkerScript<ELFT>::createSections(
George Rimar9e694502016-07-29 16:18:47 +0000274 OutputSectionFactory<ELFT> &Factory) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000275 OutputSectionBuilder<ELFT> Builder(Factory, OutputSections);
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000276
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000277 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000278 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000279 if (Cmd->Name == "/DISCARD/") {
280 discard(*Cmd);
281 continue;
282 }
283 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands) {
284 if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base2.get())) {
285 Builder.addSymbol(Cmd2);
286 continue;
287 }
288 auto *Cmd2 = cast<InputSectionDescription>(Base2.get());
289 std::vector<InputSectionBase<ELFT> *> Sections = getInputSections(Cmd2);
290 if (Cmd2->SortInner)
291 std::stable_sort(Sections.begin(), Sections.end(),
292 getComparator<ELFT>(Cmd2->SortInner));
293 if (Cmd2->SortOuter)
294 std::stable_sort(Sections.begin(), Sections.end(),
295 getComparator<ELFT>(Cmd2->SortOuter));
296 for (InputSectionBase<ELFT> *S : Sections)
297 Builder.addSection(Cmd->Name, S);
298 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000299
300 Builder.flushSection();
301 } else if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base1.get())) {
Rui Ueyama16024212016-08-11 23:22:52 +0000302 if (shouldDefine<ELFT>(Cmd2))
303 addRegular<ELFT>(Cmd2);
Eugene Leviantceabe802016-08-11 07:56:43 +0000304 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000305 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000306
307 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000308 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
309 Symtab<ELFT>::X->getObjectFiles())
310 for (InputSectionBase<ELFT> *S : F->getSections())
311 if (!isDiscarded(S) && !S->OutSec)
Eugene Leviantceabe802016-08-11 07:56:43 +0000312 Builder.addSection(getOutputSectionName(S), S);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000313
Rui Ueyama3c291e12016-07-25 21:30:00 +0000314 // Remove from the output all the sections which did not meet
315 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000316 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000317}
318
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000319template <class R, class T>
320static inline void removeElementsIf(R &Range, const T &Pred) {
321 Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
322}
323
Rui Ueyama3c291e12016-07-25 21:30:00 +0000324// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000325template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000326 // In this loop, we remove output sections if they don't satisfy
327 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000328 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
329 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
330 if (!Cmd || Cmd->Name == "/DISCARD/")
331 continue;
332
George Rimarbfc4a4b2016-07-26 10:47:09 +0000333 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000334 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000335
Rui Ueyama808d13e2016-08-05 01:05:01 +0000336 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
337 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
338
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000339 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
340 bool Writable = (S->getFlags() & SHF_WRITE);
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000341 return S->getName() == Cmd->Name &&
342 ((RO && Writable) || (RW && !Writable));
George Rimarbfc4a4b2016-07-26 10:47:09 +0000343 });
Rui Ueyama3c291e12016-07-25 21:30:00 +0000344 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000345}
346
Eugene Leviantceabe802016-08-11 07:56:43 +0000347template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000348 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000349 if (!OutSec) {
350 Sec->assignOffsets();
Eugene Leviantceabe802016-08-11 07:56:43 +0000351 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000352 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000353
354 typedef typename ELFT::uint uintX_t;
355 uintX_t Off = 0;
356
357 for (InputSection<ELFT> *I : OutSec->Sections) {
358 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
359 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
360 if (L->Cmd->Name == ".")
361 Off = Value;
362 else
363 cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym)->Value = Value;
364 } else {
365 Off = alignTo(Off, I->Alignment);
366 I->OutSecOff = Off;
367 Off += I->getSize();
368 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000369 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000370 // works correctly in the case below:
371 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
372 Sec->setSize(Off);
373 }
374}
375
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000376template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000377 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000378 // are not explicitly placed into the output file by the linker script.
379 // We place orphan sections at end of file.
380 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000381 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000382 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000383 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000384 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000385 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000386 }
George Rimar652852c2016-04-16 10:10:32 +0000387
Rui Ueyama7c18c282016-04-18 21:00:40 +0000388 // Assign addresses as instructed by linker script SECTIONS sub-commands.
George Rimare32a3592016-08-10 07:59:34 +0000389 Dot = getSizeOfHeaders();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000390 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000391 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000392
George Rimar076fe152016-07-21 06:43:01 +0000393 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
394 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000395 if (Cmd->Name == ".") {
396 Dot = Cmd->Expression(Dot);
397 } else if (Cmd->Sym) {
398 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
399 }
George Rimar652852c2016-04-16 10:10:32 +0000400 continue;
401 }
402
George Rimareefa7582016-08-04 09:29:31 +0000403 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
404 Cmd->Expression(Dot);
405 continue;
406 }
407
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000408 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000409 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000410 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000411 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000412 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar076fe152016-07-21 06:43:01 +0000413 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000414 continue;
George Rimar652852c2016-04-16 10:10:32 +0000415
George Rimar58e5c4d2016-07-25 08:29:46 +0000416 if (Cmd->AddrExpr)
417 Dot = Cmd->AddrExpr(Dot);
418
George Rimar630c6172016-07-26 18:06:29 +0000419 if (Cmd->AlignExpr)
420 Sec->updateAlignment(Cmd->AlignExpr(Dot));
421
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000422 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
423 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000424 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000425 Sec->setVA(TVA);
Eugene Leviantceabe802016-08-11 07:56:43 +0000426 assignOffsets(Sec);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000427 ThreadBssOffset = TVA - Dot + Sec->getSize();
428 continue;
429 }
George Rimar652852c2016-04-16 10:10:32 +0000430
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000431 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000432 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000433 Sec->setVA(Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000434 assignOffsets(Sec);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000435 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000436 Dot += Sec->getSize();
437 continue;
438 }
Rui Ueyama2de509c2016-08-12 00:55:08 +0000439 Sec->assignOffsets();
George Rimar652852c2016-04-16 10:10:32 +0000440 }
441 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000442
Rafael Espindola64c32d62016-07-07 14:28:47 +0000443 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000444 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000445 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
446 Out<ELFT>::ProgramHeaders->getSize(),
447 Target->PageSize);
448 Out<ELFT>::ElfHeader->setVA(MinVA);
449 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000450}
451
Rui Ueyama07320e42016-04-20 20:13:41 +0000452template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000453std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
454 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000455 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000456
457 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000458 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
459 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000460
461 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000462 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000463 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000464 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000465
466 switch (Cmd.Type) {
467 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000468 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000469 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000470 break;
471 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000472 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000473 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000474 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000475 }
476 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 case PT_GNU_EH_FRAME:
478 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000479 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000480 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000481 }
482 break;
483 }
484 }
485
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000486 PhdrEntry<ELFT> *Load = nullptr;
487 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 for (OutputSectionBase<ELFT> *Sec : Sections) {
489 if (!(Sec->getFlags() & SHF_ALLOC))
490 break;
491
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000492 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 if (!PhdrIds.empty()) {
494 // Assign headers specified by linker script
495 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000496 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000497 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000498 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000499 }
500 } else {
501 // If we have no load segment or flags've changed then we want new load
502 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000503 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000504 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000505 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000506 Flags = NewFlags;
507 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000508 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000509 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000510 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000511 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000512}
513
514template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000515ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000516 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
517 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
518 if (Cmd->Name == Name)
519 return Cmd->Filler;
520 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000521}
522
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000523// Returns the index of the given section name in linker script
524// SECTIONS commands. Sections are laid out as the same order as they
525// were in the script. If a given name did not appear in the script,
526// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000527template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000528 int I = 0;
529 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
530 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
531 if (Cmd->Name == Name)
532 return I;
533 ++I;
534 }
535 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000536}
537
538// A compartor to sort output sections. Returns -1 or 1 if
539// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000540template <class ELFT>
541int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000542 int I = getSectionIndex(A);
543 int J = getSectionIndex(B);
544 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000545 return 0;
546 return I < J ? -1 : 1;
547}
548
Eugene Leviantbbe38602016-07-19 09:25:43 +0000549template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
550 return !Opt.PhdrsCommands.empty();
551}
552
George Rimar9e694502016-07-29 16:18:47 +0000553template <class ELFT>
554typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
555 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
556 if (Sec->getName() == Name)
557 return Sec->getSize();
558 error("undefined section " + Name);
559 return 0;
560}
561
George Rimare32a3592016-08-10 07:59:34 +0000562template <class ELFT>
563typename ELFT::uint LinkerScript<ELFT>::getSizeOfHeaders() {
564 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
565}
566
Eugene Leviantbbe38602016-07-19 09:25:43 +0000567// Returns indices of ELF headers containing specific section, identified
568// by Name. Each index is a zero based number of ELF header listed within
569// PHDRS {} script block.
570template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000571std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000572 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
573 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000574 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000575 continue;
576
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000577 std::vector<size_t> Ret;
578 for (StringRef PhdrName : Cmd->Phdrs)
579 Ret.push_back(getPhdrIndex(PhdrName));
580 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000581 }
George Rimar31d842f2016-07-20 16:43:03 +0000582 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000583}
584
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000585template <class ELFT>
586size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
587 size_t I = 0;
588 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
589 if (Cmd.Name == PhdrName)
590 return I;
591 ++I;
592 }
593 error("section header '" + PhdrName + "' is not listed in PHDRS");
594 return 0;
595}
596
Rui Ueyama07320e42016-04-20 20:13:41 +0000597class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000598 typedef void (ScriptParser::*Handler)();
599
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000600public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000601 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000602
Rui Ueyama4a465392016-04-22 22:59:24 +0000603 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000604
605private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000606 void addFile(StringRef Path);
607
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000608 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000609 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000610 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000611 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000612 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000613 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000614 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000615 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000616 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000617 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000618 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000619 void readSections();
620
Rui Ueyama113cdec2016-07-24 23:05:57 +0000621 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000622 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000623 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000624 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000625 InputSectionDescription *readInputSectionDescription();
626 std::vector<StringRef> readInputFilePatterns();
627 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000628 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000629 SortKind readSortKind();
Rui Ueyama10416562016-08-04 02:03:27 +0000630 SymbolAssignment *readProvide(bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000631 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000632 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000633 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000634 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000635
636 Expr readExpr();
637 Expr readExpr1(Expr Lhs, int MinPrec);
638 Expr readPrimary();
639 Expr readTernary(Expr Cond);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000640
George Rimarc3794e52016-02-24 09:21:47 +0000641 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000642 ScriptConfiguration &Opt = *ScriptConfig;
643 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000644 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000645};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000646
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000647const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000648 {"ENTRY", &ScriptParser::readEntry},
649 {"EXTERN", &ScriptParser::readExtern},
650 {"GROUP", &ScriptParser::readGroup},
651 {"INCLUDE", &ScriptParser::readInclude},
652 {"INPUT", &ScriptParser::readGroup},
653 {"OUTPUT", &ScriptParser::readOutput},
654 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
655 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000656 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000657 {"SEARCH_DIR", &ScriptParser::readSearchDir},
658 {"SECTIONS", &ScriptParser::readSections},
659 {";", &ScriptParser::readNothing}};
660
Rui Ueyama717677a2016-02-11 21:17:59 +0000661void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000662 while (!atEOF()) {
663 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000664 if (Handler Fn = Cmd.lookup(Tok))
665 (this->*Fn)();
666 else
George Rimar57610422016-03-11 14:43:02 +0000667 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000668 }
669}
670
Rui Ueyama717677a2016-02-11 21:17:59 +0000671void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000672 if (IsUnderSysroot && S.startswith("/")) {
673 SmallString<128> Path;
674 (Config->Sysroot + S).toStringRef(Path);
675 if (sys::fs::exists(Path)) {
676 Driver->addFile(Saver.save(Path.str()));
677 return;
678 }
679 }
680
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000681 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000682 Driver->addFile(S);
683 } else if (S.startswith("=")) {
684 if (Config->Sysroot.empty())
685 Driver->addFile(S.substr(1));
686 else
687 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
688 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000689 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000690 } else if (sys::fs::exists(S)) {
691 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000692 } else {
693 std::string Path = findFromSearchPaths(S);
694 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000695 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000696 else
697 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000698 }
699}
700
Rui Ueyama717677a2016-02-11 21:17:59 +0000701void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000702 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000703 bool Orig = Config->AsNeeded;
704 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000705 while (!Error && !skip(")"))
706 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000707 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000708}
709
Rui Ueyama717677a2016-02-11 21:17:59 +0000710void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000711 // -e <symbol> takes predecence over ENTRY(<symbol>).
712 expect("(");
713 StringRef Tok = next();
714 if (Config->Entry.empty())
715 Config->Entry = Tok;
716 expect(")");
717}
718
Rui Ueyama717677a2016-02-11 21:17:59 +0000719void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000720 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000721 while (!Error && !skip(")"))
722 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000723}
724
Rui Ueyama717677a2016-02-11 21:17:59 +0000725void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000726 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000727 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000728 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000729 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000730 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000731 else
732 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000733 }
734}
735
Rui Ueyama717677a2016-02-11 21:17:59 +0000736void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000737 StringRef Tok = next();
738 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000739 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000740 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000741 return;
742 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000743 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000744 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
745 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000746 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000747}
748
Rui Ueyama717677a2016-02-11 21:17:59 +0000749void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000750 // -o <file> takes predecence over OUTPUT(<file>).
751 expect("(");
752 StringRef Tok = next();
753 if (Config->OutputFile.empty())
754 Config->OutputFile = Tok;
755 expect(")");
756}
757
Rui Ueyama717677a2016-02-11 21:17:59 +0000758void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000759 // Error checking only for now.
760 expect("(");
761 next();
762 expect(")");
763}
764
Rui Ueyama717677a2016-02-11 21:17:59 +0000765void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000766 // Error checking only for now.
767 expect("(");
768 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000769 StringRef Tok = next();
770 if (Tok == ")")
771 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000772 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000773 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000774 return;
775 }
Davide Italiano6836c612015-10-12 21:08:41 +0000776 next();
777 expect(",");
778 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000779 expect(")");
780}
781
Eugene Leviantbbe38602016-07-19 09:25:43 +0000782void ScriptParser::readPhdrs() {
783 expect("{");
784 while (!Error && !skip("}")) {
785 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000786 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000787 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
788
789 PhdrCmd.Type = readPhdrType();
790 do {
791 Tok = next();
792 if (Tok == ";")
793 break;
794 if (Tok == "FILEHDR")
795 PhdrCmd.HasFilehdr = true;
796 else if (Tok == "PHDRS")
797 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000798 else if (Tok == "FLAGS") {
799 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000800 // Passing 0 for the value of dot is a bit of a hack. It means that
801 // we accept expressions like ".|1".
802 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000803 expect(")");
804 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000805 setError("unexpected header attribute: " + Tok);
806 } while (!Error);
807 }
808}
809
Rui Ueyama717677a2016-02-11 21:17:59 +0000810void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000811 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000812 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000813 expect(")");
814}
815
Rui Ueyama717677a2016-02-11 21:17:59 +0000816void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000817 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000818 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000819 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000820 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000821 BaseCommand *Cmd = readProvideOrAssignment(Tok);
822 if (!Cmd) {
823 if (Tok == "ASSERT")
824 Cmd = new AssertCommand(readAssert());
825 else
826 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000827 }
Rui Ueyama10416562016-08-04 02:03:27 +0000828 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000829 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000830}
831
Rui Ueyama708019c2016-07-24 18:19:40 +0000832static int precedence(StringRef Op) {
833 return StringSwitch<int>(Op)
834 .Case("*", 4)
835 .Case("/", 4)
836 .Case("+", 3)
837 .Case("-", 3)
838 .Case("<", 2)
839 .Case(">", 2)
840 .Case(">=", 2)
841 .Case("<=", 2)
842 .Case("==", 2)
843 .Case("!=", 2)
844 .Case("&", 1)
845 .Default(-1);
846}
847
Rui Ueyama10416562016-08-04 02:03:27 +0000848std::vector<StringRef> ScriptParser::readInputFilePatterns() {
849 std::vector<StringRef> V;
850 while (!Error && !skip(")"))
851 V.push_back(next());
852 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000853}
854
Rui Ueyama742c3832016-08-04 22:27:00 +0000855SortKind ScriptParser::readSortKind() {
856 if (skip("SORT") || skip("SORT_BY_NAME"))
857 return SortByName;
858 if (skip("SORT_BY_ALIGNMENT"))
859 return SortByAlignment;
860 return SortNone;
861}
862
Rui Ueyama10416562016-08-04 02:03:27 +0000863InputSectionDescription *ScriptParser::readInputSectionRules() {
864 auto *Cmd = new InputSectionDescription;
865 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000866 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000867
Rui Ueyama742c3832016-08-04 22:27:00 +0000868 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000869 if (skip("EXCLUDE_FILE")) {
870 expect("(");
871 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000872 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000873 }
George Rimar06598002016-07-28 21:51:30 +0000874
Rui Ueyama742c3832016-08-04 22:27:00 +0000875 // Read SORT().
876 if (SortKind K1 = readSortKind()) {
877 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000878 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000879 if (SortKind K2 = readSortKind()) {
880 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000881 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000882 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000883 expect(")");
884 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000885 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000886 }
George Rimar0702c4e2016-07-29 15:32:46 +0000887 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000888 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000889 }
George Rimar0702c4e2016-07-29 15:32:46 +0000890
Rui Ueyama10416562016-08-04 02:03:27 +0000891 Cmd->SectionPatterns = readInputFilePatterns();
892 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000893}
894
Rui Ueyama10416562016-08-04 02:03:27 +0000895InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000896 // Input section wildcard can be surrounded by KEEP.
897 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
898 if (skip("KEEP")) {
899 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000900 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000901 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000902 Opt.KeptSections.insert(Opt.KeptSections.end(),
903 Cmd->SectionPatterns.begin(),
904 Cmd->SectionPatterns.end());
905 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000906 }
Rui Ueyama10416562016-08-04 02:03:27 +0000907 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000908}
909
Rui Ueyama10416562016-08-04 02:03:27 +0000910Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000911 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000912 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000913 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000914 return E;
George Rimar630c6172016-07-26 18:06:29 +0000915}
916
George Rimar03fc0102016-07-28 07:18:23 +0000917void ScriptParser::readSort() {
918 expect("(");
919 expect("CONSTRUCTORS");
920 expect(")");
921}
922
George Rimareefa7582016-08-04 09:29:31 +0000923Expr ScriptParser::readAssert() {
924 expect("(");
925 Expr E = readExpr();
926 expect(",");
927 StringRef Msg = next();
928 expect(")");
929 return [=](uint64_t Dot) {
930 uint64_t V = E(Dot);
931 if (!V)
932 error(Msg);
933 return V;
934 };
935}
936
Rui Ueyama10416562016-08-04 02:03:27 +0000937OutputSectionCommand *
938ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000939 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000940
941 // Read an address expression.
942 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
943 if (peek() != ":")
944 Cmd->AddrExpr = readExpr();
945
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000946 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000947
George Rimar630c6172016-07-26 18:06:29 +0000948 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000949 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000950
Davide Italiano246f6812016-07-22 03:36:24 +0000951 // Parse constraints.
952 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000953 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000954 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000955 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000956 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000957
Rui Ueyama025d59b2016-02-02 20:27:59 +0000958 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000959 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000960 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000961 continue;
962 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000963
964 StringRef Tok = next();
965 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
966 Cmd->Commands.emplace_back(Assignment);
967 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000968 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000969 else
970 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000971 }
George Rimar076fe152016-07-21 06:43:01 +0000972 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000973 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000974 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000975}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000976
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000977std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000978 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000979 if (!Tok.startswith("="))
980 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000981 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000982
983 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000984 if (Tok.startswith("=0x"))
985 return parseHex(Tok.substr(3));
986
Rui Ueyama965827d2016-08-03 23:25:15 +0000987 // Read a decimal or octal value as a big-endian 32 bit value.
988 // Why do this? I don't know, but that's what gold does.
989 uint32_t V;
990 if (Tok.substr(1).getAsInteger(0, V)) {
991 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000992 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000993 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000994 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000995}
996
Rui Ueyama10416562016-08-04 02:03:27 +0000997SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000998 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000999 SymbolAssignment *Cmd = readAssignment(next());
1000 Cmd->Provide = true;
1001 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001002 expect(")");
1003 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001004 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001005}
1006
Eugene Leviantceabe802016-08-11 07:56:43 +00001007SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1008 SymbolAssignment *Cmd = nullptr;
1009 if (peek() == "=" || peek() == "+=") {
1010 Cmd = readAssignment(Tok);
1011 expect(";");
1012 } else if (Tok == "PROVIDE") {
1013 Cmd = readProvide(false);
1014 } else if (Tok == "PROVIDE_HIDDEN") {
1015 Cmd = readProvide(true);
1016 }
1017 return Cmd;
1018}
1019
George Rimar30835ea2016-07-28 21:08:56 +00001020static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1021 if (S == ".")
1022 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001023
George Rimara9c5a522016-07-26 18:18:58 +00001024 switch (Config->EKind) {
1025 case ELF32LEKind:
1026 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1027 return B->getVA<ELF32LE>();
1028 break;
1029 case ELF32BEKind:
1030 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1031 return B->getVA<ELF32BE>();
1032 break;
1033 case ELF64LEKind:
1034 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1035 return B->getVA<ELF64LE>();
1036 break;
1037 case ELF64BEKind:
1038 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1039 return B->getVA<ELF64BE>();
1040 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001041 default:
George Rimarb567b622016-07-26 18:46:13 +00001042 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001043 }
1044 error("symbol not found: " + S);
1045 return 0;
1046}
1047
George Rimar9e694502016-07-29 16:18:47 +00001048static uint64_t getSectionSize(StringRef Name) {
1049 switch (Config->EKind) {
1050 case ELF32LEKind:
1051 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1052 case ELF32BEKind:
1053 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1054 case ELF64LEKind:
1055 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1056 case ELF64BEKind:
1057 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1058 default:
1059 llvm_unreachable("unsupported target");
1060 }
George Rimar9e694502016-07-29 16:18:47 +00001061}
1062
George Rimare32a3592016-08-10 07:59:34 +00001063static uint64_t getSizeOfHeaders() {
1064 switch (Config->EKind) {
1065 case ELF32LEKind:
1066 return Script<ELF32LE>::X->getSizeOfHeaders();
1067 case ELF32BEKind:
1068 return Script<ELF32BE>::X->getSizeOfHeaders();
1069 case ELF64LEKind:
1070 return Script<ELF64LE>::X->getSizeOfHeaders();
1071 case ELF64BEKind:
1072 return Script<ELF64BE>::X->getSizeOfHeaders();
1073 default:
1074 llvm_unreachable("unsupported target");
1075 }
1076}
1077
George Rimar30835ea2016-07-28 21:08:56 +00001078SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1079 StringRef Op = next();
1080 assert(Op == "=" || Op == "+=");
1081 Expr E = readExpr();
1082 if (Op == "+=")
1083 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001084 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001085}
1086
1087// This is an operator-precedence parser to parse a linker
1088// script expression.
1089Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1090
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001091static Expr combine(StringRef Op, Expr L, Expr R) {
1092 if (Op == "*")
1093 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1094 if (Op == "/") {
1095 return [=](uint64_t Dot) -> uint64_t {
1096 uint64_t RHS = R(Dot);
1097 if (RHS == 0) {
1098 error("division by zero");
1099 return 0;
1100 }
1101 return L(Dot) / RHS;
1102 };
1103 }
1104 if (Op == "+")
1105 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1106 if (Op == "-")
1107 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1108 if (Op == "<")
1109 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1110 if (Op == ">")
1111 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1112 if (Op == ">=")
1113 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1114 if (Op == "<=")
1115 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1116 if (Op == "==")
1117 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1118 if (Op == "!=")
1119 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1120 if (Op == "&")
1121 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1122 llvm_unreachable("invalid operator");
1123}
1124
Rui Ueyama708019c2016-07-24 18:19:40 +00001125// This is a part of the operator-precedence parser. This function
1126// assumes that the remaining token stream starts with an operator.
1127Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1128 while (!atEOF() && !Error) {
1129 // Read an operator and an expression.
1130 StringRef Op1 = peek();
1131 if (Op1 == "?")
1132 return readTernary(Lhs);
1133 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001134 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001135 next();
1136 Expr Rhs = readPrimary();
1137
1138 // Evaluate the remaining part of the expression first if the
1139 // next operator has greater precedence than the previous one.
1140 // For example, if we have read "+" and "3", and if the next
1141 // operator is "*", then we'll evaluate 3 * ... part first.
1142 while (!atEOF()) {
1143 StringRef Op2 = peek();
1144 if (precedence(Op2) <= precedence(Op1))
1145 break;
1146 Rhs = readExpr1(Rhs, precedence(Op2));
1147 }
1148
1149 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001150 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001151 return Lhs;
1152}
1153
1154uint64_t static getConstant(StringRef S) {
1155 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1156 return Target->PageSize;
1157 error("unknown constant: " + S);
1158 return 0;
1159}
1160
1161Expr ScriptParser::readPrimary() {
1162 StringRef Tok = next();
1163
Rui Ueyama708019c2016-07-24 18:19:40 +00001164 if (Tok == "(") {
1165 Expr E = readExpr();
1166 expect(")");
1167 return E;
1168 }
1169
1170 // Built-in functions are parsed here.
1171 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001172 if (Tok == "ASSERT")
1173 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001174 if (Tok == "ALIGN") {
1175 expect("(");
1176 Expr E = readExpr();
1177 expect(")");
1178 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1179 }
1180 if (Tok == "CONSTANT") {
1181 expect("(");
1182 StringRef Tok = next();
1183 expect(")");
1184 return [=](uint64_t Dot) { return getConstant(Tok); };
1185 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001186 if (Tok == "SEGMENT_START") {
1187 expect("(");
1188 next();
1189 expect(",");
1190 uint64_t Val;
1191 next().getAsInteger(0, Val);
1192 expect(")");
1193 return [=](uint64_t Dot) { return Val; };
1194 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001195 if (Tok == "DATA_SEGMENT_ALIGN") {
1196 expect("(");
1197 Expr E = readExpr();
1198 expect(",");
1199 readExpr();
1200 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001201 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001202 }
1203 if (Tok == "DATA_SEGMENT_END") {
1204 expect("(");
1205 expect(".");
1206 expect(")");
1207 return [](uint64_t Dot) { return Dot; };
1208 }
George Rimar276b4e62016-07-26 17:58:44 +00001209 // GNU linkers implements more complicated logic to handle
1210 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1211 // the next page boundary for simplicity.
1212 if (Tok == "DATA_SEGMENT_RELRO_END") {
1213 expect("(");
1214 next();
1215 expect(",");
1216 readExpr();
1217 expect(")");
1218 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1219 }
George Rimar9e694502016-07-29 16:18:47 +00001220 if (Tok == "SIZEOF") {
1221 expect("(");
1222 StringRef Name = next();
1223 expect(")");
1224 return [=](uint64_t Dot) { return getSectionSize(Name); };
1225 }
George Rimare32a3592016-08-10 07:59:34 +00001226 if (Tok == "SIZEOF_HEADERS")
1227 return [=](uint64_t Dot) { return getSizeOfHeaders(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001228
George Rimara9c5a522016-07-26 18:18:58 +00001229 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001230 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001231 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001232 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001233 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001234 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001235 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001236 return [=](uint64_t Dot) { return V; };
1237}
1238
1239Expr ScriptParser::readTernary(Expr Cond) {
1240 next();
1241 Expr L = readExpr();
1242 expect(":");
1243 Expr R = readExpr();
1244 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1245}
1246
Eugene Leviantbbe38602016-07-19 09:25:43 +00001247std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1248 std::vector<StringRef> Phdrs;
1249 while (!Error && peek().startswith(":")) {
1250 StringRef Tok = next();
1251 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1252 if (Tok.empty()) {
1253 setError("section header name is empty");
1254 break;
1255 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001256 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001257 }
1258 return Phdrs;
1259}
1260
1261unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001262 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001263 unsigned Ret = StringSwitch<unsigned>(Tok)
1264 .Case("PT_NULL", PT_NULL)
1265 .Case("PT_LOAD", PT_LOAD)
1266 .Case("PT_DYNAMIC", PT_DYNAMIC)
1267 .Case("PT_INTERP", PT_INTERP)
1268 .Case("PT_NOTE", PT_NOTE)
1269 .Case("PT_SHLIB", PT_SHLIB)
1270 .Case("PT_PHDR", PT_PHDR)
1271 .Case("PT_TLS", PT_TLS)
1272 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1273 .Case("PT_GNU_STACK", PT_GNU_STACK)
1274 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1275 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001276
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001277 if (Ret == (unsigned)-1) {
1278 setError("invalid program header type: " + Tok);
1279 return PT_NULL;
1280 }
1281 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001282}
1283
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001284static bool isUnderSysroot(StringRef Path) {
1285 if (Config->Sysroot == "")
1286 return false;
1287 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1288 if (sys::fs::equivalent(Config->Sysroot, Path))
1289 return true;
1290 return false;
1291}
1292
Rui Ueyama07320e42016-04-20 20:13:41 +00001293// Entry point.
1294void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001295 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001296 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001297}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001298
Rui Ueyama07320e42016-04-20 20:13:41 +00001299template class elf::LinkerScript<ELF32LE>;
1300template class elf::LinkerScript<ELF32BE>;
1301template class elf::LinkerScript<ELF64LE>;
1302template class elf::LinkerScript<ELF64BE>;