blob: 493e041fe6853405a9f8cd84f5d415c2bc0b57fe [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
Eugene Leviantceabe802016-08-11 07:56:43 +000046template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000047static void addRegular(SymbolAssignment *Cmd) {
48 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000053template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000054 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
55 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000056 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Rui Ueyama16024212016-08-11 23:22:52 +000059// If a symbol was in PROVIDE(), we need to define it only when
60// it is an undefined symbol.
61template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
62 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000063 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000064 if (!Cmd->Provide)
65 return true;
66 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
67 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
George Rimar076fe152016-07-21 06:43:01 +000070bool SymbolAssignment::classof(const BaseCommand *C) {
71 return C->Kind == AssignmentKind;
72}
73
74bool OutputSectionCommand::classof(const BaseCommand *C) {
75 return C->Kind == OutputSectionKind;
76}
77
George Rimareea31142016-07-21 14:26:59 +000078bool InputSectionDescription::classof(const BaseCommand *C) {
79 return C->Kind == InputSectionKind;
80}
81
George Rimareefa7582016-08-04 09:29:31 +000082bool AssertCommand::classof(const BaseCommand *C) {
83 return C->Kind == AssertKind;
84}
85
Rui Ueyama36a153c2016-07-23 14:09:58 +000086template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000087 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000088}
89
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000090template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
91template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
92
Rui Ueyama07320e42016-04-20 20:13:41 +000093template <class ELFT>
94bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000095 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000096 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000097 return true;
98 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000099}
100
Rui Ueyama63dc6502016-07-25 22:41:42 +0000101static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
102 for (StringRef Pat : Patterns)
103 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000104 return true;
105 return false;
106}
107
George Rimar06598002016-07-28 21:51:30 +0000108static bool fileMatches(const InputSectionDescription *Desc,
109 StringRef Filename) {
110 if (!globMatch(Desc->FilePattern, Filename))
111 return false;
112 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
113}
114
Rui Ueyama6b274812016-07-25 22:51:07 +0000115// Returns input sections filtered by given glob patterns.
116template <class ELFT>
117std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000118LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000119 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000120 std::vector<InputSectionBase<ELFT> *> Ret;
121 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000122 Symtab<ELFT>::X->getObjectFiles()) {
123 if (fileMatches(I, sys::path::filename(F->getName())))
124 for (InputSectionBase<ELFT> *S : F->getSections())
125 if (!isDiscarded(S) && !S->OutSec &&
126 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000127 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000128 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000129
Rui Ueyama7ad9d6d2016-08-12 03:25:25 +0000130 if (llvm::find(Patterns, "COMMON") != Patterns.end())
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000131 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000132
Rui Ueyama6b274812016-07-25 22:51:07 +0000133 return Ret;
134}
135
Eugene Leviantceabe802016-08-11 07:56:43 +0000136template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000137static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
138 return A->getSectionName() < B->getSectionName();
139}
George Rimar350ece42016-08-03 08:35:59 +0000140
Rui Ueyama742c3832016-08-04 22:27:00 +0000141template <class ELFT>
142static bool compareAlignment(InputSectionBase<ELFT> *A,
143 InputSectionBase<ELFT> *B) {
144 // ">" is not a mistake. Larger alignments are placed before smaller
145 // alignments in order to reduce the amount of padding necessary.
146 // This is compatible with GNU.
147 return A->Alignment > B->Alignment;
148}
George Rimar350ece42016-08-03 08:35:59 +0000149
Rui Ueyama742c3832016-08-04 22:27:00 +0000150template <class ELFT>
151static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
152getComparator(SortKind K) {
153 if (K == SortByName)
154 return compareName<ELFT>;
155 return compareAlignment<ELFT>;
156}
George Rimar0702c4e2016-07-29 15:32:46 +0000157
158template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000159void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
160 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
161 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
162 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
163 S->Live = false;
164 reportDiscarded(S);
165 }
166 }
167 }
168}
169
George Rimar8f66df92016-08-12 20:38:20 +0000170static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
171 bool RO = (Kind == ConstraintKind::ReadOnly);
172 bool RW = (Kind == ConstraintKind::ReadWrite);
173 bool Writable = Flags & SHF_WRITE;
174 return !((RO && Writable) || (RW && !Writable));
175}
176
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000177template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000178static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
179 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000180 if (Kind == ConstraintKind::NoConstraint)
181 return true;
182 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
183 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000184 });
185}
186
187template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000188std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000189LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000190 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000191 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000192
George Rimar06ae6832016-08-12 09:07:57 +0000193 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
194 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
195 if (shouldDefine<ELFT>(OutCmd))
196 addSynthetic<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000197 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000198 continue;
199 }
200
201 auto *Cmd = cast<InputSectionDescription>(Base.get());
202 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000203 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
204 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000205 if (Cmd->SortInner)
206 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
207 if (Cmd->SortOuter)
208 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000209
210 // Add all input sections corresponding to rule 'Cmd' to
211 // resulting vector. We do not add duplicate input sections.
212 for (InputSectionBase<ELFT> *S : V)
213 if (SectionIndex.insert(S).second)
214 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000215 }
216 return Ret;
217}
218
219template <class ELFT>
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000220void LinkerScript<ELFT>::createAssignments() {
221 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
222 if (shouldDefine<ELFT>(Cmd.get()))
223 addRegular<ELFT>(Cmd.get());
224 if (Cmd->Sym)
225 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
226 }
227}
228
229template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000230void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000231 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000232 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
233 if (shouldDefine<ELFT>(Cmd))
234 addRegular<ELFT>(Cmd);
235 continue;
236 }
237
Eugene Leviantceabe802016-08-11 07:56:43 +0000238 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000239 if (Cmd->Name == "/DISCARD/") {
240 discard(*Cmd);
241 continue;
242 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000243
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000244 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000245 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000246 continue;
247
248 OutputSectionBase<ELFT> *OutSec;
249 bool IsNew;
Eugene Leviant97403d12016-09-01 09:55:57 +0000250 std::tie(OutSec, IsNew) = Factory.create(V.front(), Cmd->Name);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000251 if (IsNew)
252 OutputSections->push_back(OutSec);
George Rimardb24d9c2016-08-19 15:18:23 +0000253
254 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
255 for (InputSectionBase<ELFT> *Sec : V) {
256 if (Subalign)
257 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000258 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000259 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000260 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000261 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000262
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000263 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000264 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000265 Symtab<ELFT>::X->getObjectFiles()) {
266 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000267 if (isDiscarded(S) || S->OutSec)
268 continue;
269 OutputSectionBase<ELFT> *OutSec;
270 bool IsNew;
271 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
272 if (IsNew)
273 OutputSections->push_back(OutSec);
274 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000275 }
276 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000277}
278
Eugene Leviant20889c52016-08-31 08:13:33 +0000279// Linker script may define start and end symbols for special section types,
280// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
281// of regular input input sections, therefore our way of defining symbols for
282// regular sections will not work. The approach we use for special section types
283// is not perfect - it handles only start and end symbols.
284template <class ELFT>
285void addStartEndSymbols(OutputSectionCommand *Cmd,
286 OutputSectionBase<ELFT> *Sec) {
287 bool Start = true;
288 BaseCommand *PrevCmd = nullptr;
289
290 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
291 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
292 if (auto *Sym = cast_or_null<DefinedSynthetic<ELFT>>(AssignCmd->Sym)) {
293 Sym->Section = Sec;
294 Sym->Value =
295 AssignCmd->Expression(Sec->getVA() + (Start ? 0 : Sec->getSize())) -
296 Sec->getVA();
297 }
298 } else {
299 if (!Start && isa<SymbolAssignment>(PrevCmd))
300 error("section '" + Sec->getName() +
301 "' supports only start and end symbols");
302 Start = false;
303 }
304 PrevCmd = Base.get();
305 }
306}
307
308template <class ELFT>
309void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000310 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000311 if (!OutSec) {
312 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000313 // This section is not regular output section. However linker script may
314 // have defined start/end symbols for it. This case is handled below.
315 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000316 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000317 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000318 typedef typename ELFT::uint uintX_t;
319 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000320 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000321
Eugene Leviant97403d12016-09-01 09:55:57 +0000322 // Assigns values to all symbols following the given
323 // input section 'D' in output section 'Sec'. When symbols
324 // are in the beginning of output section the value of 'D'
325 // is nullptr.
326 auto AssignSuccessors = [&](InputSectionData *D) {
327 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
328 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
329 if (!AssignCmd)
330 continue;
331 if (D != AssignCmd->GoesAfter)
332 break;
333
334 uintX_t Value = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
335 if (AssignCmd->Name == ".") {
336 // Update to location counter means update to section size.
Eugene Leviantceabe802016-08-11 07:56:43 +0000337 Off = Value;
Eugene Leviant97403d12016-09-01 09:55:57 +0000338 Sec->setSize(Off);
339 continue;
340 }
341
342 if (DefinedSynthetic<ELFT> *Sym =
343 cast_or_null<DefinedSynthetic<ELFT>>(AssignCmd->Sym)) {
Rui Ueyama0c70d3c2016-08-12 03:31:09 +0000344 Sym->Section = OutSec;
345 Sym->Value = Value;
346 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000347 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000348 };
349
350 AssignSuccessors(nullptr);
351 for (InputSection<ELFT> *I : OutSec->Sections) {
352 Off = alignTo(Off, I->Alignment);
353 I->OutSecOff = Off;
354 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000355 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000356 // works correctly in the case below:
357 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
358 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000359 // Add symbols following current input section.
360 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000361 }
362}
363
George Rimar8f66df92016-08-12 20:38:20 +0000364template <class ELFT>
365static OutputSectionBase<ELFT> *
366findSection(OutputSectionCommand &Cmd,
367 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
368 for (OutputSectionBase<ELFT> *Sec : Sections) {
369 if (Sec->getName() != Cmd.Name)
370 continue;
371 if (checkConstraint(Sec->getFlags(), Cmd.Constraint))
372 return Sec;
373 }
374 return nullptr;
375}
376
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000377template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000378 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000379 // are not explicitly placed into the output file by the linker script.
380 // We place orphan sections at end of file.
381 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000382 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000383 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000384 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000385 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000386 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000387 }
George Rimar652852c2016-04-16 10:10:32 +0000388
Rui Ueyama7c18c282016-04-18 21:00:40 +0000389 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000390 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000391 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000392 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000393
George Rimar076fe152016-07-21 06:43:01 +0000394 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
395 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000396 if (Cmd->Name == ".") {
397 Dot = Cmd->Expression(Dot);
398 } else if (Cmd->Sym) {
399 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
400 }
George Rimar652852c2016-04-16 10:10:32 +0000401 continue;
402 }
403
George Rimareefa7582016-08-04 09:29:31 +0000404 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
405 Cmd->Expression(Dot);
406 continue;
407 }
408
George Rimar076fe152016-07-21 06:43:01 +0000409 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar8f66df92016-08-12 20:38:20 +0000410 OutputSectionBase<ELFT> *Sec = findSection<ELFT>(*Cmd, *OutputSections);
411 if (!Sec)
George Rimarb6c52e82016-08-12 19:32:45 +0000412 continue;
George Rimar652852c2016-04-16 10:10:32 +0000413
George Rimarb6c52e82016-08-12 19:32:45 +0000414 if (Cmd->AddrExpr)
415 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000416
George Rimarb6c52e82016-08-12 19:32:45 +0000417 if (Cmd->AlignExpr)
418 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000419
George Rimarb6c52e82016-08-12 19:32:45 +0000420 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
421 uintX_t TVA = Dot + ThreadBssOffset;
422 TVA = alignTo(TVA, Sec->getAlignment());
423 Sec->setVA(TVA);
Eugene Leviant20889c52016-08-31 08:13:33 +0000424 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000425 ThreadBssOffset = TVA - Dot + Sec->getSize();
426 continue;
George Rimar652852c2016-04-16 10:10:32 +0000427 }
George Rimarb6c52e82016-08-12 19:32:45 +0000428
429 if (!(Sec->getFlags() & SHF_ALLOC)) {
Eugene Leviant20889c52016-08-31 08:13:33 +0000430 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000431 continue;
432 }
433
434 Dot = alignTo(Dot, Sec->getAlignment());
435 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000436 assignOffsets(Cmd, Sec);
George Rimarb6c52e82016-08-12 19:32:45 +0000437 MinVA = std::min(MinVA, Dot);
438 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000439 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000440
Rafael Espindola64c32d62016-07-07 14:28:47 +0000441 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000442 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000443 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
444 Out<ELFT>::ProgramHeaders->getSize(),
445 Target->PageSize);
446 Out<ELFT>::ElfHeader->setVA(MinVA);
447 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000448}
449
Rui Ueyama464daad2016-08-22 04:55:20 +0000450// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000451template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000452std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000453 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000454
Rui Ueyama464daad2016-08-22 04:55:20 +0000455 // Process PHDRS and FILEHDR keywords because they are not
456 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000457 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000458 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
459 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000460
461 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000462 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000463 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000464 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000465 }
466
Rui Ueyama464daad2016-08-22 04:55:20 +0000467 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000468 PhdrEntry<ELFT> *Load = nullptr;
469 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000470 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 if (!(Sec->getFlags() & SHF_ALLOC))
472 break;
473
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000474 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000475 if (!PhdrIds.empty()) {
476 // Assign headers specified by linker script
477 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000478 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000479 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000480 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000481 }
482 } else {
483 // If we have no load segment or flags've changed then we want new load
484 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000485 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000487 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 Flags = NewFlags;
489 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000490 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000491 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000492 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000493 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000494}
495
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000496template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
497 // Ignore .interp section in case we have PHDRS specification
498 // and PT_INTERP isn't listed.
499 return !Opt.PhdrsCommands.empty() &&
500 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
501 return Cmd.Type == PT_INTERP;
502 }) == Opt.PhdrsCommands.end();
503}
504
Eugene Leviantbbe38602016-07-19 09:25:43 +0000505template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000506ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000507 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
508 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
509 if (Cmd->Name == Name)
510 return Cmd->Filler;
511 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000512}
513
George Rimar206fffa2016-08-17 08:16:57 +0000514template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000515 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
516 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
517 if (Cmd->LmaExpr && Cmd->Name == Name)
518 return Cmd->LmaExpr;
519 return {};
520}
521
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000522// Returns the index of the given section name in linker script
523// SECTIONS commands. Sections are laid out as the same order as they
524// were in the script. If a given name did not appear in the script,
525// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000526template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000527 int I = 0;
528 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
529 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
530 if (Cmd->Name == Name)
531 return I;
532 ++I;
533 }
534 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000535}
536
537// A compartor to sort output sections. Returns -1 or 1 if
538// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000539template <class ELFT>
540int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000541 int I = getSectionIndex(A);
542 int J = getSectionIndex(B);
543 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000544 return 0;
545 return I < J ? -1 : 1;
546}
547
Eugene Leviantbbe38602016-07-19 09:25:43 +0000548template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
549 return !Opt.PhdrsCommands.empty();
550}
551
George Rimar9e694502016-07-29 16:18:47 +0000552template <class ELFT>
George Rimar96659df2016-08-30 09:54:01 +0000553typename ELFT::uint
554LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
555 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
556 if (Sec->getName() == Name)
557 return Sec->getVA();
558 error("undefined section " + Name);
559 return 0;
560}
561
562template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000563typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
564 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
565 if (Sec->getName() == Name)
566 return Sec->getSize();
567 error("undefined section " + Name);
568 return 0;
569}
570
George Rimare32a3592016-08-10 07:59:34 +0000571template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000572typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000573 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
574}
575
Eugene Leviantbbe38602016-07-19 09:25:43 +0000576// Returns indices of ELF headers containing specific section, identified
577// by Name. Each index is a zero based number of ELF header listed within
578// PHDRS {} script block.
579template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000580std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000581 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
582 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000583 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000584 continue;
585
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000586 std::vector<size_t> Ret;
587 for (StringRef PhdrName : Cmd->Phdrs)
588 Ret.push_back(getPhdrIndex(PhdrName));
589 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000590 }
George Rimar31d842f2016-07-20 16:43:03 +0000591 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000592}
593
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000594template <class ELFT>
595size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
596 size_t I = 0;
597 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
598 if (Cmd.Name == PhdrName)
599 return I;
600 ++I;
601 }
602 error("section header '" + PhdrName + "' is not listed in PHDRS");
603 return 0;
604}
605
Rui Ueyama07320e42016-04-20 20:13:41 +0000606class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000607 typedef void (ScriptParser::*Handler)();
608
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000609public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000610 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000611
George Rimar20b65982016-08-31 09:08:26 +0000612 void readLinkerScript();
613 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000614
615private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000616 void addFile(StringRef Path);
617
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000618 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000619 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000620 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000621 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000622 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000623 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000624 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000625 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000626 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000627 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000628 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000629 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000630 void readVersion();
631 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000632
Rui Ueyama113cdec2016-07-24 23:05:57 +0000633 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000634 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000635 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000636 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000637 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000638 std::vector<StringRef> readInputFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000639 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000640 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000641 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000642 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000643 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000644 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000645 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000646
647 Expr readExpr();
648 Expr readExpr1(Expr Lhs, int MinPrec);
649 Expr readPrimary();
650 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000651 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000652
George Rimar20b65982016-08-31 09:08:26 +0000653 // For parsing version script.
654 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000655 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000656 void readGlobal(StringRef VerStr);
657 void readLocal();
658
George Rimarc3794e52016-02-24 09:21:47 +0000659 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000660 ScriptConfiguration &Opt = *ScriptConfig;
661 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000662 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000663};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000664
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000665const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000666 {"ENTRY", &ScriptParser::readEntry},
667 {"EXTERN", &ScriptParser::readExtern},
668 {"GROUP", &ScriptParser::readGroup},
669 {"INCLUDE", &ScriptParser::readInclude},
670 {"INPUT", &ScriptParser::readGroup},
671 {"OUTPUT", &ScriptParser::readOutput},
672 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
673 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000674 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000675 {"SEARCH_DIR", &ScriptParser::readSearchDir},
676 {"SECTIONS", &ScriptParser::readSections},
Rui Ueyama95769b42016-08-31 20:03:54 +0000677 {"VERSION", &ScriptParser::readVersion},
George Rimarc3794e52016-02-24 09:21:47 +0000678 {";", &ScriptParser::readNothing}};
679
George Rimar20b65982016-08-31 09:08:26 +0000680void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000681 readVersionScriptCommand();
682 if (!atEOF())
683 setError("EOF expected, but got " + next());
684}
685
686void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000687 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000688 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000689 return;
690 }
691
Rui Ueyama95769b42016-08-31 20:03:54 +0000692 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000693 StringRef VerStr = next();
694 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000695 setError("anonymous version definition is used in "
696 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000697 return;
698 }
699 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000700 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000701 }
702}
703
Rui Ueyama95769b42016-08-31 20:03:54 +0000704void ScriptParser::readVersion() {
705 expect("{");
706 readVersionScriptCommand();
707 expect("}");
708}
709
George Rimar20b65982016-08-31 09:08:26 +0000710void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000711 while (!atEOF()) {
712 StringRef Tok = next();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000713 if (Handler Fn = Cmd.lookup(Tok)) {
George Rimarc3794e52016-02-24 09:21:47 +0000714 (this->*Fn)();
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000715 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
716 if (Opt.HasContents)
717 Opt.Commands.emplace_back(Cmd);
718 else
719 Opt.Assignments.emplace_back(Cmd);
720 } else {
George Rimar57610422016-03-11 14:43:02 +0000721 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000722 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000723 }
724}
725
Rui Ueyama717677a2016-02-11 21:17:59 +0000726void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000727 if (IsUnderSysroot && S.startswith("/")) {
728 SmallString<128> Path;
729 (Config->Sysroot + S).toStringRef(Path);
730 if (sys::fs::exists(Path)) {
731 Driver->addFile(Saver.save(Path.str()));
732 return;
733 }
734 }
735
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000736 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000737 Driver->addFile(S);
738 } else if (S.startswith("=")) {
739 if (Config->Sysroot.empty())
740 Driver->addFile(S.substr(1));
741 else
742 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
743 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000744 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000745 } else if (sys::fs::exists(S)) {
746 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000747 } else {
748 std::string Path = findFromSearchPaths(S);
749 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000750 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000751 else
752 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000753 }
754}
755
Rui Ueyama717677a2016-02-11 21:17:59 +0000756void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000757 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000758 bool Orig = Config->AsNeeded;
759 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000760 while (!Error && !skip(")"))
761 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000762 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000763}
764
Rui Ueyama717677a2016-02-11 21:17:59 +0000765void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000766 // -e <symbol> takes predecence over ENTRY(<symbol>).
767 expect("(");
768 StringRef Tok = next();
769 if (Config->Entry.empty())
770 Config->Entry = Tok;
771 expect(")");
772}
773
Rui Ueyama717677a2016-02-11 21:17:59 +0000774void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000775 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000776 while (!Error && !skip(")"))
777 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000778}
779
Rui Ueyama717677a2016-02-11 21:17:59 +0000780void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000781 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000782 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000783 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000784 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000785 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000786 else
787 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000788 }
789}
790
Rui Ueyama717677a2016-02-11 21:17:59 +0000791void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000792 StringRef Tok = next();
793 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000794 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000795 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000796 return;
797 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000798 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000799 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
800 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000801 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000802}
803
Rui Ueyama717677a2016-02-11 21:17:59 +0000804void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000805 // -o <file> takes predecence over OUTPUT(<file>).
806 expect("(");
807 StringRef Tok = next();
808 if (Config->OutputFile.empty())
809 Config->OutputFile = Tok;
810 expect(")");
811}
812
Rui Ueyama717677a2016-02-11 21:17:59 +0000813void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000814 // Error checking only for now.
815 expect("(");
816 next();
817 expect(")");
818}
819
Rui Ueyama717677a2016-02-11 21:17:59 +0000820void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000821 // Error checking only for now.
822 expect("(");
823 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000824 StringRef Tok = next();
825 if (Tok == ")")
826 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000827 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000828 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000829 return;
830 }
Davide Italiano6836c612015-10-12 21:08:41 +0000831 next();
832 expect(",");
833 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000834 expect(")");
835}
836
Eugene Leviantbbe38602016-07-19 09:25:43 +0000837void ScriptParser::readPhdrs() {
838 expect("{");
839 while (!Error && !skip("}")) {
840 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000841 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000842 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
843
844 PhdrCmd.Type = readPhdrType();
845 do {
846 Tok = next();
847 if (Tok == ";")
848 break;
849 if (Tok == "FILEHDR")
850 PhdrCmd.HasFilehdr = true;
851 else if (Tok == "PHDRS")
852 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000853 else if (Tok == "FLAGS") {
854 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000855 // Passing 0 for the value of dot is a bit of a hack. It means that
856 // we accept expressions like ".|1".
857 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000858 expect(")");
859 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000860 setError("unexpected header attribute: " + Tok);
861 } while (!Error);
862 }
863}
864
Rui Ueyama717677a2016-02-11 21:17:59 +0000865void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000866 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000867 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000868 expect(")");
869}
870
Rui Ueyama717677a2016-02-11 21:17:59 +0000871void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000872 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000873 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000874 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000875 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000876 BaseCommand *Cmd = readProvideOrAssignment(Tok);
877 if (!Cmd) {
878 if (Tok == "ASSERT")
879 Cmd = new AssertCommand(readAssert());
880 else
881 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000882 }
Rui Ueyama10416562016-08-04 02:03:27 +0000883 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000884 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000885}
886
Rui Ueyama708019c2016-07-24 18:19:40 +0000887static int precedence(StringRef Op) {
888 return StringSwitch<int>(Op)
889 .Case("*", 4)
890 .Case("/", 4)
891 .Case("+", 3)
892 .Case("-", 3)
893 .Case("<", 2)
894 .Case(">", 2)
895 .Case(">=", 2)
896 .Case("<=", 2)
897 .Case("==", 2)
898 .Case("!=", 2)
899 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000900 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000901 .Default(-1);
902}
903
Rui Ueyama10416562016-08-04 02:03:27 +0000904std::vector<StringRef> ScriptParser::readInputFilePatterns() {
905 std::vector<StringRef> V;
906 while (!Error && !skip(")"))
907 V.push_back(next());
908 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000909}
910
Rui Ueyama742c3832016-08-04 22:27:00 +0000911SortKind ScriptParser::readSortKind() {
912 if (skip("SORT") || skip("SORT_BY_NAME"))
913 return SortByName;
914 if (skip("SORT_BY_ALIGNMENT"))
915 return SortByAlignment;
916 return SortNone;
917}
918
George Rimara2496cb2016-08-30 09:46:59 +0000919InputSectionDescription *
920ScriptParser::readInputSectionRules(StringRef FilePattern) {
Rui Ueyama10416562016-08-04 02:03:27 +0000921 auto *Cmd = new InputSectionDescription;
George Rimara2496cb2016-08-30 09:46:59 +0000922 Cmd->FilePattern = FilePattern;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000923 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000924
Rui Ueyama742c3832016-08-04 22:27:00 +0000925 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000926 if (skip("EXCLUDE_FILE")) {
927 expect("(");
928 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000929 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000930 }
George Rimar06598002016-07-28 21:51:30 +0000931
Rui Ueyama742c3832016-08-04 22:27:00 +0000932 // Read SORT().
933 if (SortKind K1 = readSortKind()) {
934 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000935 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000936 if (SortKind K2 = readSortKind()) {
937 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000938 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000939 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000940 expect(")");
941 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000942 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000943 }
George Rimar0702c4e2016-07-29 15:32:46 +0000944 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000945 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000946 }
George Rimar0702c4e2016-07-29 15:32:46 +0000947
Rui Ueyama10416562016-08-04 02:03:27 +0000948 Cmd->SectionPatterns = readInputFilePatterns();
949 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000950}
951
George Rimara2496cb2016-08-30 09:46:59 +0000952InputSectionDescription *
953ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000954 // Input section wildcard can be surrounded by KEEP.
955 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000956 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000957 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000958 StringRef FilePattern = next();
959 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000960 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000961 Opt.KeptSections.insert(Opt.KeptSections.end(),
962 Cmd->SectionPatterns.begin(),
963 Cmd->SectionPatterns.end());
964 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000965 }
George Rimara2496cb2016-08-30 09:46:59 +0000966 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000967}
968
George Rimar03fc0102016-07-28 07:18:23 +0000969void ScriptParser::readSort() {
970 expect("(");
971 expect("CONSTRUCTORS");
972 expect(")");
973}
974
George Rimareefa7582016-08-04 09:29:31 +0000975Expr ScriptParser::readAssert() {
976 expect("(");
977 Expr E = readExpr();
978 expect(",");
979 StringRef Msg = next();
980 expect(")");
981 return [=](uint64_t Dot) {
982 uint64_t V = E(Dot);
983 if (!V)
984 error(Msg);
985 return V;
986 };
987}
988
Rui Ueyama10416562016-08-04 02:03:27 +0000989OutputSectionCommand *
990ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000991 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000992
993 // Read an address expression.
994 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
995 if (peek() != ":")
996 Cmd->AddrExpr = readExpr();
997
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000998 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000999
George Rimar8ceadb32016-08-17 07:44:19 +00001000 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001001 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001002 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001003 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001004 if (skip("SUBALIGN"))
1005 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001006
Davide Italiano246f6812016-07-22 03:36:24 +00001007 // Parse constraints.
1008 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001009 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001010 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001011 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001012 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001013
Rui Ueyama025d59b2016-02-02 20:27:59 +00001014 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001015 StringRef Tok = next();
1016 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1017 Cmd->Commands.emplace_back(Assignment);
1018 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001019 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001020 else if (peek() == "(")
1021 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001022 else
1023 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001024 }
George Rimar076fe152016-07-21 06:43:01 +00001025 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001026 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +00001027 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001028}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001029
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001030// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1031// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1032//
1033// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1034// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1035// as 32-bit big-endian values. We will do the same as ld.gold does
1036// because it's simpler than what ld.bfd does.
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001037std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001038 if (!peek().startswith("="))
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001039 return {};
Rui Ueyama965827d2016-08-03 23:25:15 +00001040
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001041 StringRef Tok = next();
Rui Ueyama965827d2016-08-03 23:25:15 +00001042 uint32_t V;
1043 if (Tok.substr(1).getAsInteger(0, V)) {
1044 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001045 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001046 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001047 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001048}
1049
Petr Hoseka35e39c2016-08-16 01:11:16 +00001050SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001051 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001052 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001053 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001054 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001055 expect(")");
1056 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001057 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001058}
1059
Eugene Leviantceabe802016-08-11 07:56:43 +00001060SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1061 SymbolAssignment *Cmd = nullptr;
1062 if (peek() == "=" || peek() == "+=") {
1063 Cmd = readAssignment(Tok);
1064 expect(";");
1065 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001066 Cmd = readProvideHidden(true, false);
1067 } else if (Tok == "HIDDEN") {
1068 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001069 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001070 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001071 }
1072 return Cmd;
1073}
1074
George Rimar30835ea2016-07-28 21:08:56 +00001075static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1076 if (S == ".")
1077 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001078
George Rimara9c5a522016-07-26 18:18:58 +00001079 switch (Config->EKind) {
1080 case ELF32LEKind:
1081 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1082 return B->getVA<ELF32LE>();
1083 break;
1084 case ELF32BEKind:
1085 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1086 return B->getVA<ELF32BE>();
1087 break;
1088 case ELF64LEKind:
1089 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1090 return B->getVA<ELF64LE>();
1091 break;
1092 case ELF64BEKind:
1093 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1094 return B->getVA<ELF64BE>();
1095 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001096 default:
George Rimarb567b622016-07-26 18:46:13 +00001097 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001098 }
1099 error("symbol not found: " + S);
1100 return 0;
1101}
1102
George Rimar9e694502016-07-29 16:18:47 +00001103static uint64_t getSectionSize(StringRef Name) {
1104 switch (Config->EKind) {
1105 case ELF32LEKind:
1106 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1107 case ELF32BEKind:
1108 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1109 case ELF64LEKind:
1110 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1111 case ELF64BEKind:
1112 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1113 default:
1114 llvm_unreachable("unsupported target");
1115 }
George Rimar9e694502016-07-29 16:18:47 +00001116}
1117
George Rimar96659df2016-08-30 09:54:01 +00001118static uint64_t getSectionAddress(StringRef Name) {
1119 switch (Config->EKind) {
1120 case ELF32LEKind:
1121 return Script<ELF32LE>::X->getOutputSectionAddress(Name);
1122 case ELF32BEKind:
1123 return Script<ELF32BE>::X->getOutputSectionAddress(Name);
1124 case ELF64LEKind:
1125 return Script<ELF64LE>::X->getOutputSectionAddress(Name);
1126 case ELF64BEKind:
1127 return Script<ELF64BE>::X->getOutputSectionAddress(Name);
1128 default:
1129 llvm_unreachable("unsupported target");
1130 }
1131}
1132
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001133static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001134 switch (Config->EKind) {
1135 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001136 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001137 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001138 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001139 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001140 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001141 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001142 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001143 default:
1144 llvm_unreachable("unsupported target");
1145 }
1146}
1147
George Rimar30835ea2016-07-28 21:08:56 +00001148SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1149 StringRef Op = next();
1150 assert(Op == "=" || Op == "+=");
1151 Expr E = readExpr();
1152 if (Op == "+=")
1153 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001154 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001155}
1156
1157// This is an operator-precedence parser to parse a linker
1158// script expression.
1159Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1160
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001161static Expr combine(StringRef Op, Expr L, Expr R) {
1162 if (Op == "*")
1163 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1164 if (Op == "/") {
1165 return [=](uint64_t Dot) -> uint64_t {
1166 uint64_t RHS = R(Dot);
1167 if (RHS == 0) {
1168 error("division by zero");
1169 return 0;
1170 }
1171 return L(Dot) / RHS;
1172 };
1173 }
1174 if (Op == "+")
1175 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1176 if (Op == "-")
1177 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1178 if (Op == "<")
1179 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1180 if (Op == ">")
1181 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1182 if (Op == ">=")
1183 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1184 if (Op == "<=")
1185 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1186 if (Op == "==")
1187 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1188 if (Op == "!=")
1189 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1190 if (Op == "&")
1191 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001192 if (Op == "|")
1193 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001194 llvm_unreachable("invalid operator");
1195}
1196
Rui Ueyama708019c2016-07-24 18:19:40 +00001197// This is a part of the operator-precedence parser. This function
1198// assumes that the remaining token stream starts with an operator.
1199Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1200 while (!atEOF() && !Error) {
1201 // Read an operator and an expression.
1202 StringRef Op1 = peek();
1203 if (Op1 == "?")
1204 return readTernary(Lhs);
1205 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001206 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001207 next();
1208 Expr Rhs = readPrimary();
1209
1210 // Evaluate the remaining part of the expression first if the
1211 // next operator has greater precedence than the previous one.
1212 // For example, if we have read "+" and "3", and if the next
1213 // operator is "*", then we'll evaluate 3 * ... part first.
1214 while (!atEOF()) {
1215 StringRef Op2 = peek();
1216 if (precedence(Op2) <= precedence(Op1))
1217 break;
1218 Rhs = readExpr1(Rhs, precedence(Op2));
1219 }
1220
1221 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001222 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001223 return Lhs;
1224}
1225
1226uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001227 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001228 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001229 if (S == "MAXPAGESIZE")
1230 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001231 error("unknown constant: " + S);
1232 return 0;
1233}
1234
Rui Ueyama626e0b02016-09-02 18:19:00 +00001235// Parses Tok as an integer. Returns true if successful.
1236// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1237// and decimal numbers. Decimal numbers may have "K" (kilo) or
1238// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001239static bool readInteger(StringRef Tok, uint64_t &Result) {
1240 if (Tok.startswith_lower("0x"))
1241 return !Tok.substr(2).getAsInteger(16, Result);
1242 if (Tok.endswith_lower("H"))
1243 return !Tok.drop_back().getAsInteger(16, Result);
1244
1245 int Suffix = 1;
1246 if (Tok.endswith_lower("K")) {
1247 Suffix = 1024;
1248 Tok = Tok.drop_back();
1249 } else if (Tok.endswith_lower("M")) {
1250 Suffix = 1024 * 1024;
1251 Tok = Tok.drop_back();
1252 }
1253 if (Tok.getAsInteger(10, Result))
1254 return false;
1255 Result *= Suffix;
1256 return true;
1257}
1258
Rui Ueyama708019c2016-07-24 18:19:40 +00001259Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001260 if (peek() == "(")
1261 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001262
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001263 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001264
1265 // Built-in functions are parsed here.
1266 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001267 if (Tok == "ADDR") {
1268 expect("(");
1269 StringRef Name = next();
1270 expect(")");
1271 return [=](uint64_t Dot) { return getSectionAddress(Name); };
1272 }
George Rimareefa7582016-08-04 09:29:31 +00001273 if (Tok == "ASSERT")
1274 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001275 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001276 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001277 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1278 }
1279 if (Tok == "CONSTANT") {
1280 expect("(");
1281 StringRef Tok = next();
1282 expect(")");
1283 return [=](uint64_t Dot) { return getConstant(Tok); };
1284 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001285 if (Tok == "SEGMENT_START") {
1286 expect("(");
1287 next();
1288 expect(",");
1289 uint64_t Val;
1290 next().getAsInteger(0, Val);
1291 expect(")");
1292 return [=](uint64_t Dot) { return Val; };
1293 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001294 if (Tok == "DATA_SEGMENT_ALIGN") {
1295 expect("(");
1296 Expr E = readExpr();
1297 expect(",");
1298 readExpr();
1299 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001300 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001301 }
1302 if (Tok == "DATA_SEGMENT_END") {
1303 expect("(");
1304 expect(".");
1305 expect(")");
1306 return [](uint64_t Dot) { return Dot; };
1307 }
George Rimar276b4e62016-07-26 17:58:44 +00001308 // GNU linkers implements more complicated logic to handle
1309 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1310 // the next page boundary for simplicity.
1311 if (Tok == "DATA_SEGMENT_RELRO_END") {
1312 expect("(");
1313 next();
1314 expect(",");
1315 readExpr();
1316 expect(")");
1317 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1318 }
George Rimar9e694502016-07-29 16:18:47 +00001319 if (Tok == "SIZEOF") {
1320 expect("(");
1321 StringRef Name = next();
1322 expect(")");
1323 return [=](uint64_t Dot) { return getSectionSize(Name); };
1324 }
George Rimare32a3592016-08-10 07:59:34 +00001325 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001326 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001327
George Rimar9f2f7ad2016-09-02 16:01:42 +00001328 // Tok is a literal number.
1329 uint64_t V;
1330 if (readInteger(Tok, V))
1331 return [=](uint64_t Dot) { return V; };
1332
1333 // Tok is a symbol name.
1334 if (Tok != "." && !isValidCIdentifier(Tok))
1335 setError("malformed number: " + Tok);
1336 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001337}
1338
1339Expr ScriptParser::readTernary(Expr Cond) {
1340 next();
1341 Expr L = readExpr();
1342 expect(":");
1343 Expr R = readExpr();
1344 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1345}
1346
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001347Expr ScriptParser::readParenExpr() {
1348 expect("(");
1349 Expr E = readExpr();
1350 expect(")");
1351 return E;
1352}
1353
Eugene Leviantbbe38602016-07-19 09:25:43 +00001354std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1355 std::vector<StringRef> Phdrs;
1356 while (!Error && peek().startswith(":")) {
1357 StringRef Tok = next();
1358 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1359 if (Tok.empty()) {
1360 setError("section header name is empty");
1361 break;
1362 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001363 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001364 }
1365 return Phdrs;
1366}
1367
1368unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001369 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001370 unsigned Ret = StringSwitch<unsigned>(Tok)
1371 .Case("PT_NULL", PT_NULL)
1372 .Case("PT_LOAD", PT_LOAD)
1373 .Case("PT_DYNAMIC", PT_DYNAMIC)
1374 .Case("PT_INTERP", PT_INTERP)
1375 .Case("PT_NOTE", PT_NOTE)
1376 .Case("PT_SHLIB", PT_SHLIB)
1377 .Case("PT_PHDR", PT_PHDR)
1378 .Case("PT_TLS", PT_TLS)
1379 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1380 .Case("PT_GNU_STACK", PT_GNU_STACK)
1381 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1382 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001383
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001384 if (Ret == (unsigned)-1) {
1385 setError("invalid program header type: " + Tok);
1386 return PT_NULL;
1387 }
1388 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001389}
1390
Rui Ueyama95769b42016-08-31 20:03:54 +00001391void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001392 // Identifiers start at 2 because 0 and 1 are reserved
1393 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1394 size_t VersionId = Config->VersionDefinitions.size() + 2;
1395 Config->VersionDefinitions.push_back({VerStr, VersionId});
1396
1397 if (skip("global:") || peek() != "local:")
1398 readGlobal(VerStr);
1399 if (skip("local:"))
1400 readLocal();
1401 expect("}");
1402
1403 // Each version may have a parent version. For example, "Ver2" defined as
1404 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1405 // version hierarchy is, probably against your instinct, purely for human; the
1406 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1407 if (!VerStr.empty() && peek() != ";")
1408 next();
1409 expect(";");
1410}
1411
1412void ScriptParser::readLocal() {
1413 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1414 expect("*");
1415 expect(";");
1416}
1417
1418void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1419 expect("C++");
1420 expect("{");
1421
1422 for (;;) {
1423 if (peek() == "}" || Error)
1424 break;
1425 Globals->push_back({next(), true});
1426 expect(";");
1427 }
1428
1429 expect("}");
1430 expect(";");
1431}
1432
1433void ScriptParser::readGlobal(StringRef VerStr) {
1434 std::vector<SymbolVersion> *Globals;
1435 if (VerStr.empty())
1436 Globals = &Config->VersionScriptGlobals;
1437 else
1438 Globals = &Config->VersionDefinitions.back().Globals;
1439
1440 for (;;) {
1441 if (skip("extern"))
1442 readExtern(Globals);
1443
1444 StringRef Cur = peek();
1445 if (Cur == "}" || Cur == "local:" || Error)
1446 return;
1447 next();
1448 Globals->push_back({Cur, false});
1449 expect(";");
1450 }
1451}
1452
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001453static bool isUnderSysroot(StringRef Path) {
1454 if (Config->Sysroot == "")
1455 return false;
1456 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1457 if (sys::fs::equivalent(Config->Sysroot, Path))
1458 return true;
1459 return false;
1460}
1461
Rui Ueyama07320e42016-04-20 20:13:41 +00001462void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001463 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001464 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1465}
1466
1467void elf::readVersionScript(MemoryBufferRef MB) {
1468 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001469}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001470
Rui Ueyama07320e42016-04-20 20:13:41 +00001471template class elf::LinkerScript<ELF32LE>;
1472template class elf::LinkerScript<ELF32BE>;
1473template class elf::LinkerScript<ELF64LE>;
1474template class elf::LinkerScript<ELF64BE>;