blob: ab2ce70840e5cf5c1276cac6bce33b091c226d10 [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>
47static Symbol *addSymbolToSymtabAux(StringRef Name, uint8_t StOther) {
48 return Symtab<ELFT>::X->addRegular(Name, STB_GLOBAL, StOther);
49}
50
51template <class ELFT>
52static Symbol *addSymbolToSymtabAux(StringRef Name, typename ELFT::uint Value,
53 OutputSectionBase<ELFT> *Section) {
54 return Symtab<ELFT>::X->addSynthetic(Name, Section, Value);
55}
56
57template <class ELFT, class... ArgsT>
58static bool addSymbolToSymtab(SymbolAssignment &Cmd, ArgsT... Args) {
59 if (Cmd.Name == ".")
60 return false;
61
62 // If a symbol was in PROVIDE(), define it only when it is an
63 // undefined symbol.
64 SymbolBody *B = Symtab<ELFT>::X->find(Cmd.Name);
65 if (Cmd.Provide && !(B && B->isUndefined()))
66 return false;
67
68 Symbol *Sym =
69 addSymbolToSymtabAux<ELFT>(Cmd.Name, std::forward<ArgsT>(Args)...);
70
71 Sym->Visibility = Cmd.Hidden ? STV_HIDDEN : STV_DEFAULT;
72 Cmd.Sym = Sym->body();
73 return true;
74}
75
George Rimar076fe152016-07-21 06:43:01 +000076bool SymbolAssignment::classof(const BaseCommand *C) {
77 return C->Kind == AssignmentKind;
78}
79
80bool OutputSectionCommand::classof(const BaseCommand *C) {
81 return C->Kind == OutputSectionKind;
82}
83
George Rimareea31142016-07-21 14:26:59 +000084bool InputSectionDescription::classof(const BaseCommand *C) {
85 return C->Kind == InputSectionKind;
86}
87
George Rimareefa7582016-08-04 09:29:31 +000088bool AssertCommand::classof(const BaseCommand *C) {
89 return C->Kind == AssertKind;
90}
91
Rui Ueyama36a153c2016-07-23 14:09:58 +000092template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000093 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000094}
95
Rui Ueyama07320e42016-04-20 20:13:41 +000096template <class ELFT>
97bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000098 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000099 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000100 return true;
101 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000102}
103
Rui Ueyama63dc6502016-07-25 22:41:42 +0000104static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
105 for (StringRef Pat : Patterns)
106 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000107 return true;
108 return false;
109}
110
George Rimar06598002016-07-28 21:51:30 +0000111static bool fileMatches(const InputSectionDescription *Desc,
112 StringRef Filename) {
113 if (!globMatch(Desc->FilePattern, Filename))
114 return false;
115 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
116}
117
Rui Ueyama6b274812016-07-25 22:51:07 +0000118// Returns input sections filtered by given glob patterns.
119template <class ELFT>
120std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000121LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000122 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000123 std::vector<InputSectionBase<ELFT> *> Ret;
124 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000125 Symtab<ELFT>::X->getObjectFiles()) {
126 if (fileMatches(I, sys::path::filename(F->getName())))
127 for (InputSectionBase<ELFT> *S : F->getSections())
128 if (!isDiscarded(S) && !S->OutSec &&
129 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000130 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000131 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000132
133 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000134 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000135
Rui Ueyama6b274812016-07-25 22:51:07 +0000136 return Ret;
137}
138
Eugene Leviantceabe802016-08-11 07:56:43 +0000139namespace {
140template <class ELFT> class LayoutInputSection : public InputSection<ELFT> {
141public:
142 LayoutInputSection(SymbolAssignment *Cmd);
143 static bool classof(const InputSectionBase<ELFT> *S);
144 SymbolAssignment *Cmd;
145
146private:
147 typename ELFT::Shdr Hdr;
148};
149
150// Helper class, which builds output section list, also
151// creating symbol sections, when needed
152template <class ELFT> class OutputSectionBuilder {
153public:
154 OutputSectionBuilder(OutputSectionFactory<ELFT> &F,
155 std::vector<OutputSectionBase<ELFT> *> *Out)
156 : Factory(F), OutputSections(Out) {}
157
158 void addSection(StringRef OutputName, InputSectionBase<ELFT> *I);
159 void addSymbol(SymbolAssignment *Cmd) {
160 PendingSymbols.emplace_back(new LayoutInputSection<ELFT>(Cmd));
161 }
162 void flushSymbols();
163 void flushSection();
164 void finalize();
165
166private:
167 OutputSectionFactory<ELFT> &Factory;
168 std::vector<OutputSectionBase<ELFT> *> *OutputSections;
169 OutputSectionBase<ELFT> *Current = nullptr;
170 std::vector<std::unique_ptr<LayoutInputSection<ELFT>>> PendingSymbols;
171 static std::vector<std::unique_ptr<LayoutInputSection<ELFT>>> OwningSections;
172};
173
George Rimarc3cb8842016-07-29 15:12:48 +0000174template <class ELFT>
Eugene Leviantceabe802016-08-11 07:56:43 +0000175std::vector<std::unique_ptr<LayoutInputSection<ELFT>>>
176 OutputSectionBuilder<ELFT>::OwningSections;
177}
178
179template <class T> static T *zero(T *Val) {
180 memset(Val, 0, sizeof(*Val));
181 return Val;
182}
183
184template <class ELFT>
185LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
186 : InputSection<ELFT>(nullptr, zero(&Hdr)), Cmd(Cmd) {
187 this->Live = true;
188 this->SectionKind = InputSectionBase<ELFT>::Layout;
189 Hdr.sh_type = SHT_NOBITS;
190}
191
192template <class ELFT>
193bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
194 return S->SectionKind == InputSectionBase<ELFT>::Layout;
195}
196
197template <class ELFT>
198void OutputSectionBuilder<ELFT>::addSection(StringRef OutputName,
199 InputSectionBase<ELFT> *C) {
George Rimarc3cb8842016-07-29 15:12:48 +0000200 bool IsNew;
Eugene Leviantceabe802016-08-11 07:56:43 +0000201 std::tie(Current, IsNew) = Factory.create(C, OutputName);
George Rimarc3cb8842016-07-29 15:12:48 +0000202 if (IsNew)
Eugene Leviantceabe802016-08-11 07:56:43 +0000203 OutputSections->push_back(Current);
204 flushSymbols();
205 Current->addSection(C);
206}
207
208template <class ELFT> void OutputSectionBuilder<ELFT>::flushSymbols() {
209 for (std::unique_ptr<LayoutInputSection<ELFT>> &I : PendingSymbols)
210 if (I->Cmd->Name == "." || addSymbolToSymtab<ELFT>(*I->Cmd, 0, Current)) {
211 // Only regular output sections are supported.
212 if (dyn_cast_or_null<OutputSection<ELFT>>(Current)) {
213 Current->addSection(I.get());
214 OwningSections.push_back(std::move(I));
215 }
216 }
217
218 PendingSymbols.clear();
219}
220
221template <class ELFT> void OutputSectionBuilder<ELFT>::flushSection() {
222 flushSymbols();
223 Current = nullptr;
224}
225
226template <class ELFT> void OutputSectionBuilder<ELFT>::finalize() {
227 // Assign offsets to all sections which don't contain symbols
228 for (OutputSectionBase<ELFT> *S : *OutputSections)
229 if (llvm::find_if(OwningSections,
230 [&](std::unique_ptr<LayoutInputSection<ELFT>> &L) {
231 return L->OutSec == S;
232 }) == OwningSections.end())
233 S->assignOffsets();
George Rimarc3cb8842016-07-29 15:12:48 +0000234}
235
Rui Ueyama742c3832016-08-04 22:27:00 +0000236template <class ELFT>
237static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
238 return A->getSectionName() < B->getSectionName();
239}
George Rimar350ece42016-08-03 08:35:59 +0000240
Rui Ueyama742c3832016-08-04 22:27:00 +0000241template <class ELFT>
242static bool compareAlignment(InputSectionBase<ELFT> *A,
243 InputSectionBase<ELFT> *B) {
244 // ">" is not a mistake. Larger alignments are placed before smaller
245 // alignments in order to reduce the amount of padding necessary.
246 // This is compatible with GNU.
247 return A->Alignment > B->Alignment;
248}
George Rimar350ece42016-08-03 08:35:59 +0000249
Rui Ueyama742c3832016-08-04 22:27:00 +0000250template <class ELFT>
251static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
252getComparator(SortKind K) {
253 if (K == SortByName)
254 return compareName<ELFT>;
255 return compareAlignment<ELFT>;
256}
George Rimar0702c4e2016-07-29 15:32:46 +0000257
258template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000259void LinkerScript<ELFT>::createSections(
George Rimar9e694502016-07-29 16:18:47 +0000260 OutputSectionFactory<ELFT> &Factory) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000261 OutputSectionBuilder<ELFT> Builder(Factory, OutputSections);
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000262
Eugene Leviantceabe802016-08-11 07:56:43 +0000263 auto Add = [&](StringRef OutputName, const InputSectionDescription *Cmd) {
264 std::vector<InputSectionBase<ELFT> *> Sections = getInputSections(Cmd);
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000265 if (OutputName == "/DISCARD/") {
266 for (InputSectionBase<ELFT> *S : Sections) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000267 S->Live = false;
268 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000269 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000270 return;
George Rimareea31142016-07-21 14:26:59 +0000271 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000272 if (Cmd->SortInner)
George Rimar350ece42016-08-03 08:35:59 +0000273 std::stable_sort(Sections.begin(), Sections.end(),
Rui Ueyama742c3832016-08-04 22:27:00 +0000274 getComparator<ELFT>(Cmd->SortInner));
275 if (Cmd->SortOuter)
276 std::stable_sort(Sections.begin(), Sections.end(),
277 getComparator<ELFT>(Cmd->SortOuter));
George Rimar0702c4e2016-07-29 15:32:46 +0000278 for (InputSectionBase<ELFT> *S : Sections)
Eugene Leviantceabe802016-08-11 07:56:43 +0000279 Builder.addSection(OutputName, S);
280 };
281
282 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
283 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
284 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
285 if (auto *Assignment = dyn_cast<SymbolAssignment>(Base2.get()))
286 Builder.addSymbol(Assignment);
287 else
288 Add(Cmd->Name, cast<InputSectionDescription>(Base2.get()));
289
290 Builder.flushSection();
291 } else if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base1.get())) {
292 addSymbolToSymtab<ELFT>(*Cmd2, STV_DEFAULT);
293 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000294
295 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000296 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
297 Symtab<ELFT>::X->getObjectFiles())
298 for (InputSectionBase<ELFT> *S : F->getSections())
299 if (!isDiscarded(S) && !S->OutSec)
Eugene Leviantceabe802016-08-11 07:56:43 +0000300 Builder.addSection(getOutputSectionName(S), S);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000301
Rui Ueyama3c291e12016-07-25 21:30:00 +0000302 // Remove from the output all the sections which did not meet
303 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000304 filter();
Eugene Leviantceabe802016-08-11 07:56:43 +0000305 Builder.finalize();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000306}
307
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000308template <class R, class T>
309static inline void removeElementsIf(R &Range, const T &Pred) {
310 Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
311}
312
Rui Ueyama3c291e12016-07-25 21:30:00 +0000313// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000314template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000315 // In this loop, we remove output sections if they don't satisfy
316 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000317 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
318 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
319 if (!Cmd || Cmd->Name == "/DISCARD/")
320 continue;
321
George Rimarbfc4a4b2016-07-26 10:47:09 +0000322 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000323 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000324
Rui Ueyama808d13e2016-08-05 01:05:01 +0000325 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
326 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
327
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000328 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
329 bool Writable = (S->getFlags() & SHF_WRITE);
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000330 return S->getName() == Cmd->Name &&
331 ((RO && Writable) || (RW && !Writable));
George Rimarbfc4a4b2016-07-26 10:47:09 +0000332 });
Rui Ueyama3c291e12016-07-25 21:30:00 +0000333 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000334}
335
Eugene Leviantceabe802016-08-11 07:56:43 +0000336template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
337 // Non-zero size means we have assigned offsets earlier in
338 // OutputSectionBuilder<ELFT>::finalize
339 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
340 if (Sec->getSize() || !OutSec)
341 return;
342
343 typedef typename ELFT::uint uintX_t;
344 uintX_t Off = 0;
345
346 for (InputSection<ELFT> *I : OutSec->Sections) {
347 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
348 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
349 if (L->Cmd->Name == ".")
350 Off = Value;
351 else
352 cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym)->Value = Value;
353 } else {
354 Off = alignTo(Off, I->Alignment);
355 I->OutSecOff = Off;
356 Off += I->getSize();
357 }
358 // Update section size inside for-loop, so that SIZEOF
359 // works correctly in the case below:
360 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
361 Sec->setSize(Off);
362 }
363}
364
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000365template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
366 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
George Rimar652852c2016-04-16 10:10:32 +0000367 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000368 // are not explicitly placed into the output file by the linker script.
369 // We place orphan sections at end of file.
370 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000371 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000372 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000373 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000374 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000375 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000376 }
George Rimar652852c2016-04-16 10:10:32 +0000377
Rui Ueyama7c18c282016-04-18 21:00:40 +0000378 // Assign addresses as instructed by linker script SECTIONS sub-commands.
George Rimare32a3592016-08-10 07:59:34 +0000379 Dot = getSizeOfHeaders();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000380 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000381 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000382
George Rimar076fe152016-07-21 06:43:01 +0000383 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
384 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000385 if (Cmd->Name == ".") {
386 Dot = Cmd->Expression(Dot);
387 } else if (Cmd->Sym) {
388 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
389 }
George Rimar652852c2016-04-16 10:10:32 +0000390 continue;
391 }
392
George Rimareefa7582016-08-04 09:29:31 +0000393 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
394 Cmd->Expression(Dot);
395 continue;
396 }
397
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000398 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000399 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000400 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000401 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000402 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000403 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000404 continue;
George Rimar652852c2016-04-16 10:10:32 +0000405
George Rimar58e5c4d2016-07-25 08:29:46 +0000406 if (Cmd->AddrExpr)
407 Dot = Cmd->AddrExpr(Dot);
408
George Rimar630c6172016-07-26 18:06:29 +0000409 if (Cmd->AlignExpr)
410 Sec->updateAlignment(Cmd->AlignExpr(Dot));
411
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000412 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
413 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000414 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000415 Sec->setVA(TVA);
Eugene Leviantceabe802016-08-11 07:56:43 +0000416 assignOffsets(Sec);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000417 ThreadBssOffset = TVA - Dot + Sec->getSize();
418 continue;
419 }
George Rimar652852c2016-04-16 10:10:32 +0000420
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000421 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000422 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000423 Sec->setVA(Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000424 assignOffsets(Sec);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000425 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000426 Dot += Sec->getSize();
427 continue;
428 }
George Rimar652852c2016-04-16 10:10:32 +0000429 }
430 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000431
Rafael Espindola64c32d62016-07-07 14:28:47 +0000432 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000433 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000434 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
435 Out<ELFT>::ProgramHeaders->getSize(),
436 Target->PageSize);
437 Out<ELFT>::ElfHeader->setVA(MinVA);
438 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000439}
440
Rui Ueyama07320e42016-04-20 20:13:41 +0000441template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000442std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
443 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000444 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445
446 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000447 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
448 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000449
450 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000451 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000452 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000453 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000454
455 switch (Cmd.Type) {
456 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000457 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000458 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000459 break;
460 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000461 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000462 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000463 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000464 }
465 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000466 case PT_GNU_EH_FRAME:
467 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000468 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000469 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000470 }
471 break;
472 }
473 }
474
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000475 PhdrEntry<ELFT> *Load = nullptr;
476 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 for (OutputSectionBase<ELFT> *Sec : Sections) {
478 if (!(Sec->getFlags() & SHF_ALLOC))
479 break;
480
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000481 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 if (!PhdrIds.empty()) {
483 // Assign headers specified by linker script
484 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000485 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000486 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000487 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 }
489 } else {
490 // If we have no load segment or flags've changed then we want new load
491 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000492 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000494 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000495 Flags = NewFlags;
496 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000497 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000499 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000500 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000501}
502
503template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000504ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000505 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
506 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
507 if (Cmd->Name == Name)
508 return Cmd->Filler;
509 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000510}
511
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000512// Returns the index of the given section name in linker script
513// SECTIONS commands. Sections are laid out as the same order as they
514// were in the script. If a given name did not appear in the script,
515// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000516template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000517 int I = 0;
518 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
519 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
520 if (Cmd->Name == Name)
521 return I;
522 ++I;
523 }
524 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000525}
526
527// A compartor to sort output sections. Returns -1 or 1 if
528// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000529template <class ELFT>
530int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000531 int I = getSectionIndex(A);
532 int J = getSectionIndex(B);
533 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000534 return 0;
535 return I < J ? -1 : 1;
536}
537
Eugene Leviantbbe38602016-07-19 09:25:43 +0000538template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
539 return !Opt.PhdrsCommands.empty();
540}
541
George Rimar9e694502016-07-29 16:18:47 +0000542template <class ELFT>
543typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
544 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
545 if (Sec->getName() == Name)
546 return Sec->getSize();
547 error("undefined section " + Name);
548 return 0;
549}
550
George Rimare32a3592016-08-10 07:59:34 +0000551template <class ELFT>
552typename ELFT::uint LinkerScript<ELFT>::getSizeOfHeaders() {
553 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
554}
555
Eugene Leviantbbe38602016-07-19 09:25:43 +0000556// Returns indices of ELF headers containing specific section, identified
557// by Name. Each index is a zero based number of ELF header listed within
558// PHDRS {} script block.
559template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000560std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000561 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
562 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000563 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000564 continue;
565
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000566 std::vector<size_t> Ret;
567 for (StringRef PhdrName : Cmd->Phdrs)
568 Ret.push_back(getPhdrIndex(PhdrName));
569 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000570 }
George Rimar31d842f2016-07-20 16:43:03 +0000571 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000572}
573
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000574template <class ELFT>
575size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
576 size_t I = 0;
577 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
578 if (Cmd.Name == PhdrName)
579 return I;
580 ++I;
581 }
582 error("section header '" + PhdrName + "' is not listed in PHDRS");
583 return 0;
584}
585
Rui Ueyama07320e42016-04-20 20:13:41 +0000586class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000587 typedef void (ScriptParser::*Handler)();
588
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000589public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000590 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000591
Rui Ueyama4a465392016-04-22 22:59:24 +0000592 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000593
594private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000595 void addFile(StringRef Path);
596
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000597 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000598 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000599 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000600 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000601 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000602 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000603 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000604 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000605 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000606 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000607 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000608 void readSections();
609
Rui Ueyama113cdec2016-07-24 23:05:57 +0000610 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000611 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000612 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000613 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000614 InputSectionDescription *readInputSectionDescription();
615 std::vector<StringRef> readInputFilePatterns();
616 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000617 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000618 SortKind readSortKind();
Rui Ueyama10416562016-08-04 02:03:27 +0000619 SymbolAssignment *readProvide(bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000620 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000621 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000622 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000623 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000624
625 Expr readExpr();
626 Expr readExpr1(Expr Lhs, int MinPrec);
627 Expr readPrimary();
628 Expr readTernary(Expr Cond);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000629
George Rimarc3794e52016-02-24 09:21:47 +0000630 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000631 ScriptConfiguration &Opt = *ScriptConfig;
632 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000633 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000634};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000635
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000636const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000637 {"ENTRY", &ScriptParser::readEntry},
638 {"EXTERN", &ScriptParser::readExtern},
639 {"GROUP", &ScriptParser::readGroup},
640 {"INCLUDE", &ScriptParser::readInclude},
641 {"INPUT", &ScriptParser::readGroup},
642 {"OUTPUT", &ScriptParser::readOutput},
643 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
644 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000645 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000646 {"SEARCH_DIR", &ScriptParser::readSearchDir},
647 {"SECTIONS", &ScriptParser::readSections},
648 {";", &ScriptParser::readNothing}};
649
Rui Ueyama717677a2016-02-11 21:17:59 +0000650void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000651 while (!atEOF()) {
652 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000653 if (Handler Fn = Cmd.lookup(Tok))
654 (this->*Fn)();
655 else
George Rimar57610422016-03-11 14:43:02 +0000656 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000657 }
658}
659
Rui Ueyama717677a2016-02-11 21:17:59 +0000660void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000661 if (IsUnderSysroot && S.startswith("/")) {
662 SmallString<128> Path;
663 (Config->Sysroot + S).toStringRef(Path);
664 if (sys::fs::exists(Path)) {
665 Driver->addFile(Saver.save(Path.str()));
666 return;
667 }
668 }
669
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000670 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000671 Driver->addFile(S);
672 } else if (S.startswith("=")) {
673 if (Config->Sysroot.empty())
674 Driver->addFile(S.substr(1));
675 else
676 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
677 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000678 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000679 } else if (sys::fs::exists(S)) {
680 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000681 } else {
682 std::string Path = findFromSearchPaths(S);
683 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000684 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000685 else
686 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000687 }
688}
689
Rui Ueyama717677a2016-02-11 21:17:59 +0000690void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000691 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000692 bool Orig = Config->AsNeeded;
693 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000694 while (!Error && !skip(")"))
695 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000696 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000697}
698
Rui Ueyama717677a2016-02-11 21:17:59 +0000699void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000700 // -e <symbol> takes predecence over ENTRY(<symbol>).
701 expect("(");
702 StringRef Tok = next();
703 if (Config->Entry.empty())
704 Config->Entry = Tok;
705 expect(")");
706}
707
Rui Ueyama717677a2016-02-11 21:17:59 +0000708void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000709 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000710 while (!Error && !skip(")"))
711 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000712}
713
Rui Ueyama717677a2016-02-11 21:17:59 +0000714void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000715 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000716 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000717 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000718 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000719 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000720 else
721 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000722 }
723}
724
Rui Ueyama717677a2016-02-11 21:17:59 +0000725void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000726 StringRef Tok = next();
727 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000728 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000729 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000730 return;
731 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000732 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000733 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
734 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000735 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000736}
737
Rui Ueyama717677a2016-02-11 21:17:59 +0000738void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000739 // -o <file> takes predecence over OUTPUT(<file>).
740 expect("(");
741 StringRef Tok = next();
742 if (Config->OutputFile.empty())
743 Config->OutputFile = Tok;
744 expect(")");
745}
746
Rui Ueyama717677a2016-02-11 21:17:59 +0000747void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000748 // Error checking only for now.
749 expect("(");
750 next();
751 expect(")");
752}
753
Rui Ueyama717677a2016-02-11 21:17:59 +0000754void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000755 // Error checking only for now.
756 expect("(");
757 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000758 StringRef Tok = next();
759 if (Tok == ")")
760 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000761 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000762 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000763 return;
764 }
Davide Italiano6836c612015-10-12 21:08:41 +0000765 next();
766 expect(",");
767 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000768 expect(")");
769}
770
Eugene Leviantbbe38602016-07-19 09:25:43 +0000771void ScriptParser::readPhdrs() {
772 expect("{");
773 while (!Error && !skip("}")) {
774 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000775 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000776 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
777
778 PhdrCmd.Type = readPhdrType();
779 do {
780 Tok = next();
781 if (Tok == ";")
782 break;
783 if (Tok == "FILEHDR")
784 PhdrCmd.HasFilehdr = true;
785 else if (Tok == "PHDRS")
786 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000787 else if (Tok == "FLAGS") {
788 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000789 // Passing 0 for the value of dot is a bit of a hack. It means that
790 // we accept expressions like ".|1".
791 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000792 expect(")");
793 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000794 setError("unexpected header attribute: " + Tok);
795 } while (!Error);
796 }
797}
798
Rui Ueyama717677a2016-02-11 21:17:59 +0000799void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000800 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000801 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000802 expect(")");
803}
804
Rui Ueyama717677a2016-02-11 21:17:59 +0000805void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000806 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000807 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000808 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000809 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000810 BaseCommand *Cmd = readProvideOrAssignment(Tok);
811 if (!Cmd) {
812 if (Tok == "ASSERT")
813 Cmd = new AssertCommand(readAssert());
814 else
815 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000816 }
Rui Ueyama10416562016-08-04 02:03:27 +0000817 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000818 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000819}
820
Rui Ueyama708019c2016-07-24 18:19:40 +0000821static int precedence(StringRef Op) {
822 return StringSwitch<int>(Op)
823 .Case("*", 4)
824 .Case("/", 4)
825 .Case("+", 3)
826 .Case("-", 3)
827 .Case("<", 2)
828 .Case(">", 2)
829 .Case(">=", 2)
830 .Case("<=", 2)
831 .Case("==", 2)
832 .Case("!=", 2)
833 .Case("&", 1)
834 .Default(-1);
835}
836
Rui Ueyama10416562016-08-04 02:03:27 +0000837std::vector<StringRef> ScriptParser::readInputFilePatterns() {
838 std::vector<StringRef> V;
839 while (!Error && !skip(")"))
840 V.push_back(next());
841 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000842}
843
Rui Ueyama742c3832016-08-04 22:27:00 +0000844SortKind ScriptParser::readSortKind() {
845 if (skip("SORT") || skip("SORT_BY_NAME"))
846 return SortByName;
847 if (skip("SORT_BY_ALIGNMENT"))
848 return SortByAlignment;
849 return SortNone;
850}
851
Rui Ueyama10416562016-08-04 02:03:27 +0000852InputSectionDescription *ScriptParser::readInputSectionRules() {
853 auto *Cmd = new InputSectionDescription;
854 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000855 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000856
Rui Ueyama742c3832016-08-04 22:27:00 +0000857 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000858 if (skip("EXCLUDE_FILE")) {
859 expect("(");
860 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000861 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000862 }
George Rimar06598002016-07-28 21:51:30 +0000863
Rui Ueyama742c3832016-08-04 22:27:00 +0000864 // Read SORT().
865 if (SortKind K1 = readSortKind()) {
866 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000867 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000868 if (SortKind K2 = readSortKind()) {
869 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000870 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000871 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000872 expect(")");
873 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000874 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000875 }
George Rimar0702c4e2016-07-29 15:32:46 +0000876 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000877 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000878 }
George Rimar0702c4e2016-07-29 15:32:46 +0000879
Rui Ueyama10416562016-08-04 02:03:27 +0000880 Cmd->SectionPatterns = readInputFilePatterns();
881 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000882}
883
Rui Ueyama10416562016-08-04 02:03:27 +0000884InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000885 // Input section wildcard can be surrounded by KEEP.
886 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
887 if (skip("KEEP")) {
888 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000889 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000890 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000891 Opt.KeptSections.insert(Opt.KeptSections.end(),
892 Cmd->SectionPatterns.begin(),
893 Cmd->SectionPatterns.end());
894 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000895 }
Rui Ueyama10416562016-08-04 02:03:27 +0000896 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000897}
898
Rui Ueyama10416562016-08-04 02:03:27 +0000899Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000900 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000901 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000902 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000903 return E;
George Rimar630c6172016-07-26 18:06:29 +0000904}
905
George Rimar03fc0102016-07-28 07:18:23 +0000906void ScriptParser::readSort() {
907 expect("(");
908 expect("CONSTRUCTORS");
909 expect(")");
910}
911
George Rimareefa7582016-08-04 09:29:31 +0000912Expr ScriptParser::readAssert() {
913 expect("(");
914 Expr E = readExpr();
915 expect(",");
916 StringRef Msg = next();
917 expect(")");
918 return [=](uint64_t Dot) {
919 uint64_t V = E(Dot);
920 if (!V)
921 error(Msg);
922 return V;
923 };
924}
925
Rui Ueyama10416562016-08-04 02:03:27 +0000926OutputSectionCommand *
927ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000928 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000929
930 // Read an address expression.
931 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
932 if (peek() != ":")
933 Cmd->AddrExpr = readExpr();
934
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000935 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000936
George Rimar630c6172016-07-26 18:06:29 +0000937 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000938 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000939
Davide Italiano246f6812016-07-22 03:36:24 +0000940 // Parse constraints.
941 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000942 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000943 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000944 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000945 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000946
Rui Ueyama025d59b2016-02-02 20:27:59 +0000947 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000948 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000949 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000950 continue;
951 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000952
953 StringRef Tok = next();
954 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
955 Cmd->Commands.emplace_back(Assignment);
956 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000957 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000958 else
959 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000960 }
George Rimar076fe152016-07-21 06:43:01 +0000961 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000962 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000963 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000964}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000965
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000966std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000967 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000968 if (!Tok.startswith("="))
969 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000970 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000971
972 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000973 if (Tok.startswith("=0x"))
974 return parseHex(Tok.substr(3));
975
Rui Ueyama965827d2016-08-03 23:25:15 +0000976 // Read a decimal or octal value as a big-endian 32 bit value.
977 // Why do this? I don't know, but that's what gold does.
978 uint32_t V;
979 if (Tok.substr(1).getAsInteger(0, V)) {
980 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000981 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000982 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000983 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000984}
985
Rui Ueyama10416562016-08-04 02:03:27 +0000986SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000987 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000988 SymbolAssignment *Cmd = readAssignment(next());
989 Cmd->Provide = true;
990 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000991 expect(")");
992 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000993 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000994}
995
Eugene Leviantceabe802016-08-11 07:56:43 +0000996SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
997 SymbolAssignment *Cmd = nullptr;
998 if (peek() == "=" || peek() == "+=") {
999 Cmd = readAssignment(Tok);
1000 expect(";");
1001 } else if (Tok == "PROVIDE") {
1002 Cmd = readProvide(false);
1003 } else if (Tok == "PROVIDE_HIDDEN") {
1004 Cmd = readProvide(true);
1005 }
1006 return Cmd;
1007}
1008
George Rimar30835ea2016-07-28 21:08:56 +00001009static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1010 if (S == ".")
1011 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001012
George Rimara9c5a522016-07-26 18:18:58 +00001013 switch (Config->EKind) {
1014 case ELF32LEKind:
1015 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1016 return B->getVA<ELF32LE>();
1017 break;
1018 case ELF32BEKind:
1019 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1020 return B->getVA<ELF32BE>();
1021 break;
1022 case ELF64LEKind:
1023 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1024 return B->getVA<ELF64LE>();
1025 break;
1026 case ELF64BEKind:
1027 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1028 return B->getVA<ELF64BE>();
1029 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001030 default:
George Rimarb567b622016-07-26 18:46:13 +00001031 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001032 }
1033 error("symbol not found: " + S);
1034 return 0;
1035}
1036
George Rimar9e694502016-07-29 16:18:47 +00001037static uint64_t getSectionSize(StringRef Name) {
1038 switch (Config->EKind) {
1039 case ELF32LEKind:
1040 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1041 case ELF32BEKind:
1042 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1043 case ELF64LEKind:
1044 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1045 case ELF64BEKind:
1046 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1047 default:
1048 llvm_unreachable("unsupported target");
1049 }
George Rimar9e694502016-07-29 16:18:47 +00001050}
1051
George Rimare32a3592016-08-10 07:59:34 +00001052static uint64_t getSizeOfHeaders() {
1053 switch (Config->EKind) {
1054 case ELF32LEKind:
1055 return Script<ELF32LE>::X->getSizeOfHeaders();
1056 case ELF32BEKind:
1057 return Script<ELF32BE>::X->getSizeOfHeaders();
1058 case ELF64LEKind:
1059 return Script<ELF64LE>::X->getSizeOfHeaders();
1060 case ELF64BEKind:
1061 return Script<ELF64BE>::X->getSizeOfHeaders();
1062 default:
1063 llvm_unreachable("unsupported target");
1064 }
1065}
1066
George Rimar30835ea2016-07-28 21:08:56 +00001067SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1068 StringRef Op = next();
1069 assert(Op == "=" || Op == "+=");
1070 Expr E = readExpr();
1071 if (Op == "+=")
1072 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001073 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001074}
1075
1076// This is an operator-precedence parser to parse a linker
1077// script expression.
1078Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1079
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001080static Expr combine(StringRef Op, Expr L, Expr R) {
1081 if (Op == "*")
1082 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1083 if (Op == "/") {
1084 return [=](uint64_t Dot) -> uint64_t {
1085 uint64_t RHS = R(Dot);
1086 if (RHS == 0) {
1087 error("division by zero");
1088 return 0;
1089 }
1090 return L(Dot) / RHS;
1091 };
1092 }
1093 if (Op == "+")
1094 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1095 if (Op == "-")
1096 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1097 if (Op == "<")
1098 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1099 if (Op == ">")
1100 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1101 if (Op == ">=")
1102 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1103 if (Op == "<=")
1104 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1105 if (Op == "==")
1106 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1107 if (Op == "!=")
1108 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1109 if (Op == "&")
1110 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1111 llvm_unreachable("invalid operator");
1112}
1113
Rui Ueyama708019c2016-07-24 18:19:40 +00001114// This is a part of the operator-precedence parser. This function
1115// assumes that the remaining token stream starts with an operator.
1116Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1117 while (!atEOF() && !Error) {
1118 // Read an operator and an expression.
1119 StringRef Op1 = peek();
1120 if (Op1 == "?")
1121 return readTernary(Lhs);
1122 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001123 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001124 next();
1125 Expr Rhs = readPrimary();
1126
1127 // Evaluate the remaining part of the expression first if the
1128 // next operator has greater precedence than the previous one.
1129 // For example, if we have read "+" and "3", and if the next
1130 // operator is "*", then we'll evaluate 3 * ... part first.
1131 while (!atEOF()) {
1132 StringRef Op2 = peek();
1133 if (precedence(Op2) <= precedence(Op1))
1134 break;
1135 Rhs = readExpr1(Rhs, precedence(Op2));
1136 }
1137
1138 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001139 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001140 return Lhs;
1141}
1142
1143uint64_t static getConstant(StringRef S) {
1144 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1145 return Target->PageSize;
1146 error("unknown constant: " + S);
1147 return 0;
1148}
1149
1150Expr ScriptParser::readPrimary() {
1151 StringRef Tok = next();
1152
Rui Ueyama708019c2016-07-24 18:19:40 +00001153 if (Tok == "(") {
1154 Expr E = readExpr();
1155 expect(")");
1156 return E;
1157 }
1158
1159 // Built-in functions are parsed here.
1160 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001161 if (Tok == "ASSERT")
1162 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001163 if (Tok == "ALIGN") {
1164 expect("(");
1165 Expr E = readExpr();
1166 expect(")");
1167 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1168 }
1169 if (Tok == "CONSTANT") {
1170 expect("(");
1171 StringRef Tok = next();
1172 expect(")");
1173 return [=](uint64_t Dot) { return getConstant(Tok); };
1174 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001175 if (Tok == "SEGMENT_START") {
1176 expect("(");
1177 next();
1178 expect(",");
1179 uint64_t Val;
1180 next().getAsInteger(0, Val);
1181 expect(")");
1182 return [=](uint64_t Dot) { return Val; };
1183 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001184 if (Tok == "DATA_SEGMENT_ALIGN") {
1185 expect("(");
1186 Expr E = readExpr();
1187 expect(",");
1188 readExpr();
1189 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001190 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001191 }
1192 if (Tok == "DATA_SEGMENT_END") {
1193 expect("(");
1194 expect(".");
1195 expect(")");
1196 return [](uint64_t Dot) { return Dot; };
1197 }
George Rimar276b4e62016-07-26 17:58:44 +00001198 // GNU linkers implements more complicated logic to handle
1199 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1200 // the next page boundary for simplicity.
1201 if (Tok == "DATA_SEGMENT_RELRO_END") {
1202 expect("(");
1203 next();
1204 expect(",");
1205 readExpr();
1206 expect(")");
1207 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1208 }
George Rimar9e694502016-07-29 16:18:47 +00001209 if (Tok == "SIZEOF") {
1210 expect("(");
1211 StringRef Name = next();
1212 expect(")");
1213 return [=](uint64_t Dot) { return getSectionSize(Name); };
1214 }
George Rimare32a3592016-08-10 07:59:34 +00001215 if (Tok == "SIZEOF_HEADERS")
1216 return [=](uint64_t Dot) { return getSizeOfHeaders(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001217
George Rimara9c5a522016-07-26 18:18:58 +00001218 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001219 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001220 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001221 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001222 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001223 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001224 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001225 return [=](uint64_t Dot) { return V; };
1226}
1227
1228Expr ScriptParser::readTernary(Expr Cond) {
1229 next();
1230 Expr L = readExpr();
1231 expect(":");
1232 Expr R = readExpr();
1233 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1234}
1235
Eugene Leviantbbe38602016-07-19 09:25:43 +00001236std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1237 std::vector<StringRef> Phdrs;
1238 while (!Error && peek().startswith(":")) {
1239 StringRef Tok = next();
1240 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1241 if (Tok.empty()) {
1242 setError("section header name is empty");
1243 break;
1244 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001245 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001246 }
1247 return Phdrs;
1248}
1249
1250unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001251 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001252 unsigned Ret = StringSwitch<unsigned>(Tok)
1253 .Case("PT_NULL", PT_NULL)
1254 .Case("PT_LOAD", PT_LOAD)
1255 .Case("PT_DYNAMIC", PT_DYNAMIC)
1256 .Case("PT_INTERP", PT_INTERP)
1257 .Case("PT_NOTE", PT_NOTE)
1258 .Case("PT_SHLIB", PT_SHLIB)
1259 .Case("PT_PHDR", PT_PHDR)
1260 .Case("PT_TLS", PT_TLS)
1261 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1262 .Case("PT_GNU_STACK", PT_GNU_STACK)
1263 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1264 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001265
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001266 if (Ret == (unsigned)-1) {
1267 setError("invalid program header type: " + Tok);
1268 return PT_NULL;
1269 }
1270 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001271}
1272
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001273static bool isUnderSysroot(StringRef Path) {
1274 if (Config->Sysroot == "")
1275 return false;
1276 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1277 if (sys::fs::equivalent(Config->Sysroot, Path))
1278 return true;
1279 return false;
1280}
1281
Rui Ueyama07320e42016-04-20 20:13:41 +00001282// Entry point.
1283void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001284 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001285 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001286}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001287
Rui Ueyama07320e42016-04-20 20:13:41 +00001288template class elf::LinkerScript<ELF32LE>;
1289template class elf::LinkerScript<ELF32BE>;
1290template class elf::LinkerScript<ELF64LE>;
1291template class elf::LinkerScript<ELF64BE>;