blob: f6712d32043db514bf6bb2a19fddc67334dba7cf [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 Ueyamaf34d0e02016-08-12 01:24:53 +000092template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
93template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
94
Rui Ueyama07320e42016-04-20 20:13:41 +000095template <class ELFT>
96bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000097 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000098 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000099 return true;
100 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000101}
102
Rui Ueyama63dc6502016-07-25 22:41:42 +0000103static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
104 for (StringRef Pat : Patterns)
105 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000106 return true;
107 return false;
108}
109
George Rimar06598002016-07-28 21:51:30 +0000110static bool fileMatches(const InputSectionDescription *Desc,
111 StringRef Filename) {
112 if (!globMatch(Desc->FilePattern, Filename))
113 return false;
114 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
115}
116
Rui Ueyama6b274812016-07-25 22:51:07 +0000117// Returns input sections filtered by given glob patterns.
118template <class ELFT>
119std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000120LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000121 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000122 std::vector<InputSectionBase<ELFT> *> Ret;
123 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000124 Symtab<ELFT>::X->getObjectFiles()) {
125 if (fileMatches(I, sys::path::filename(F->getName())))
126 for (InputSectionBase<ELFT> *S : F->getSections())
127 if (!isDiscarded(S) && !S->OutSec &&
128 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000129 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000130 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000131
132 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000133 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000134
Rui Ueyama6b274812016-07-25 22:51:07 +0000135 return Ret;
136}
137
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000138// You can define new symbols using linker scripts. For example,
139// ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
140// foo just after abc.o's text section contents. This class is to
141// handle such symbol definitions.
142//
143// In order to handle scripts like the above one, we want to
144// keep symbol definitions in output sections. Because output sections
145// can contain only input sections, we wrap symbol definitions
146// with dummy input sections. This class serves that purpose.
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000147template <class ELFT>
148class elf::LayoutInputSection : public InputSectionBase<ELFT> {
Eugene Leviantceabe802016-08-11 07:56:43 +0000149public:
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000150 explicit LayoutInputSection(SymbolAssignment *Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000151 static bool classof(const InputSectionBase<ELFT> *S);
152 SymbolAssignment *Cmd;
153
154private:
155 typename ELFT::Shdr Hdr;
156};
157
158// Helper class, which builds output section list, also
159// creating symbol sections, when needed
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000160namespace {
Eugene Leviantceabe802016-08-11 07:56:43 +0000161template <class ELFT> class OutputSectionBuilder {
162public:
163 OutputSectionBuilder(OutputSectionFactory<ELFT> &F,
164 std::vector<OutputSectionBase<ELFT> *> *Out)
165 : Factory(F), OutputSections(Out) {}
166
167 void addSection(StringRef OutputName, InputSectionBase<ELFT> *I);
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000168 void addSymbol(LayoutInputSection<ELFT> *S) { PendingSymbols.push_back(S); }
Eugene Leviantceabe802016-08-11 07:56:43 +0000169 void flushSymbols();
170 void flushSection();
Eugene Leviantceabe802016-08-11 07:56:43 +0000171
172private:
173 OutputSectionFactory<ELFT> &Factory;
174 std::vector<OutputSectionBase<ELFT> *> *OutputSections;
175 OutputSectionBase<ELFT> *Current = nullptr;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000176 std::vector<LayoutInputSection<ELFT> *> PendingSymbols;
Eugene Leviantceabe802016-08-11 07:56:43 +0000177};
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000178} // anonymous namespace
Eugene Leviantceabe802016-08-11 07:56:43 +0000179
180template <class T> static T *zero(T *Val) {
181 memset(Val, 0, sizeof(*Val));
182 return Val;
183}
184
185template <class ELFT>
186LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000187 : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
188 InputSectionBase<ELFT>::Layout),
189 Cmd(Cmd) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000190 this->Live = true;
Eugene Leviantceabe802016-08-11 07:56:43 +0000191 Hdr.sh_type = SHT_NOBITS;
192}
193
194template <class ELFT>
195bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
196 return S->SectionKind == InputSectionBase<ELFT>::Layout;
197}
198
199template <class ELFT>
200void OutputSectionBuilder<ELFT>::addSection(StringRef OutputName,
201 InputSectionBase<ELFT> *C) {
George Rimarc3cb8842016-07-29 15:12:48 +0000202 bool IsNew;
Eugene Leviantceabe802016-08-11 07:56:43 +0000203 std::tie(Current, IsNew) = Factory.create(C, OutputName);
George Rimarc3cb8842016-07-29 15:12:48 +0000204 if (IsNew)
Eugene Leviantceabe802016-08-11 07:56:43 +0000205 OutputSections->push_back(Current);
206 flushSymbols();
207 Current->addSection(C);
208}
209
210template <class ELFT> void OutputSectionBuilder<ELFT>::flushSymbols() {
Rui Ueyama16024212016-08-11 23:22:52 +0000211 // Only regular output sections are supported.
212 if (dyn_cast_or_null<OutputSection<ELFT>>(Current)) {
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000213 for (LayoutInputSection<ELFT> *I : PendingSymbols) {
Rui Ueyama16024212016-08-11 23:22:52 +0000214 if (I->Cmd->Name == ".") {
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000215 Current->addSection(I);
Rui Ueyama16024212016-08-11 23:22:52 +0000216 } else if (shouldDefine<ELFT>(I->Cmd)) {
217 addSynthetic<ELFT>(I->Cmd, Current);
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000218 Current->addSection(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000219 }
220 }
Rui Ueyama16024212016-08-11 23:22:52 +0000221 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000222
223 PendingSymbols.clear();
224}
225
226template <class ELFT> void OutputSectionBuilder<ELFT>::flushSection() {
227 flushSymbols();
228 Current = nullptr;
229}
230
Rui Ueyama742c3832016-08-04 22:27:00 +0000231template <class ELFT>
232static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
233 return A->getSectionName() < B->getSectionName();
234}
George Rimar350ece42016-08-03 08:35:59 +0000235
Rui Ueyama742c3832016-08-04 22:27:00 +0000236template <class ELFT>
237static bool compareAlignment(InputSectionBase<ELFT> *A,
238 InputSectionBase<ELFT> *B) {
239 // ">" is not a mistake. Larger alignments are placed before smaller
240 // alignments in order to reduce the amount of padding necessary.
241 // This is compatible with GNU.
242 return A->Alignment > B->Alignment;
243}
George Rimar350ece42016-08-03 08:35:59 +0000244
Rui Ueyama742c3832016-08-04 22:27:00 +0000245template <class ELFT>
246static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
247getComparator(SortKind K) {
248 if (K == SortByName)
249 return compareName<ELFT>;
250 return compareAlignment<ELFT>;
251}
George Rimar0702c4e2016-07-29 15:32:46 +0000252
253template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000254void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
255 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
256 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
257 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
258 S->Live = false;
259 reportDiscarded(S);
260 }
261 }
262 }
263}
264
265template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000266void LinkerScript<ELFT>::createSections(
George Rimar9e694502016-07-29 16:18:47 +0000267 OutputSectionFactory<ELFT> &Factory) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000268 OutputSectionBuilder<ELFT> Builder(Factory, OutputSections);
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000269
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000270 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000271 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000272 if (Cmd->Name == "/DISCARD/") {
273 discard(*Cmd);
274 continue;
275 }
276 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands) {
277 if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base2.get())) {
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000278 Builder.addSymbol(new (LAlloc.Allocate())
279 LayoutInputSection<ELFT>(Cmd2));
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000280 continue;
281 }
282 auto *Cmd2 = cast<InputSectionDescription>(Base2.get());
283 std::vector<InputSectionBase<ELFT> *> Sections = getInputSections(Cmd2);
284 if (Cmd2->SortInner)
285 std::stable_sort(Sections.begin(), Sections.end(),
286 getComparator<ELFT>(Cmd2->SortInner));
287 if (Cmd2->SortOuter)
288 std::stable_sort(Sections.begin(), Sections.end(),
289 getComparator<ELFT>(Cmd2->SortOuter));
290 for (InputSectionBase<ELFT> *S : Sections)
291 Builder.addSection(Cmd->Name, S);
292 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000293
294 Builder.flushSection();
295 } else if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base1.get())) {
Rui Ueyama16024212016-08-11 23:22:52 +0000296 if (shouldDefine<ELFT>(Cmd2))
297 addRegular<ELFT>(Cmd2);
Eugene Leviantceabe802016-08-11 07:56:43 +0000298 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000299 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000300
301 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000302 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
303 Symtab<ELFT>::X->getObjectFiles())
304 for (InputSectionBase<ELFT> *S : F->getSections())
305 if (!isDiscarded(S) && !S->OutSec)
Eugene Leviantceabe802016-08-11 07:56:43 +0000306 Builder.addSection(getOutputSectionName(S), S);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000307
Rui Ueyama3c291e12016-07-25 21:30:00 +0000308 // Remove from the output all the sections which did not meet
309 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000310 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000311}
312
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000313template <class R, class T>
314static inline void removeElementsIf(R &Range, const T &Pred) {
315 Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
316}
317
Rui Ueyama3c291e12016-07-25 21:30:00 +0000318// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000319template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000320 // In this loop, we remove output sections if they don't satisfy
321 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000322 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
323 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
324 if (!Cmd || Cmd->Name == "/DISCARD/")
325 continue;
326
George Rimarbfc4a4b2016-07-26 10:47:09 +0000327 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000328 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000329
Rui Ueyama808d13e2016-08-05 01:05:01 +0000330 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
331 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
332
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000333 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
334 bool Writable = (S->getFlags() & SHF_WRITE);
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000335 return S->getName() == Cmd->Name &&
336 ((RO && Writable) || (RW && !Writable));
George Rimarbfc4a4b2016-07-26 10:47:09 +0000337 });
Rui Ueyama3c291e12016-07-25 21:30:00 +0000338 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000339}
340
Eugene Leviantceabe802016-08-11 07:56:43 +0000341template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000342 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000343 if (!OutSec) {
344 Sec->assignOffsets();
Eugene Leviantceabe802016-08-11 07:56:43 +0000345 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000346 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000347
348 typedef typename ELFT::uint uintX_t;
349 uintX_t Off = 0;
350
351 for (InputSection<ELFT> *I : OutSec->Sections) {
352 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
353 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
354 if (L->Cmd->Name == ".")
355 Off = Value;
356 else
357 cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym)->Value = Value;
358 } else {
359 Off = alignTo(Off, I->Alignment);
360 I->OutSecOff = Off;
361 Off += I->getSize();
362 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000363 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000364 // works correctly in the case below:
365 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
366 Sec->setSize(Off);
367 }
368}
369
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000370template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000371 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000372 // are not explicitly placed into the output file by the linker script.
373 // We place orphan sections at end of file.
374 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000375 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000376 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000377 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000378 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000379 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000380 }
George Rimar652852c2016-04-16 10:10:32 +0000381
Rui Ueyama7c18c282016-04-18 21:00:40 +0000382 // Assign addresses as instructed by linker script SECTIONS sub-commands.
George Rimare32a3592016-08-10 07:59:34 +0000383 Dot = getSizeOfHeaders();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000384 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000385 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000386
George Rimar076fe152016-07-21 06:43:01 +0000387 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
388 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000389 if (Cmd->Name == ".") {
390 Dot = Cmd->Expression(Dot);
391 } else if (Cmd->Sym) {
392 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
393 }
George Rimar652852c2016-04-16 10:10:32 +0000394 continue;
395 }
396
George Rimareefa7582016-08-04 09:29:31 +0000397 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
398 Cmd->Expression(Dot);
399 continue;
400 }
401
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000402 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000403 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000404 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000405 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000406 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar076fe152016-07-21 06:43:01 +0000407 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000408 continue;
George Rimar652852c2016-04-16 10:10:32 +0000409
George Rimar58e5c4d2016-07-25 08:29:46 +0000410 if (Cmd->AddrExpr)
411 Dot = Cmd->AddrExpr(Dot);
412
George Rimar630c6172016-07-26 18:06:29 +0000413 if (Cmd->AlignExpr)
414 Sec->updateAlignment(Cmd->AlignExpr(Dot));
415
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000416 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
417 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000418 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000419 Sec->setVA(TVA);
Eugene Leviantceabe802016-08-11 07:56:43 +0000420 assignOffsets(Sec);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000421 ThreadBssOffset = TVA - Dot + Sec->getSize();
422 continue;
423 }
George Rimar652852c2016-04-16 10:10:32 +0000424
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000425 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000426 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000427 Sec->setVA(Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000428 assignOffsets(Sec);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000429 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000430 Dot += Sec->getSize();
431 continue;
432 }
Rui Ueyama2de509c2016-08-12 00:55:08 +0000433 Sec->assignOffsets();
George Rimar652852c2016-04-16 10:10:32 +0000434 }
435 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000436
Rafael Espindola64c32d62016-07-07 14:28:47 +0000437 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000438 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000439 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
440 Out<ELFT>::ProgramHeaders->getSize(),
441 Target->PageSize);
442 Out<ELFT>::ElfHeader->setVA(MinVA);
443 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000444}
445
Rui Ueyama07320e42016-04-20 20:13:41 +0000446template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000447std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
448 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000449 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000450
451 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000452 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
453 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000454
455 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000456 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000457 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000458 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000459
460 switch (Cmd.Type) {
461 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000462 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000463 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000464 break;
465 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000466 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000467 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000468 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000469 }
470 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 case PT_GNU_EH_FRAME:
472 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000473 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000474 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000475 }
476 break;
477 }
478 }
479
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000480 PhdrEntry<ELFT> *Load = nullptr;
481 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 for (OutputSectionBase<ELFT> *Sec : Sections) {
483 if (!(Sec->getFlags() & SHF_ALLOC))
484 break;
485
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000486 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 if (!PhdrIds.empty()) {
488 // Assign headers specified by linker script
489 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000490 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000491 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000492 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 }
494 } else {
495 // If we have no load segment or flags've changed then we want new load
496 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000497 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000499 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000500 Flags = NewFlags;
501 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000502 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000503 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000504 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000505 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000506}
507
508template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000509ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000510 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
511 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
512 if (Cmd->Name == Name)
513 return Cmd->Filler;
514 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000515}
516
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000517// Returns the index of the given section name in linker script
518// SECTIONS commands. Sections are laid out as the same order as they
519// were in the script. If a given name did not appear in the script,
520// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000521template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000522 int I = 0;
523 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
524 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
525 if (Cmd->Name == Name)
526 return I;
527 ++I;
528 }
529 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000530}
531
532// A compartor to sort output sections. Returns -1 or 1 if
533// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000534template <class ELFT>
535int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000536 int I = getSectionIndex(A);
537 int J = getSectionIndex(B);
538 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000539 return 0;
540 return I < J ? -1 : 1;
541}
542
Eugene Leviantbbe38602016-07-19 09:25:43 +0000543template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
544 return !Opt.PhdrsCommands.empty();
545}
546
George Rimar9e694502016-07-29 16:18:47 +0000547template <class ELFT>
548typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
549 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
550 if (Sec->getName() == Name)
551 return Sec->getSize();
552 error("undefined section " + Name);
553 return 0;
554}
555
George Rimare32a3592016-08-10 07:59:34 +0000556template <class ELFT>
557typename ELFT::uint LinkerScript<ELFT>::getSizeOfHeaders() {
558 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
559}
560
Eugene Leviantbbe38602016-07-19 09:25:43 +0000561// Returns indices of ELF headers containing specific section, identified
562// by Name. Each index is a zero based number of ELF header listed within
563// PHDRS {} script block.
564template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000565std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000566 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
567 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000568 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000569 continue;
570
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000571 std::vector<size_t> Ret;
572 for (StringRef PhdrName : Cmd->Phdrs)
573 Ret.push_back(getPhdrIndex(PhdrName));
574 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000575 }
George Rimar31d842f2016-07-20 16:43:03 +0000576 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000577}
578
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000579template <class ELFT>
580size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
581 size_t I = 0;
582 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
583 if (Cmd.Name == PhdrName)
584 return I;
585 ++I;
586 }
587 error("section header '" + PhdrName + "' is not listed in PHDRS");
588 return 0;
589}
590
Rui Ueyama07320e42016-04-20 20:13:41 +0000591class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000592 typedef void (ScriptParser::*Handler)();
593
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000594public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000595 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000596
Rui Ueyama4a465392016-04-22 22:59:24 +0000597 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000598
599private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000600 void addFile(StringRef Path);
601
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000602 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000603 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000604 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000605 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000606 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000607 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000608 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000609 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000610 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000611 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000612 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000613 void readSections();
614
Rui Ueyama113cdec2016-07-24 23:05:57 +0000615 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000616 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000617 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000618 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000619 InputSectionDescription *readInputSectionDescription();
620 std::vector<StringRef> readInputFilePatterns();
621 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000622 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000623 SortKind readSortKind();
Rui Ueyama10416562016-08-04 02:03:27 +0000624 SymbolAssignment *readProvide(bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000625 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000626 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000627 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000628 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000629
630 Expr readExpr();
631 Expr readExpr1(Expr Lhs, int MinPrec);
632 Expr readPrimary();
633 Expr readTernary(Expr Cond);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000634
George Rimarc3794e52016-02-24 09:21:47 +0000635 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000636 ScriptConfiguration &Opt = *ScriptConfig;
637 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000638 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000639};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000640
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000641const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000642 {"ENTRY", &ScriptParser::readEntry},
643 {"EXTERN", &ScriptParser::readExtern},
644 {"GROUP", &ScriptParser::readGroup},
645 {"INCLUDE", &ScriptParser::readInclude},
646 {"INPUT", &ScriptParser::readGroup},
647 {"OUTPUT", &ScriptParser::readOutput},
648 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
649 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000650 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000651 {"SEARCH_DIR", &ScriptParser::readSearchDir},
652 {"SECTIONS", &ScriptParser::readSections},
653 {";", &ScriptParser::readNothing}};
654
Rui Ueyama717677a2016-02-11 21:17:59 +0000655void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000656 while (!atEOF()) {
657 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000658 if (Handler Fn = Cmd.lookup(Tok))
659 (this->*Fn)();
660 else
George Rimar57610422016-03-11 14:43:02 +0000661 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000662 }
663}
664
Rui Ueyama717677a2016-02-11 21:17:59 +0000665void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000666 if (IsUnderSysroot && S.startswith("/")) {
667 SmallString<128> Path;
668 (Config->Sysroot + S).toStringRef(Path);
669 if (sys::fs::exists(Path)) {
670 Driver->addFile(Saver.save(Path.str()));
671 return;
672 }
673 }
674
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000675 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000676 Driver->addFile(S);
677 } else if (S.startswith("=")) {
678 if (Config->Sysroot.empty())
679 Driver->addFile(S.substr(1));
680 else
681 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
682 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000683 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000684 } else if (sys::fs::exists(S)) {
685 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000686 } else {
687 std::string Path = findFromSearchPaths(S);
688 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000689 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000690 else
691 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000692 }
693}
694
Rui Ueyama717677a2016-02-11 21:17:59 +0000695void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000696 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000697 bool Orig = Config->AsNeeded;
698 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000699 while (!Error && !skip(")"))
700 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000701 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000702}
703
Rui Ueyama717677a2016-02-11 21:17:59 +0000704void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000705 // -e <symbol> takes predecence over ENTRY(<symbol>).
706 expect("(");
707 StringRef Tok = next();
708 if (Config->Entry.empty())
709 Config->Entry = Tok;
710 expect(")");
711}
712
Rui Ueyama717677a2016-02-11 21:17:59 +0000713void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000714 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000715 while (!Error && !skip(")"))
716 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000717}
718
Rui Ueyama717677a2016-02-11 21:17:59 +0000719void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000720 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000721 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000722 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000723 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000724 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000725 else
726 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000727 }
728}
729
Rui Ueyama717677a2016-02-11 21:17:59 +0000730void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000731 StringRef Tok = next();
732 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000733 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000734 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000735 return;
736 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000737 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000738 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
739 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000740 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000741}
742
Rui Ueyama717677a2016-02-11 21:17:59 +0000743void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000744 // -o <file> takes predecence over OUTPUT(<file>).
745 expect("(");
746 StringRef Tok = next();
747 if (Config->OutputFile.empty())
748 Config->OutputFile = Tok;
749 expect(")");
750}
751
Rui Ueyama717677a2016-02-11 21:17:59 +0000752void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000753 // Error checking only for now.
754 expect("(");
755 next();
756 expect(")");
757}
758
Rui Ueyama717677a2016-02-11 21:17:59 +0000759void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000760 // Error checking only for now.
761 expect("(");
762 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000763 StringRef Tok = next();
764 if (Tok == ")")
765 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000766 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000767 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000768 return;
769 }
Davide Italiano6836c612015-10-12 21:08:41 +0000770 next();
771 expect(",");
772 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000773 expect(")");
774}
775
Eugene Leviantbbe38602016-07-19 09:25:43 +0000776void ScriptParser::readPhdrs() {
777 expect("{");
778 while (!Error && !skip("}")) {
779 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000780 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000781 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
782
783 PhdrCmd.Type = readPhdrType();
784 do {
785 Tok = next();
786 if (Tok == ";")
787 break;
788 if (Tok == "FILEHDR")
789 PhdrCmd.HasFilehdr = true;
790 else if (Tok == "PHDRS")
791 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000792 else if (Tok == "FLAGS") {
793 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000794 // Passing 0 for the value of dot is a bit of a hack. It means that
795 // we accept expressions like ".|1".
796 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000797 expect(")");
798 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000799 setError("unexpected header attribute: " + Tok);
800 } while (!Error);
801 }
802}
803
Rui Ueyama717677a2016-02-11 21:17:59 +0000804void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000805 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000806 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000807 expect(")");
808}
809
Rui Ueyama717677a2016-02-11 21:17:59 +0000810void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000811 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000812 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000813 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000814 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000815 BaseCommand *Cmd = readProvideOrAssignment(Tok);
816 if (!Cmd) {
817 if (Tok == "ASSERT")
818 Cmd = new AssertCommand(readAssert());
819 else
820 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000821 }
Rui Ueyama10416562016-08-04 02:03:27 +0000822 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000823 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000824}
825
Rui Ueyama708019c2016-07-24 18:19:40 +0000826static int precedence(StringRef Op) {
827 return StringSwitch<int>(Op)
828 .Case("*", 4)
829 .Case("/", 4)
830 .Case("+", 3)
831 .Case("-", 3)
832 .Case("<", 2)
833 .Case(">", 2)
834 .Case(">=", 2)
835 .Case("<=", 2)
836 .Case("==", 2)
837 .Case("!=", 2)
838 .Case("&", 1)
839 .Default(-1);
840}
841
Rui Ueyama10416562016-08-04 02:03:27 +0000842std::vector<StringRef> ScriptParser::readInputFilePatterns() {
843 std::vector<StringRef> V;
844 while (!Error && !skip(")"))
845 V.push_back(next());
846 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000847}
848
Rui Ueyama742c3832016-08-04 22:27:00 +0000849SortKind ScriptParser::readSortKind() {
850 if (skip("SORT") || skip("SORT_BY_NAME"))
851 return SortByName;
852 if (skip("SORT_BY_ALIGNMENT"))
853 return SortByAlignment;
854 return SortNone;
855}
856
Rui Ueyama10416562016-08-04 02:03:27 +0000857InputSectionDescription *ScriptParser::readInputSectionRules() {
858 auto *Cmd = new InputSectionDescription;
859 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000860 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000861
Rui Ueyama742c3832016-08-04 22:27:00 +0000862 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000863 if (skip("EXCLUDE_FILE")) {
864 expect("(");
865 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000866 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000867 }
George Rimar06598002016-07-28 21:51:30 +0000868
Rui Ueyama742c3832016-08-04 22:27:00 +0000869 // Read SORT().
870 if (SortKind K1 = readSortKind()) {
871 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000872 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000873 if (SortKind K2 = readSortKind()) {
874 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000875 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000876 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000877 expect(")");
878 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000879 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000880 }
George Rimar0702c4e2016-07-29 15:32:46 +0000881 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000882 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000883 }
George Rimar0702c4e2016-07-29 15:32:46 +0000884
Rui Ueyama10416562016-08-04 02:03:27 +0000885 Cmd->SectionPatterns = readInputFilePatterns();
886 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000887}
888
Rui Ueyama10416562016-08-04 02:03:27 +0000889InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000890 // Input section wildcard can be surrounded by KEEP.
891 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
892 if (skip("KEEP")) {
893 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000894 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000895 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000896 Opt.KeptSections.insert(Opt.KeptSections.end(),
897 Cmd->SectionPatterns.begin(),
898 Cmd->SectionPatterns.end());
899 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000900 }
Rui Ueyama10416562016-08-04 02:03:27 +0000901 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000902}
903
Rui Ueyama10416562016-08-04 02:03:27 +0000904Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000905 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000906 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000907 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000908 return E;
George Rimar630c6172016-07-26 18:06:29 +0000909}
910
George Rimar03fc0102016-07-28 07:18:23 +0000911void ScriptParser::readSort() {
912 expect("(");
913 expect("CONSTRUCTORS");
914 expect(")");
915}
916
George Rimareefa7582016-08-04 09:29:31 +0000917Expr ScriptParser::readAssert() {
918 expect("(");
919 Expr E = readExpr();
920 expect(",");
921 StringRef Msg = next();
922 expect(")");
923 return [=](uint64_t Dot) {
924 uint64_t V = E(Dot);
925 if (!V)
926 error(Msg);
927 return V;
928 };
929}
930
Rui Ueyama10416562016-08-04 02:03:27 +0000931OutputSectionCommand *
932ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000933 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000934
935 // Read an address expression.
936 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
937 if (peek() != ":")
938 Cmd->AddrExpr = readExpr();
939
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000940 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000941
George Rimar630c6172016-07-26 18:06:29 +0000942 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000943 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000944
Davide Italiano246f6812016-07-22 03:36:24 +0000945 // Parse constraints.
946 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000947 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000948 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000949 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000950 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000951
Rui Ueyama025d59b2016-02-02 20:27:59 +0000952 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000953 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000954 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000955 continue;
956 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000957
958 StringRef Tok = next();
959 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
960 Cmd->Commands.emplace_back(Assignment);
961 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000962 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000963 else
964 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000965 }
George Rimar076fe152016-07-21 06:43:01 +0000966 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000967 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000968 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000969}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000970
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000971std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000972 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000973 if (!Tok.startswith("="))
974 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000975 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000976
977 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000978 if (Tok.startswith("=0x"))
979 return parseHex(Tok.substr(3));
980
Rui Ueyama965827d2016-08-03 23:25:15 +0000981 // Read a decimal or octal value as a big-endian 32 bit value.
982 // Why do this? I don't know, but that's what gold does.
983 uint32_t V;
984 if (Tok.substr(1).getAsInteger(0, V)) {
985 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000986 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000987 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000988 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000989}
990
Rui Ueyama10416562016-08-04 02:03:27 +0000991SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000992 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000993 SymbolAssignment *Cmd = readAssignment(next());
994 Cmd->Provide = true;
995 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000996 expect(")");
997 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000998 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000999}
1000
Eugene Leviantceabe802016-08-11 07:56:43 +00001001SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1002 SymbolAssignment *Cmd = nullptr;
1003 if (peek() == "=" || peek() == "+=") {
1004 Cmd = readAssignment(Tok);
1005 expect(";");
1006 } else if (Tok == "PROVIDE") {
1007 Cmd = readProvide(false);
1008 } else if (Tok == "PROVIDE_HIDDEN") {
1009 Cmd = readProvide(true);
1010 }
1011 return Cmd;
1012}
1013
George Rimar30835ea2016-07-28 21:08:56 +00001014static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1015 if (S == ".")
1016 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001017
George Rimara9c5a522016-07-26 18:18:58 +00001018 switch (Config->EKind) {
1019 case ELF32LEKind:
1020 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1021 return B->getVA<ELF32LE>();
1022 break;
1023 case ELF32BEKind:
1024 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1025 return B->getVA<ELF32BE>();
1026 break;
1027 case ELF64LEKind:
1028 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1029 return B->getVA<ELF64LE>();
1030 break;
1031 case ELF64BEKind:
1032 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1033 return B->getVA<ELF64BE>();
1034 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001035 default:
George Rimarb567b622016-07-26 18:46:13 +00001036 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001037 }
1038 error("symbol not found: " + S);
1039 return 0;
1040}
1041
George Rimar9e694502016-07-29 16:18:47 +00001042static uint64_t getSectionSize(StringRef Name) {
1043 switch (Config->EKind) {
1044 case ELF32LEKind:
1045 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1046 case ELF32BEKind:
1047 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1048 case ELF64LEKind:
1049 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1050 case ELF64BEKind:
1051 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1052 default:
1053 llvm_unreachable("unsupported target");
1054 }
George Rimar9e694502016-07-29 16:18:47 +00001055}
1056
George Rimare32a3592016-08-10 07:59:34 +00001057static uint64_t getSizeOfHeaders() {
1058 switch (Config->EKind) {
1059 case ELF32LEKind:
1060 return Script<ELF32LE>::X->getSizeOfHeaders();
1061 case ELF32BEKind:
1062 return Script<ELF32BE>::X->getSizeOfHeaders();
1063 case ELF64LEKind:
1064 return Script<ELF64LE>::X->getSizeOfHeaders();
1065 case ELF64BEKind:
1066 return Script<ELF64BE>::X->getSizeOfHeaders();
1067 default:
1068 llvm_unreachable("unsupported target");
1069 }
1070}
1071
George Rimar30835ea2016-07-28 21:08:56 +00001072SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1073 StringRef Op = next();
1074 assert(Op == "=" || Op == "+=");
1075 Expr E = readExpr();
1076 if (Op == "+=")
1077 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001078 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001079}
1080
1081// This is an operator-precedence parser to parse a linker
1082// script expression.
1083Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1084
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001085static Expr combine(StringRef Op, Expr L, Expr R) {
1086 if (Op == "*")
1087 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1088 if (Op == "/") {
1089 return [=](uint64_t Dot) -> uint64_t {
1090 uint64_t RHS = R(Dot);
1091 if (RHS == 0) {
1092 error("division by zero");
1093 return 0;
1094 }
1095 return L(Dot) / RHS;
1096 };
1097 }
1098 if (Op == "+")
1099 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1100 if (Op == "-")
1101 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1102 if (Op == "<")
1103 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
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 llvm_unreachable("invalid operator");
1117}
1118
Rui Ueyama708019c2016-07-24 18:19:40 +00001119// This is a part of the operator-precedence parser. This function
1120// assumes that the remaining token stream starts with an operator.
1121Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1122 while (!atEOF() && !Error) {
1123 // Read an operator and an expression.
1124 StringRef Op1 = peek();
1125 if (Op1 == "?")
1126 return readTernary(Lhs);
1127 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001128 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001129 next();
1130 Expr Rhs = readPrimary();
1131
1132 // Evaluate the remaining part of the expression first if the
1133 // next operator has greater precedence than the previous one.
1134 // For example, if we have read "+" and "3", and if the next
1135 // operator is "*", then we'll evaluate 3 * ... part first.
1136 while (!atEOF()) {
1137 StringRef Op2 = peek();
1138 if (precedence(Op2) <= precedence(Op1))
1139 break;
1140 Rhs = readExpr1(Rhs, precedence(Op2));
1141 }
1142
1143 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001144 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001145 return Lhs;
1146}
1147
1148uint64_t static getConstant(StringRef S) {
1149 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1150 return Target->PageSize;
1151 error("unknown constant: " + S);
1152 return 0;
1153}
1154
1155Expr ScriptParser::readPrimary() {
1156 StringRef Tok = next();
1157
Rui Ueyama708019c2016-07-24 18:19:40 +00001158 if (Tok == "(") {
1159 Expr E = readExpr();
1160 expect(")");
1161 return E;
1162 }
1163
1164 // Built-in functions are parsed here.
1165 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001166 if (Tok == "ASSERT")
1167 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001168 if (Tok == "ALIGN") {
1169 expect("(");
1170 Expr E = readExpr();
1171 expect(")");
1172 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1173 }
1174 if (Tok == "CONSTANT") {
1175 expect("(");
1176 StringRef Tok = next();
1177 expect(")");
1178 return [=](uint64_t Dot) { return getConstant(Tok); };
1179 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001180 if (Tok == "SEGMENT_START") {
1181 expect("(");
1182 next();
1183 expect(",");
1184 uint64_t Val;
1185 next().getAsInteger(0, Val);
1186 expect(")");
1187 return [=](uint64_t Dot) { return Val; };
1188 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001189 if (Tok == "DATA_SEGMENT_ALIGN") {
1190 expect("(");
1191 Expr E = readExpr();
1192 expect(",");
1193 readExpr();
1194 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001195 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001196 }
1197 if (Tok == "DATA_SEGMENT_END") {
1198 expect("(");
1199 expect(".");
1200 expect(")");
1201 return [](uint64_t Dot) { return Dot; };
1202 }
George Rimar276b4e62016-07-26 17:58:44 +00001203 // GNU linkers implements more complicated logic to handle
1204 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1205 // the next page boundary for simplicity.
1206 if (Tok == "DATA_SEGMENT_RELRO_END") {
1207 expect("(");
1208 next();
1209 expect(",");
1210 readExpr();
1211 expect(")");
1212 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1213 }
George Rimar9e694502016-07-29 16:18:47 +00001214 if (Tok == "SIZEOF") {
1215 expect("(");
1216 StringRef Name = next();
1217 expect(")");
1218 return [=](uint64_t Dot) { return getSectionSize(Name); };
1219 }
George Rimare32a3592016-08-10 07:59:34 +00001220 if (Tok == "SIZEOF_HEADERS")
1221 return [=](uint64_t Dot) { return getSizeOfHeaders(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001222
George Rimara9c5a522016-07-26 18:18:58 +00001223 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001224 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001225 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001226 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001227 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001228 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001229 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001230 return [=](uint64_t Dot) { return V; };
1231}
1232
1233Expr ScriptParser::readTernary(Expr Cond) {
1234 next();
1235 Expr L = readExpr();
1236 expect(":");
1237 Expr R = readExpr();
1238 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1239}
1240
Eugene Leviantbbe38602016-07-19 09:25:43 +00001241std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1242 std::vector<StringRef> Phdrs;
1243 while (!Error && peek().startswith(":")) {
1244 StringRef Tok = next();
1245 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1246 if (Tok.empty()) {
1247 setError("section header name is empty");
1248 break;
1249 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001250 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001251 }
1252 return Phdrs;
1253}
1254
1255unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001256 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001257 unsigned Ret = StringSwitch<unsigned>(Tok)
1258 .Case("PT_NULL", PT_NULL)
1259 .Case("PT_LOAD", PT_LOAD)
1260 .Case("PT_DYNAMIC", PT_DYNAMIC)
1261 .Case("PT_INTERP", PT_INTERP)
1262 .Case("PT_NOTE", PT_NOTE)
1263 .Case("PT_SHLIB", PT_SHLIB)
1264 .Case("PT_PHDR", PT_PHDR)
1265 .Case("PT_TLS", PT_TLS)
1266 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1267 .Case("PT_GNU_STACK", PT_GNU_STACK)
1268 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1269 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001270
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001271 if (Ret == (unsigned)-1) {
1272 setError("invalid program header type: " + Tok);
1273 return PT_NULL;
1274 }
1275 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001276}
1277
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001278static bool isUnderSysroot(StringRef Path) {
1279 if (Config->Sysroot == "")
1280 return false;
1281 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1282 if (sys::fs::equivalent(Config->Sysroot, Path))
1283 return true;
1284 return false;
1285}
1286
Rui Ueyama07320e42016-04-20 20:13:41 +00001287// Entry point.
1288void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001289 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001290 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001291}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001292
Rui Ueyama07320e42016-04-20 20:13:41 +00001293template class elf::LinkerScript<ELF32LE>;
1294template class elf::LinkerScript<ELF32BE>;
1295template class elf::LinkerScript<ELF64LE>;
1296template class elf::LinkerScript<ELF64BE>;