blob: 1c24614ce880b0b198e557ece62d800929dbd722 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
Eugene Leviantceabe802016-08-11 07:56:43 +000046template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000047static void addRegular(SymbolAssignment *Cmd) {
48 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000053template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
54 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(Cmd->Name, nullptr, 0);
Rui Ueyama16024212016-08-11 23:22:52 +000055 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
56 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Rui Ueyama16024212016-08-11 23:22:52 +000059// If a symbol was in PROVIDE(), we need to define it only when
60// it is an undefined symbol.
61template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
62 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000063 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000064 if (!Cmd->Provide)
65 return true;
66 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
67 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
George Rimar076fe152016-07-21 06:43:01 +000070bool SymbolAssignment::classof(const BaseCommand *C) {
71 return C->Kind == AssignmentKind;
72}
73
74bool OutputSectionCommand::classof(const BaseCommand *C) {
75 return C->Kind == OutputSectionKind;
76}
77
George Rimareea31142016-07-21 14:26:59 +000078bool InputSectionDescription::classof(const BaseCommand *C) {
79 return C->Kind == InputSectionKind;
80}
81
George Rimareefa7582016-08-04 09:29:31 +000082bool AssertCommand::classof(const BaseCommand *C) {
83 return C->Kind == AssertKind;
84}
85
Rui Ueyama36a153c2016-07-23 14:09:58 +000086template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000087 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000088}
89
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000090template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
91template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
92
Rui Ueyama07320e42016-04-20 20:13:41 +000093template <class ELFT>
94bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000095 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000096 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000097 return true;
98 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000099}
100
Rui Ueyama63dc6502016-07-25 22:41:42 +0000101static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
102 for (StringRef Pat : Patterns)
103 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000104 return true;
105 return false;
106}
107
George Rimar06598002016-07-28 21:51:30 +0000108static bool fileMatches(const InputSectionDescription *Desc,
109 StringRef Filename) {
110 if (!globMatch(Desc->FilePattern, Filename))
111 return false;
112 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
113}
114
Rui Ueyama6b274812016-07-25 22:51:07 +0000115// Returns input sections filtered by given glob patterns.
116template <class ELFT>
117std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000118LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000119 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000120 std::vector<InputSectionBase<ELFT> *> Ret;
121 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000122 Symtab<ELFT>::X->getObjectFiles()) {
123 if (fileMatches(I, sys::path::filename(F->getName())))
124 for (InputSectionBase<ELFT> *S : F->getSections())
125 if (!isDiscarded(S) && !S->OutSec &&
126 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000127 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000128 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000129
Rui Ueyama7ad9d6d2016-08-12 03:25:25 +0000130 if (llvm::find(Patterns, "COMMON") != Patterns.end())
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000131 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000132
Rui Ueyama6b274812016-07-25 22:51:07 +0000133 return Ret;
134}
135
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000136// You can define new symbols using linker scripts. For example,
137// ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
138// foo just after abc.o's text section contents. This class is to
139// handle such symbol definitions.
140//
141// In order to handle scripts like the above one, we want to
142// keep symbol definitions in output sections. Because output sections
143// can contain only input sections, we wrap symbol definitions
144// with dummy input sections. This class serves that purpose.
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000145template <class ELFT>
146class elf::LayoutInputSection : public InputSectionBase<ELFT> {
Eugene Leviantceabe802016-08-11 07:56:43 +0000147public:
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000148 explicit LayoutInputSection(SymbolAssignment *Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000149 static bool classof(const InputSectionBase<ELFT> *S);
150 SymbolAssignment *Cmd;
151
152private:
153 typename ELFT::Shdr Hdr;
154};
155
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000156template <class ELFT>
157static InputSectionBase<ELFT> *
158getNonLayoutSection(std::vector<InputSectionBase<ELFT> *> &Vec) {
159 for (InputSectionBase<ELFT> *S : Vec)
160 if (!isa<LayoutInputSection<ELFT>>(S))
161 return S;
162 return nullptr;
163}
Eugene Leviantceabe802016-08-11 07:56:43 +0000164
165template <class T> static T *zero(T *Val) {
166 memset(Val, 0, sizeof(*Val));
167 return Val;
168}
169
170template <class ELFT>
171LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000172 : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
173 InputSectionBase<ELFT>::Layout),
174 Cmd(Cmd) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000175 this->Live = true;
Eugene Leviantceabe802016-08-11 07:56:43 +0000176 Hdr.sh_type = SHT_NOBITS;
177}
178
179template <class ELFT>
180bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
181 return S->SectionKind == InputSectionBase<ELFT>::Layout;
182}
183
184template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000185static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
186 return A->getSectionName() < B->getSectionName();
187}
George Rimar350ece42016-08-03 08:35:59 +0000188
Rui Ueyama742c3832016-08-04 22:27:00 +0000189template <class ELFT>
190static bool compareAlignment(InputSectionBase<ELFT> *A,
191 InputSectionBase<ELFT> *B) {
192 // ">" is not a mistake. Larger alignments are placed before smaller
193 // alignments in order to reduce the amount of padding necessary.
194 // This is compatible with GNU.
195 return A->Alignment > B->Alignment;
196}
George Rimar350ece42016-08-03 08:35:59 +0000197
Rui Ueyama742c3832016-08-04 22:27:00 +0000198template <class ELFT>
199static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
200getComparator(SortKind K) {
201 if (K == SortByName)
202 return compareName<ELFT>;
203 return compareAlignment<ELFT>;
204}
George Rimar0702c4e2016-07-29 15:32:46 +0000205
206template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000207void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
208 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
209 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
210 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
211 S->Live = false;
212 reportDiscarded(S);
213 }
214 }
215 }
216}
217
218template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000219static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
220 ConstraintKind Kind) {
221 bool RO = (Kind == ConstraintKind::ReadOnly);
222 bool RW = (Kind == ConstraintKind::ReadWrite);
223 return !llvm::any_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
224 bool Writable = Sec->getSectionHdr()->sh_flags & SHF_WRITE;
225 return (RO && Writable) || (RW && !Writable);
226 });
227}
228
229template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000230std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000231LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000232 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000233
George Rimar06ae6832016-08-12 09:07:57 +0000234 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
235 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
236 if (shouldDefine<ELFT>(OutCmd))
237 addSynthetic<ELFT>(OutCmd);
238 Ret.push_back(new (LAlloc.Allocate()) LayoutInputSection<ELFT>(OutCmd));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000239 continue;
240 }
241
242 auto *Cmd = cast<InputSectionDescription>(Base.get());
243 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000244 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
245 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000246 if (Cmd->SortInner)
247 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
248 if (Cmd->SortOuter)
249 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
250 Ret.insert(Ret.end(), V.begin(), V.end());
251 }
252 return Ret;
253}
254
255template <class ELFT>
256void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000257 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000258 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
259 if (shouldDefine<ELFT>(Cmd))
260 addRegular<ELFT>(Cmd);
261 continue;
262 }
263
Eugene Leviantceabe802016-08-11 07:56:43 +0000264 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000265 if (Cmd->Name == "/DISCARD/") {
266 discard(*Cmd);
267 continue;
268 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000269
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000270 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
271 InputSectionBase<ELFT> *Head = getNonLayoutSection<ELFT>(V);
272 if (!Head)
273 continue;
274
275 OutputSectionBase<ELFT> *OutSec;
276 bool IsNew;
277 std::tie(OutSec, IsNew) = Factory.create(Head, Cmd->Name);
278 if (IsNew)
279 OutputSections->push_back(OutSec);
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000280 for (InputSectionBase<ELFT> *Sec : V)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000281 OutSec->addSection(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000282 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000283 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000284
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000285 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000286 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000287 Symtab<ELFT>::X->getObjectFiles()) {
288 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000289 if (isDiscarded(S) || S->OutSec)
290 continue;
291 OutputSectionBase<ELFT> *OutSec;
292 bool IsNew;
293 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
294 if (IsNew)
295 OutputSections->push_back(OutSec);
296 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000297 }
298 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000299}
300
Eugene Leviantceabe802016-08-11 07:56:43 +0000301template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000302 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000303 if (!OutSec) {
304 Sec->assignOffsets();
Eugene Leviantceabe802016-08-11 07:56:43 +0000305 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000306 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000307
308 typedef typename ELFT::uint uintX_t;
309 uintX_t Off = 0;
310
311 for (InputSection<ELFT> *I : OutSec->Sections) {
312 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
313 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000314 if (L->Cmd->Name == ".") {
Eugene Leviantceabe802016-08-11 07:56:43 +0000315 Off = Value;
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000316 } else {
317 auto *Sym = cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym);
318 Sym->Section = OutSec;
319 Sym->Value = Value;
320 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000321 } else {
322 Off = alignTo(Off, I->Alignment);
323 I->OutSecOff = Off;
324 Off += I->getSize();
325 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000326 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000327 // works correctly in the case below:
328 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
329 Sec->setSize(Off);
330 }
331}
332
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000333template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000334 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000335 // are not explicitly placed into the output file by the linker script.
336 // We place orphan sections at end of file.
337 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000338 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000339 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000340 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000341 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000342 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000343 }
George Rimar652852c2016-04-16 10:10:32 +0000344
Rui Ueyama7c18c282016-04-18 21:00:40 +0000345 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000346 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000347 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000348 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000349
George Rimar076fe152016-07-21 06:43:01 +0000350 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
351 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000352 if (Cmd->Name == ".") {
353 Dot = Cmd->Expression(Dot);
354 } else if (Cmd->Sym) {
355 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
356 }
George Rimar652852c2016-04-16 10:10:32 +0000357 continue;
358 }
359
George Rimareefa7582016-08-04 09:29:31 +0000360 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
361 Cmd->Expression(Dot);
362 continue;
363 }
364
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000365 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000366 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000367 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000368 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000369 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar076fe152016-07-21 06:43:01 +0000370 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000371 continue;
George Rimar652852c2016-04-16 10:10:32 +0000372
George Rimar58e5c4d2016-07-25 08:29:46 +0000373 if (Cmd->AddrExpr)
374 Dot = Cmd->AddrExpr(Dot);
375
George Rimar630c6172016-07-26 18:06:29 +0000376 if (Cmd->AlignExpr)
377 Sec->updateAlignment(Cmd->AlignExpr(Dot));
378
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000379 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
380 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000381 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000382 Sec->setVA(TVA);
Eugene Leviantceabe802016-08-11 07:56:43 +0000383 assignOffsets(Sec);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000384 ThreadBssOffset = TVA - Dot + Sec->getSize();
385 continue;
386 }
George Rimar652852c2016-04-16 10:10:32 +0000387
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000388 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000389 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000390 Sec->setVA(Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000391 assignOffsets(Sec);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000392 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000393 Dot += Sec->getSize();
394 continue;
395 }
Rui Ueyama2de509c2016-08-12 00:55:08 +0000396 Sec->assignOffsets();
George Rimar652852c2016-04-16 10:10:32 +0000397 }
398 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000399
Rafael Espindola64c32d62016-07-07 14:28:47 +0000400 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000401 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000402 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
403 Out<ELFT>::ProgramHeaders->getSize(),
404 Target->PageSize);
405 Out<ELFT>::ElfHeader->setVA(MinVA);
406 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000407}
408
Rui Ueyama07320e42016-04-20 20:13:41 +0000409template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000410std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
411 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000412 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000413
414 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000415 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
416 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000417
418 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000419 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000420 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000421 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000422
423 switch (Cmd.Type) {
424 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000425 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000426 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000427 break;
428 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000429 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000430 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000431 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000432 }
433 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000434 case PT_GNU_EH_FRAME:
435 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000436 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000437 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000438 }
439 break;
440 }
441 }
442
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000443 PhdrEntry<ELFT> *Load = nullptr;
444 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445 for (OutputSectionBase<ELFT> *Sec : Sections) {
446 if (!(Sec->getFlags() & SHF_ALLOC))
447 break;
448
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000449 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000450 if (!PhdrIds.empty()) {
451 // Assign headers specified by linker script
452 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000453 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000454 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000455 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000456 }
457 } else {
458 // If we have no load segment or flags've changed then we want new load
459 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000460 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000461 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000462 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000463 Flags = NewFlags;
464 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000465 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000466 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000467 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000468 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000469}
470
471template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000472ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000473 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
474 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
475 if (Cmd->Name == Name)
476 return Cmd->Filler;
477 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000478}
479
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000480// Returns the index of the given section name in linker script
481// SECTIONS commands. Sections are laid out as the same order as they
482// were in the script. If a given name did not appear in the script,
483// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000484template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000485 int I = 0;
486 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
487 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
488 if (Cmd->Name == Name)
489 return I;
490 ++I;
491 }
492 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000493}
494
495// A compartor to sort output sections. Returns -1 or 1 if
496// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000497template <class ELFT>
498int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000499 int I = getSectionIndex(A);
500 int J = getSectionIndex(B);
501 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000502 return 0;
503 return I < J ? -1 : 1;
504}
505
Eugene Leviantbbe38602016-07-19 09:25:43 +0000506template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
507 return !Opt.PhdrsCommands.empty();
508}
509
George Rimar9e694502016-07-29 16:18:47 +0000510template <class ELFT>
511typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
512 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
513 if (Sec->getName() == Name)
514 return Sec->getSize();
515 error("undefined section " + Name);
516 return 0;
517}
518
George Rimare32a3592016-08-10 07:59:34 +0000519template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000520typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000521 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
522}
523
Eugene Leviantbbe38602016-07-19 09:25:43 +0000524// Returns indices of ELF headers containing specific section, identified
525// by Name. Each index is a zero based number of ELF header listed within
526// PHDRS {} script block.
527template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000528std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000529 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
530 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000531 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000532 continue;
533
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000534 std::vector<size_t> Ret;
535 for (StringRef PhdrName : Cmd->Phdrs)
536 Ret.push_back(getPhdrIndex(PhdrName));
537 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000538 }
George Rimar31d842f2016-07-20 16:43:03 +0000539 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000540}
541
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000542template <class ELFT>
543size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
544 size_t I = 0;
545 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
546 if (Cmd.Name == PhdrName)
547 return I;
548 ++I;
549 }
550 error("section header '" + PhdrName + "' is not listed in PHDRS");
551 return 0;
552}
553
Rui Ueyama07320e42016-04-20 20:13:41 +0000554class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000555 typedef void (ScriptParser::*Handler)();
556
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000557public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000558 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000559
Rui Ueyama4a465392016-04-22 22:59:24 +0000560 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000561
562private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000563 void addFile(StringRef Path);
564
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000565 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000566 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000567 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000568 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000569 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000570 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000571 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000572 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000573 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000574 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000575 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000576 void readSections();
577
Rui Ueyama113cdec2016-07-24 23:05:57 +0000578 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000579 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000580 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000581 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000582 InputSectionDescription *readInputSectionDescription();
583 std::vector<StringRef> readInputFilePatterns();
584 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000585 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000586 SortKind readSortKind();
Rui Ueyama10416562016-08-04 02:03:27 +0000587 SymbolAssignment *readProvide(bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000588 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000589 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000590 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000591 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000592
593 Expr readExpr();
594 Expr readExpr1(Expr Lhs, int MinPrec);
595 Expr readPrimary();
596 Expr readTernary(Expr Cond);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000597
George Rimarc3794e52016-02-24 09:21:47 +0000598 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000599 ScriptConfiguration &Opt = *ScriptConfig;
600 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000601 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000602};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000603
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000604const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000605 {"ENTRY", &ScriptParser::readEntry},
606 {"EXTERN", &ScriptParser::readExtern},
607 {"GROUP", &ScriptParser::readGroup},
608 {"INCLUDE", &ScriptParser::readInclude},
609 {"INPUT", &ScriptParser::readGroup},
610 {"OUTPUT", &ScriptParser::readOutput},
611 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
612 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000613 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000614 {"SEARCH_DIR", &ScriptParser::readSearchDir},
615 {"SECTIONS", &ScriptParser::readSections},
616 {";", &ScriptParser::readNothing}};
617
Rui Ueyama717677a2016-02-11 21:17:59 +0000618void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000619 while (!atEOF()) {
620 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000621 if (Handler Fn = Cmd.lookup(Tok))
622 (this->*Fn)();
623 else
George Rimar57610422016-03-11 14:43:02 +0000624 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000625 }
626}
627
Rui Ueyama717677a2016-02-11 21:17:59 +0000628void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000629 if (IsUnderSysroot && S.startswith("/")) {
630 SmallString<128> Path;
631 (Config->Sysroot + S).toStringRef(Path);
632 if (sys::fs::exists(Path)) {
633 Driver->addFile(Saver.save(Path.str()));
634 return;
635 }
636 }
637
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000638 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000639 Driver->addFile(S);
640 } else if (S.startswith("=")) {
641 if (Config->Sysroot.empty())
642 Driver->addFile(S.substr(1));
643 else
644 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
645 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000646 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000647 } else if (sys::fs::exists(S)) {
648 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000649 } else {
650 std::string Path = findFromSearchPaths(S);
651 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000652 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000653 else
654 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000655 }
656}
657
Rui Ueyama717677a2016-02-11 21:17:59 +0000658void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000659 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000660 bool Orig = Config->AsNeeded;
661 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000662 while (!Error && !skip(")"))
663 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000664 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000665}
666
Rui Ueyama717677a2016-02-11 21:17:59 +0000667void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000668 // -e <symbol> takes predecence over ENTRY(<symbol>).
669 expect("(");
670 StringRef Tok = next();
671 if (Config->Entry.empty())
672 Config->Entry = Tok;
673 expect(")");
674}
675
Rui Ueyama717677a2016-02-11 21:17:59 +0000676void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000677 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000678 while (!Error && !skip(")"))
679 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000680}
681
Rui Ueyama717677a2016-02-11 21:17:59 +0000682void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000683 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000684 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000685 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000686 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000687 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000688 else
689 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000690 }
691}
692
Rui Ueyama717677a2016-02-11 21:17:59 +0000693void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000694 StringRef Tok = next();
695 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000696 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000697 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000698 return;
699 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000700 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000701 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
702 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000703 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000704}
705
Rui Ueyama717677a2016-02-11 21:17:59 +0000706void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000707 // -o <file> takes predecence over OUTPUT(<file>).
708 expect("(");
709 StringRef Tok = next();
710 if (Config->OutputFile.empty())
711 Config->OutputFile = Tok;
712 expect(")");
713}
714
Rui Ueyama717677a2016-02-11 21:17:59 +0000715void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000716 // Error checking only for now.
717 expect("(");
718 next();
719 expect(")");
720}
721
Rui Ueyama717677a2016-02-11 21:17:59 +0000722void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000723 // Error checking only for now.
724 expect("(");
725 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000726 StringRef Tok = next();
727 if (Tok == ")")
728 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000729 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000730 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000731 return;
732 }
Davide Italiano6836c612015-10-12 21:08:41 +0000733 next();
734 expect(",");
735 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000736 expect(")");
737}
738
Eugene Leviantbbe38602016-07-19 09:25:43 +0000739void ScriptParser::readPhdrs() {
740 expect("{");
741 while (!Error && !skip("}")) {
742 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000743 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000744 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
745
746 PhdrCmd.Type = readPhdrType();
747 do {
748 Tok = next();
749 if (Tok == ";")
750 break;
751 if (Tok == "FILEHDR")
752 PhdrCmd.HasFilehdr = true;
753 else if (Tok == "PHDRS")
754 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000755 else if (Tok == "FLAGS") {
756 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000757 // Passing 0 for the value of dot is a bit of a hack. It means that
758 // we accept expressions like ".|1".
759 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000760 expect(")");
761 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000762 setError("unexpected header attribute: " + Tok);
763 } while (!Error);
764 }
765}
766
Rui Ueyama717677a2016-02-11 21:17:59 +0000767void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000768 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000769 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000770 expect(")");
771}
772
Rui Ueyama717677a2016-02-11 21:17:59 +0000773void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000774 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000775 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000776 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000777 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000778 BaseCommand *Cmd = readProvideOrAssignment(Tok);
779 if (!Cmd) {
780 if (Tok == "ASSERT")
781 Cmd = new AssertCommand(readAssert());
782 else
783 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000784 }
Rui Ueyama10416562016-08-04 02:03:27 +0000785 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000786 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000787}
788
Rui Ueyama708019c2016-07-24 18:19:40 +0000789static int precedence(StringRef Op) {
790 return StringSwitch<int>(Op)
791 .Case("*", 4)
792 .Case("/", 4)
793 .Case("+", 3)
794 .Case("-", 3)
795 .Case("<", 2)
796 .Case(">", 2)
797 .Case(">=", 2)
798 .Case("<=", 2)
799 .Case("==", 2)
800 .Case("!=", 2)
801 .Case("&", 1)
802 .Default(-1);
803}
804
Rui Ueyama10416562016-08-04 02:03:27 +0000805std::vector<StringRef> ScriptParser::readInputFilePatterns() {
806 std::vector<StringRef> V;
807 while (!Error && !skip(")"))
808 V.push_back(next());
809 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000810}
811
Rui Ueyama742c3832016-08-04 22:27:00 +0000812SortKind ScriptParser::readSortKind() {
813 if (skip("SORT") || skip("SORT_BY_NAME"))
814 return SortByName;
815 if (skip("SORT_BY_ALIGNMENT"))
816 return SortByAlignment;
817 return SortNone;
818}
819
Rui Ueyama10416562016-08-04 02:03:27 +0000820InputSectionDescription *ScriptParser::readInputSectionRules() {
821 auto *Cmd = new InputSectionDescription;
822 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000823 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000824
Rui Ueyama742c3832016-08-04 22:27:00 +0000825 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000826 if (skip("EXCLUDE_FILE")) {
827 expect("(");
828 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000829 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000830 }
George Rimar06598002016-07-28 21:51:30 +0000831
Rui Ueyama742c3832016-08-04 22:27:00 +0000832 // Read SORT().
833 if (SortKind K1 = readSortKind()) {
834 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000835 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000836 if (SortKind K2 = readSortKind()) {
837 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000838 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000839 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000840 expect(")");
841 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000842 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000843 }
George Rimar0702c4e2016-07-29 15:32:46 +0000844 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000845 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000846 }
George Rimar0702c4e2016-07-29 15:32:46 +0000847
Rui Ueyama10416562016-08-04 02:03:27 +0000848 Cmd->SectionPatterns = readInputFilePatterns();
849 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000850}
851
Rui Ueyama10416562016-08-04 02:03:27 +0000852InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000853 // Input section wildcard can be surrounded by KEEP.
854 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
855 if (skip("KEEP")) {
856 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000857 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000858 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000859 Opt.KeptSections.insert(Opt.KeptSections.end(),
860 Cmd->SectionPatterns.begin(),
861 Cmd->SectionPatterns.end());
862 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000863 }
Rui Ueyama10416562016-08-04 02:03:27 +0000864 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000865}
866
Rui Ueyama10416562016-08-04 02:03:27 +0000867Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000868 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000869 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000870 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000871 return E;
George Rimar630c6172016-07-26 18:06:29 +0000872}
873
George Rimar03fc0102016-07-28 07:18:23 +0000874void ScriptParser::readSort() {
875 expect("(");
876 expect("CONSTRUCTORS");
877 expect(")");
878}
879
George Rimareefa7582016-08-04 09:29:31 +0000880Expr ScriptParser::readAssert() {
881 expect("(");
882 Expr E = readExpr();
883 expect(",");
884 StringRef Msg = next();
885 expect(")");
886 return [=](uint64_t Dot) {
887 uint64_t V = E(Dot);
888 if (!V)
889 error(Msg);
890 return V;
891 };
892}
893
Rui Ueyama10416562016-08-04 02:03:27 +0000894OutputSectionCommand *
895ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000896 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000897
898 // Read an address expression.
899 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
900 if (peek() != ":")
901 Cmd->AddrExpr = readExpr();
902
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000903 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000904
George Rimar630c6172016-07-26 18:06:29 +0000905 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000906 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000907
Davide Italiano246f6812016-07-22 03:36:24 +0000908 // Parse constraints.
909 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000910 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000911 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000912 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000913 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000914
Rui Ueyama025d59b2016-02-02 20:27:59 +0000915 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000916 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000917 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000918 continue;
919 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000920
921 StringRef Tok = next();
922 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
923 Cmd->Commands.emplace_back(Assignment);
924 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000925 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000926 else
927 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000928 }
George Rimar076fe152016-07-21 06:43:01 +0000929 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000930 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000931 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000932}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000933
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000934std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000935 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000936 if (!Tok.startswith("="))
937 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000938 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000939
940 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000941 if (Tok.startswith("=0x"))
942 return parseHex(Tok.substr(3));
943
Rui Ueyama965827d2016-08-03 23:25:15 +0000944 // Read a decimal or octal value as a big-endian 32 bit value.
945 // Why do this? I don't know, but that's what gold does.
946 uint32_t V;
947 if (Tok.substr(1).getAsInteger(0, V)) {
948 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000949 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000950 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000951 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000952}
953
Rui Ueyama10416562016-08-04 02:03:27 +0000954SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000955 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000956 SymbolAssignment *Cmd = readAssignment(next());
957 Cmd->Provide = true;
958 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000959 expect(")");
960 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000961 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000962}
963
Eugene Leviantceabe802016-08-11 07:56:43 +0000964SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
965 SymbolAssignment *Cmd = nullptr;
966 if (peek() == "=" || peek() == "+=") {
967 Cmd = readAssignment(Tok);
968 expect(";");
969 } else if (Tok == "PROVIDE") {
970 Cmd = readProvide(false);
971 } else if (Tok == "PROVIDE_HIDDEN") {
972 Cmd = readProvide(true);
973 }
974 return Cmd;
975}
976
George Rimar30835ea2016-07-28 21:08:56 +0000977static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
978 if (S == ".")
979 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000980
George Rimara9c5a522016-07-26 18:18:58 +0000981 switch (Config->EKind) {
982 case ELF32LEKind:
983 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
984 return B->getVA<ELF32LE>();
985 break;
986 case ELF32BEKind:
987 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
988 return B->getVA<ELF32BE>();
989 break;
990 case ELF64LEKind:
991 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
992 return B->getVA<ELF64LE>();
993 break;
994 case ELF64BEKind:
995 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
996 return B->getVA<ELF64BE>();
997 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000998 default:
George Rimarb567b622016-07-26 18:46:13 +0000999 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001000 }
1001 error("symbol not found: " + S);
1002 return 0;
1003}
1004
George Rimar9e694502016-07-29 16:18:47 +00001005static uint64_t getSectionSize(StringRef Name) {
1006 switch (Config->EKind) {
1007 case ELF32LEKind:
1008 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1009 case ELF32BEKind:
1010 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1011 case ELF64LEKind:
1012 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1013 case ELF64BEKind:
1014 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1015 default:
1016 llvm_unreachable("unsupported target");
1017 }
George Rimar9e694502016-07-29 16:18:47 +00001018}
1019
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001020static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001021 switch (Config->EKind) {
1022 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001023 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001024 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001025 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001026 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001027 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001028 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001029 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001030 default:
1031 llvm_unreachable("unsupported target");
1032 }
1033}
1034
George Rimar30835ea2016-07-28 21:08:56 +00001035SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1036 StringRef Op = next();
1037 assert(Op == "=" || Op == "+=");
1038 Expr E = readExpr();
1039 if (Op == "+=")
1040 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001041 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001042}
1043
1044// This is an operator-precedence parser to parse a linker
1045// script expression.
1046Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1047
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001048static Expr combine(StringRef Op, Expr L, Expr R) {
1049 if (Op == "*")
1050 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1051 if (Op == "/") {
1052 return [=](uint64_t Dot) -> uint64_t {
1053 uint64_t RHS = R(Dot);
1054 if (RHS == 0) {
1055 error("division by zero");
1056 return 0;
1057 }
1058 return L(Dot) / RHS;
1059 };
1060 }
1061 if (Op == "+")
1062 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1063 if (Op == "-")
1064 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1065 if (Op == "<")
1066 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1067 if (Op == ">")
1068 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1069 if (Op == ">=")
1070 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1071 if (Op == "<=")
1072 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1073 if (Op == "==")
1074 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1075 if (Op == "!=")
1076 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1077 if (Op == "&")
1078 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1079 llvm_unreachable("invalid operator");
1080}
1081
Rui Ueyama708019c2016-07-24 18:19:40 +00001082// This is a part of the operator-precedence parser. This function
1083// assumes that the remaining token stream starts with an operator.
1084Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1085 while (!atEOF() && !Error) {
1086 // Read an operator and an expression.
1087 StringRef Op1 = peek();
1088 if (Op1 == "?")
1089 return readTernary(Lhs);
1090 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001091 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001092 next();
1093 Expr Rhs = readPrimary();
1094
1095 // Evaluate the remaining part of the expression first if the
1096 // next operator has greater precedence than the previous one.
1097 // For example, if we have read "+" and "3", and if the next
1098 // operator is "*", then we'll evaluate 3 * ... part first.
1099 while (!atEOF()) {
1100 StringRef Op2 = peek();
1101 if (precedence(Op2) <= precedence(Op1))
1102 break;
1103 Rhs = readExpr1(Rhs, precedence(Op2));
1104 }
1105
1106 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001107 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001108 return Lhs;
1109}
1110
1111uint64_t static getConstant(StringRef S) {
1112 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1113 return Target->PageSize;
1114 error("unknown constant: " + S);
1115 return 0;
1116}
1117
1118Expr ScriptParser::readPrimary() {
1119 StringRef Tok = next();
1120
Rui Ueyama708019c2016-07-24 18:19:40 +00001121 if (Tok == "(") {
1122 Expr E = readExpr();
1123 expect(")");
1124 return E;
1125 }
1126
1127 // Built-in functions are parsed here.
1128 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001129 if (Tok == "ASSERT")
1130 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001131 if (Tok == "ALIGN") {
1132 expect("(");
1133 Expr E = readExpr();
1134 expect(")");
1135 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1136 }
1137 if (Tok == "CONSTANT") {
1138 expect("(");
1139 StringRef Tok = next();
1140 expect(")");
1141 return [=](uint64_t Dot) { return getConstant(Tok); };
1142 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001143 if (Tok == "SEGMENT_START") {
1144 expect("(");
1145 next();
1146 expect(",");
1147 uint64_t Val;
1148 next().getAsInteger(0, Val);
1149 expect(")");
1150 return [=](uint64_t Dot) { return Val; };
1151 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001152 if (Tok == "DATA_SEGMENT_ALIGN") {
1153 expect("(");
1154 Expr E = readExpr();
1155 expect(",");
1156 readExpr();
1157 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001158 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001159 }
1160 if (Tok == "DATA_SEGMENT_END") {
1161 expect("(");
1162 expect(".");
1163 expect(")");
1164 return [](uint64_t Dot) { return Dot; };
1165 }
George Rimar276b4e62016-07-26 17:58:44 +00001166 // GNU linkers implements more complicated logic to handle
1167 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1168 // the next page boundary for simplicity.
1169 if (Tok == "DATA_SEGMENT_RELRO_END") {
1170 expect("(");
1171 next();
1172 expect(",");
1173 readExpr();
1174 expect(")");
1175 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1176 }
George Rimar9e694502016-07-29 16:18:47 +00001177 if (Tok == "SIZEOF") {
1178 expect("(");
1179 StringRef Name = next();
1180 expect(")");
1181 return [=](uint64_t Dot) { return getSectionSize(Name); };
1182 }
George Rimare32a3592016-08-10 07:59:34 +00001183 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001184 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001185
George Rimara9c5a522016-07-26 18:18:58 +00001186 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001187 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001188 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001189 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001190 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001191 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001192 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001193 return [=](uint64_t Dot) { return V; };
1194}
1195
1196Expr ScriptParser::readTernary(Expr Cond) {
1197 next();
1198 Expr L = readExpr();
1199 expect(":");
1200 Expr R = readExpr();
1201 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1202}
1203
Eugene Leviantbbe38602016-07-19 09:25:43 +00001204std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1205 std::vector<StringRef> Phdrs;
1206 while (!Error && peek().startswith(":")) {
1207 StringRef Tok = next();
1208 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1209 if (Tok.empty()) {
1210 setError("section header name is empty");
1211 break;
1212 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001213 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001214 }
1215 return Phdrs;
1216}
1217
1218unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001219 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001220 unsigned Ret = StringSwitch<unsigned>(Tok)
1221 .Case("PT_NULL", PT_NULL)
1222 .Case("PT_LOAD", PT_LOAD)
1223 .Case("PT_DYNAMIC", PT_DYNAMIC)
1224 .Case("PT_INTERP", PT_INTERP)
1225 .Case("PT_NOTE", PT_NOTE)
1226 .Case("PT_SHLIB", PT_SHLIB)
1227 .Case("PT_PHDR", PT_PHDR)
1228 .Case("PT_TLS", PT_TLS)
1229 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1230 .Case("PT_GNU_STACK", PT_GNU_STACK)
1231 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1232 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001233
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001234 if (Ret == (unsigned)-1) {
1235 setError("invalid program header type: " + Tok);
1236 return PT_NULL;
1237 }
1238 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001239}
1240
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001241static bool isUnderSysroot(StringRef Path) {
1242 if (Config->Sysroot == "")
1243 return false;
1244 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1245 if (sys::fs::equivalent(Config->Sysroot, Path))
1246 return true;
1247 return false;
1248}
1249
Rui Ueyama07320e42016-04-20 20:13:41 +00001250// Entry point.
1251void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001252 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001253 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001254}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001255
Rui Ueyama07320e42016-04-20 20:13:41 +00001256template class elf::LinkerScript<ELF32LE>;
1257template class elf::LinkerScript<ELF32BE>;
1258template class elf::LinkerScript<ELF64LE>;
1259template class elf::LinkerScript<ELF64BE>;