blob: a6fbe64d5ee2a3b626ac5680f518793dfd65f0e2 [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
Eugene Leviantdb741e72016-09-07 07:08:43 +000059template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
60 if (Cmd->IsAbsolute)
61 addRegular<ELFT>(Cmd);
62 else
63 addSynthetic<ELFT>(Cmd);
64}
Rui Ueyama16024212016-08-11 23:22:52 +000065// If a symbol was in PROVIDE(), we need to define it only when
66// it is an undefined symbol.
67template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
68 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000069 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000070 if (!Cmd->Provide)
71 return true;
72 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
73 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000074}
75
George Rimar076fe152016-07-21 06:43:01 +000076bool SymbolAssignment::classof(const BaseCommand *C) {
77 return C->Kind == AssignmentKind;
78}
79
80bool OutputSectionCommand::classof(const BaseCommand *C) {
81 return C->Kind == OutputSectionKind;
82}
83
George Rimareea31142016-07-21 14:26:59 +000084bool InputSectionDescription::classof(const BaseCommand *C) {
85 return C->Kind == InputSectionKind;
86}
87
George Rimareefa7582016-08-04 09:29:31 +000088bool AssertCommand::classof(const BaseCommand *C) {
89 return C->Kind == AssertKind;
90}
91
Rui Ueyama36a153c2016-07-23 14:09:58 +000092template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000093 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000094}
95
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000096template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
97template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
98
Rui Ueyama07320e42016-04-20 20:13:41 +000099template <class ELFT>
100bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000101 for (Regex *Re : Opt.KeptSections)
102 if (Re->match(S->getSectionName()))
George Rimareea31142016-07-21 14:26:59 +0000103 return true;
104 return false;
105}
106
George Rimar06598002016-07-28 21:51:30 +0000107static bool fileMatches(const InputSectionDescription *Desc,
108 StringRef Filename) {
George Rimarc91930a2016-09-02 21:17:20 +0000109 return const_cast<Regex &>(Desc->FileRe).match(Filename) &&
110 !const_cast<Regex &>(Desc->ExcludedFileRe).match(Filename);
George Rimar06598002016-07-28 21:51:30 +0000111}
112
Rui Ueyama6b274812016-07-25 22:51:07 +0000113// Returns input sections filtered by given glob patterns.
114template <class ELFT>
115std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000116LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimarc91930a2016-09-02 21:17:20 +0000117 const Regex &Re = I->SectionRe;
Rui Ueyama6b274812016-07-25 22:51:07 +0000118 std::vector<InputSectionBase<ELFT> *> Ret;
119 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000120 Symtab<ELFT>::X->getObjectFiles()) {
121 if (fileMatches(I, sys::path::filename(F->getName())))
122 for (InputSectionBase<ELFT> *S : F->getSections())
123 if (!isDiscarded(S) && !S->OutSec &&
George Rimarc91930a2016-09-02 21:17:20 +0000124 const_cast<Regex &>(Re).match(S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000125 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000126 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000127
George Rimarc91930a2016-09-02 21:17:20 +0000128 if (const_cast<Regex &>(Re).match("COMMON"))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000129 Ret.push_back(CommonInputSection<ELFT>::X);
Rui Ueyama6b274812016-07-25 22:51:07 +0000130 return Ret;
131}
132
Eugene Leviantceabe802016-08-11 07:56:43 +0000133template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000134static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
135 return A->getSectionName() < B->getSectionName();
136}
George Rimar350ece42016-08-03 08:35:59 +0000137
Rui Ueyama742c3832016-08-04 22:27:00 +0000138template <class ELFT>
139static bool compareAlignment(InputSectionBase<ELFT> *A,
140 InputSectionBase<ELFT> *B) {
141 // ">" is not a mistake. Larger alignments are placed before smaller
142 // alignments in order to reduce the amount of padding necessary.
143 // This is compatible with GNU.
144 return A->Alignment > B->Alignment;
145}
George Rimar350ece42016-08-03 08:35:59 +0000146
Rui Ueyama742c3832016-08-04 22:27:00 +0000147template <class ELFT>
148static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
149getComparator(SortKind K) {
150 if (K == SortByName)
151 return compareName<ELFT>;
152 return compareAlignment<ELFT>;
153}
George Rimar0702c4e2016-07-29 15:32:46 +0000154
155template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000156void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
157 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
158 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
159 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
160 S->Live = false;
161 reportDiscarded(S);
162 }
163 }
164 }
165}
166
George Rimar8f66df92016-08-12 20:38:20 +0000167static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
168 bool RO = (Kind == ConstraintKind::ReadOnly);
169 bool RW = (Kind == ConstraintKind::ReadWrite);
170 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000171 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000172}
173
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000174template <class ELFT>
George Rimar06ae6832016-08-12 09:07:57 +0000175static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
176 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000177 if (Kind == ConstraintKind::NoConstraint)
178 return true;
179 return llvm::all_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
180 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000181 });
182}
183
184template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000185std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000186LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000187 std::vector<InputSectionBase<ELFT> *> Ret;
Eugene Leviant97403d12016-09-01 09:55:57 +0000188 DenseSet<InputSectionBase<ELFT> *> SectionIndex;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000189
George Rimar06ae6832016-08-12 09:07:57 +0000190 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
191 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
192 if (shouldDefine<ELFT>(OutCmd))
Eugene Leviantdb741e72016-09-07 07:08:43 +0000193 addSymbol<ELFT>(OutCmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000194 OutCmd->GoesAfter = Ret.empty() ? nullptr : Ret.back();
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000195 continue;
196 }
197
198 auto *Cmd = cast<InputSectionDescription>(Base.get());
199 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
George Rimar06ae6832016-08-12 09:07:57 +0000200 if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
201 continue;
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000202 if (Cmd->SortInner)
203 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
204 if (Cmd->SortOuter)
205 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
Eugene Leviant97403d12016-09-01 09:55:57 +0000206
207 // Add all input sections corresponding to rule 'Cmd' to
208 // resulting vector. We do not add duplicate input sections.
209 for (InputSectionBase<ELFT> *S : V)
210 if (SectionIndex.insert(S).second)
211 Ret.push_back(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000212 }
213 return Ret;
214}
215
216template <class ELFT>
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000217void LinkerScript<ELFT>::createAssignments() {
218 for (const std::unique_ptr<SymbolAssignment> &Cmd : Opt.Assignments) {
219 if (shouldDefine<ELFT>(Cmd.get()))
220 addRegular<ELFT>(Cmd.get());
221 if (Cmd->Sym)
222 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
223 }
224}
225
226template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000227void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000228 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000229 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
230 if (shouldDefine<ELFT>(Cmd))
231 addRegular<ELFT>(Cmd);
232 continue;
233 }
234
Eugene Leviantceabe802016-08-11 07:56:43 +0000235 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000236 if (Cmd->Name == "/DISCARD/") {
237 discard(*Cmd);
238 continue;
239 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000240
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000241 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
Eugene Leviant97403d12016-09-01 09:55:57 +0000242 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000243 continue;
244
George Rimardb24d9c2016-08-19 15:18:23 +0000245 for (InputSectionBase<ELFT> *Sec : V) {
George Rimara14b13d2016-09-07 10:46:07 +0000246 OutputSectionBase<ELFT> *OutSec;
247 bool IsNew;
248 std::tie(OutSec, IsNew) = Factory.create(Sec, Cmd->Name);
249 if (IsNew)
250 OutputSections->push_back(OutSec);
251
252 uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0;
253
George Rimardb24d9c2016-08-19 15:18:23 +0000254 if (Subalign)
255 Sec->Alignment = Subalign;
Eugene Leviant97403d12016-09-01 09:55:57 +0000256 OutSec->addSection(Sec);
George Rimardb24d9c2016-08-19 15:18:23 +0000257 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000258 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000259 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000260
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000261 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000262 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000263 Symtab<ELFT>::X->getObjectFiles()) {
264 for (InputSectionBase<ELFT> *S : F->getSections()) {
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000265 if (isDiscarded(S) || S->OutSec)
266 continue;
267 OutputSectionBase<ELFT> *OutSec;
268 bool IsNew;
269 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
270 if (IsNew)
271 OutputSections->push_back(OutSec);
272 OutSec->addSection(S);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000273 }
274 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000275}
276
Eugene Leviantdb741e72016-09-07 07:08:43 +0000277// Sets value of a section-defined symbol. Two kinds of
278// symbols are processed: synthetic symbols, whose value
279// is an offset from beginning of section and regular
280// symbols whose value is absolute.
281template <class ELFT>
282static void assignSectionSymbol(SymbolAssignment *Cmd,
283 OutputSectionBase<ELFT> *Sec,
284 typename ELFT::uint Off) {
285 if (!Cmd->Sym)
286 return;
287
288 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
289 Body->Section = Sec;
290 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
291 return;
292 }
293 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
294 Body->Value = Cmd->Expression(Sec->getVA() + Off);
295}
296
Eugene Leviant20889c52016-08-31 08:13:33 +0000297// Linker script may define start and end symbols for special section types,
298// like .got, .eh_frame_hdr, .eh_frame and others. Those sections are not a list
299// of regular input input sections, therefore our way of defining symbols for
300// regular sections will not work. The approach we use for special section types
301// is not perfect - it handles only start and end symbols.
302template <class ELFT>
303void addStartEndSymbols(OutputSectionCommand *Cmd,
304 OutputSectionBase<ELFT> *Sec) {
305 bool Start = true;
306 BaseCommand *PrevCmd = nullptr;
307
308 for (std::unique_ptr<BaseCommand> &Base : Cmd->Commands) {
309 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(Base.get())) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000310 assignSectionSymbol<ELFT>(AssignCmd, Sec, Start ? 0 : Sec->getSize());
Eugene Leviant20889c52016-08-31 08:13:33 +0000311 } else {
312 if (!Start && isa<SymbolAssignment>(PrevCmd))
313 error("section '" + Sec->getName() +
314 "' supports only start and end symbols");
315 Start = false;
316 }
317 PrevCmd = Base.get();
318 }
319}
320
321template <class ELFT>
322void assignOffsets(OutputSectionCommand *Cmd, OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000323 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000324 if (!OutSec) {
325 Sec->assignOffsets();
Eugene Leviant20889c52016-08-31 08:13:33 +0000326 // This section is not regular output section. However linker script may
327 // have defined start/end symbols for it. This case is handled below.
328 addStartEndSymbols(Cmd, Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000329 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000330 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000331 typedef typename ELFT::uint uintX_t;
332 uintX_t Off = 0;
Eugene Leviant97403d12016-09-01 09:55:57 +0000333 auto ItCmd = Cmd->Commands.begin();
Eugene Leviantceabe802016-08-11 07:56:43 +0000334
Eugene Leviant97403d12016-09-01 09:55:57 +0000335 // Assigns values to all symbols following the given
336 // input section 'D' in output section 'Sec'. When symbols
337 // are in the beginning of output section the value of 'D'
338 // is nullptr.
339 auto AssignSuccessors = [&](InputSectionData *D) {
340 for (; ItCmd != Cmd->Commands.end(); ++ItCmd) {
341 auto *AssignCmd = dyn_cast<SymbolAssignment>(ItCmd->get());
342 if (!AssignCmd)
343 continue;
344 if (D != AssignCmd->GoesAfter)
345 break;
346
Eugene Leviant97403d12016-09-01 09:55:57 +0000347 if (AssignCmd->Name == ".") {
348 // Update to location counter means update to section size.
Eugene Leviantdb741e72016-09-07 07:08:43 +0000349 Off = AssignCmd->Expression(Sec->getVA() + Off) - Sec->getVA();
Eugene Leviant97403d12016-09-01 09:55:57 +0000350 Sec->setSize(Off);
351 continue;
352 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000353 assignSectionSymbol<ELFT>(AssignCmd, Sec, Off);
Eugene Leviantceabe802016-08-11 07:56:43 +0000354 }
Eugene Leviant97403d12016-09-01 09:55:57 +0000355 };
356
357 AssignSuccessors(nullptr);
358 for (InputSection<ELFT> *I : OutSec->Sections) {
359 Off = alignTo(Off, I->Alignment);
360 I->OutSecOff = Off;
361 Off += I->getSize();
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000362 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000363 // works correctly in the case below:
364 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
365 Sec->setSize(Off);
Eugene Leviant97403d12016-09-01 09:55:57 +0000366 // Add symbols following current input section.
367 AssignSuccessors(I);
Eugene Leviantceabe802016-08-11 07:56:43 +0000368 }
369}
370
George Rimar8f66df92016-08-12 20:38:20 +0000371template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000372static std::vector<OutputSectionBase<ELFT> *>
373findSections(OutputSectionCommand &Cmd,
374 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
375 std::vector<OutputSectionBase<ELFT> *> Ret;
376 for (OutputSectionBase<ELFT> *Sec : Sections)
377 if (Sec->getName() == Cmd.Name &&
378 checkConstraint(Sec->getFlags(), Cmd.Constraint))
379 Ret.push_back(Sec);
380 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000381}
382
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000383template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000384 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000385 // are not explicitly placed into the output file by the linker script.
386 // We place orphan sections at end of file.
387 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000388 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000389 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000390 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000391 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000392 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000393 }
George Rimar652852c2016-04-16 10:10:32 +0000394
Rui Ueyama7c18c282016-04-18 21:00:40 +0000395 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000396 Dot = getHeaderSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000397 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000398 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000399
George Rimar076fe152016-07-21 06:43:01 +0000400 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
401 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000402 if (Cmd->Name == ".") {
403 Dot = Cmd->Expression(Dot);
404 } else if (Cmd->Sym) {
405 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
406 }
George Rimar652852c2016-04-16 10:10:32 +0000407 continue;
408 }
409
George Rimareefa7582016-08-04 09:29:31 +0000410 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
411 Cmd->Expression(Dot);
412 continue;
413 }
414
George Rimar076fe152016-07-21 06:43:01 +0000415 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimara14b13d2016-09-07 10:46:07 +0000416 for (OutputSectionBase<ELFT> *Sec :
417 findSections<ELFT>(*Cmd, *OutputSections)) {
George Rimar652852c2016-04-16 10:10:32 +0000418
George Rimara14b13d2016-09-07 10:46:07 +0000419 if (Cmd->AddrExpr)
420 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000421
George Rimara14b13d2016-09-07 10:46:07 +0000422 if (Cmd->AlignExpr)
423 Sec->updateAlignment(Cmd->AlignExpr(Dot));
George Rimar630c6172016-07-26 18:06:29 +0000424
George Rimara14b13d2016-09-07 10:46:07 +0000425 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
426 uintX_t TVA = Dot + ThreadBssOffset;
427 TVA = alignTo(TVA, Sec->getAlignment());
428 Sec->setVA(TVA);
429 assignOffsets(Cmd, Sec);
430 ThreadBssOffset = TVA - Dot + Sec->getSize();
431 continue;
432 }
433
434 if (!(Sec->getFlags() & SHF_ALLOC)) {
435 assignOffsets(Cmd, Sec);
436 continue;
437 }
438
439 Dot = alignTo(Dot, Sec->getAlignment());
440 Sec->setVA(Dot);
Eugene Leviant20889c52016-08-31 08:13:33 +0000441 assignOffsets(Cmd, Sec);
George Rimara14b13d2016-09-07 10:46:07 +0000442 MinVA = std::min(MinVA, Dot);
443 Dot += Sec->getSize();
George Rimar652852c2016-04-16 10:10:32 +0000444 }
445 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000446
Rafael Espindola64c32d62016-07-07 14:28:47 +0000447 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000448 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000449 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
450 Out<ELFT>::ProgramHeaders->getSize(),
451 Target->PageSize);
452 Out<ELFT>::ElfHeader->setVA(MinVA);
453 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000454}
455
Rui Ueyama464daad2016-08-22 04:55:20 +0000456// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000457template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000458std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000459 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000460
Rui Ueyama464daad2016-08-22 04:55:20 +0000461 // Process PHDRS and FILEHDR keywords because they are not
462 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000463 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000464 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
465 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000466
467 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000468 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000469 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000470 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 }
472
Rui Ueyama464daad2016-08-22 04:55:20 +0000473 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000474 PhdrEntry<ELFT> *Load = nullptr;
475 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000476 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 if (!(Sec->getFlags() & SHF_ALLOC))
478 break;
479
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000480 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000481 if (!PhdrIds.empty()) {
482 // Assign headers specified by linker script
483 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000484 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000485 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000486 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 }
488 } else {
489 // If we have no load segment or flags've changed then we want new load
490 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000491 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000492 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000493 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000494 Flags = NewFlags;
495 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000496 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000497 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000498 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000499 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000500}
501
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000502template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
503 // Ignore .interp section in case we have PHDRS specification
504 // and PT_INTERP isn't listed.
505 return !Opt.PhdrsCommands.empty() &&
506 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
507 return Cmd.Type == PT_INTERP;
508 }) == Opt.PhdrsCommands.end();
509}
510
Eugene Leviantbbe38602016-07-19 09:25:43 +0000511template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000512ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000513 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
514 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
515 if (Cmd->Name == Name)
516 return Cmd->Filler;
517 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000518}
519
George Rimar206fffa2016-08-17 08:16:57 +0000520template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000521 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
522 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
523 if (Cmd->LmaExpr && Cmd->Name == Name)
524 return Cmd->LmaExpr;
525 return {};
526}
527
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000528// Returns the index of the given section name in linker script
529// SECTIONS commands. Sections are laid out as the same order as they
530// were in the script. If a given name did not appear in the script,
531// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000532template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000533 int I = 0;
534 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
535 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
536 if (Cmd->Name == Name)
537 return I;
538 ++I;
539 }
540 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000541}
542
543// A compartor to sort output sections. Returns -1 or 1 if
544// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000545template <class ELFT>
546int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000547 int I = getSectionIndex(A);
548 int J = getSectionIndex(B);
549 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000550 return 0;
551 return I < J ? -1 : 1;
552}
553
Eugene Leviantbbe38602016-07-19 09:25:43 +0000554template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
555 return !Opt.PhdrsCommands.empty();
556}
557
George Rimar9e694502016-07-29 16:18:47 +0000558template <class ELFT>
George Rimar96659df2016-08-30 09:54:01 +0000559typename ELFT::uint
560LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
561 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
562 if (Sec->getName() == Name)
563 return Sec->getVA();
564 error("undefined section " + Name);
565 return 0;
566}
567
568template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000569typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
570 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
571 if (Sec->getName() == Name)
572 return Sec->getSize();
573 error("undefined section " + Name);
574 return 0;
575}
576
George Rimare32a3592016-08-10 07:59:34 +0000577template <class ELFT>
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000578typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000579 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
580}
581
Eugene Leviantbbe38602016-07-19 09:25:43 +0000582// Returns indices of ELF headers containing specific section, identified
583// by Name. Each index is a zero based number of ELF header listed within
584// PHDRS {} script block.
585template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000586std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000587 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
588 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000589 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000590 continue;
591
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000592 std::vector<size_t> Ret;
593 for (StringRef PhdrName : Cmd->Phdrs)
594 Ret.push_back(getPhdrIndex(PhdrName));
595 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000596 }
George Rimar31d842f2016-07-20 16:43:03 +0000597 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000598}
599
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000600template <class ELFT>
601size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
602 size_t I = 0;
603 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
604 if (Cmd.Name == PhdrName)
605 return I;
606 ++I;
607 }
608 error("section header '" + PhdrName + "' is not listed in PHDRS");
609 return 0;
610}
611
Rui Ueyama07320e42016-04-20 20:13:41 +0000612class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000613 typedef void (ScriptParser::*Handler)();
614
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000615public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000616 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000617
George Rimar20b65982016-08-31 09:08:26 +0000618 void readLinkerScript();
619 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000620
621private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000622 void addFile(StringRef Path);
623
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000624 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000625 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000626 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000627 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000628 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000629 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000630 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000631 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000632 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000633 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000634 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000635 void readVersion();
636 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000637
Rui Ueyama113cdec2016-07-24 23:05:57 +0000638 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000639 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000640 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000641 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000642 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000643 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000644 Regex readFilePatterns();
George Rimara2496cb2016-08-30 09:46:59 +0000645 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000646 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000647 SortKind readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000648 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000649 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000650 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000651 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000652
653 Expr readExpr();
654 Expr readExpr1(Expr Lhs, int MinPrec);
655 Expr readPrimary();
656 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000657 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000658
George Rimar20b65982016-08-31 09:08:26 +0000659 // For parsing version script.
660 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000661 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000662 void readGlobal(StringRef VerStr);
663 void readLocal();
664
Rui Ueyama07320e42016-04-20 20:13:41 +0000665 ScriptConfiguration &Opt = *ScriptConfig;
666 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000667 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000668};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000669
George Rimar20b65982016-08-31 09:08:26 +0000670void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000671 readVersionScriptCommand();
672 if (!atEOF())
673 setError("EOF expected, but got " + next());
674}
675
676void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000677 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000678 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000679 return;
680 }
681
Rui Ueyama95769b42016-08-31 20:03:54 +0000682 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000683 StringRef VerStr = next();
684 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000685 setError("anonymous version definition is used in "
686 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000687 return;
688 }
689 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000690 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000691 }
692}
693
Rui Ueyama95769b42016-08-31 20:03:54 +0000694void ScriptParser::readVersion() {
695 expect("{");
696 readVersionScriptCommand();
697 expect("}");
698}
699
George Rimar20b65982016-08-31 09:08:26 +0000700void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000701 while (!atEOF()) {
702 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000703 if (Tok == ";")
704 continue;
705
706 if (Tok == "ENTRY") {
707 readEntry();
708 } else if (Tok == "EXTERN") {
709 readExtern();
710 } else if (Tok == "GROUP" || Tok == "INPUT") {
711 readGroup();
712 } else if (Tok == "INCLUDE") {
713 readInclude();
714 } else if (Tok == "OUTPUT") {
715 readOutput();
716 } else if (Tok == "OUTPUT_ARCH") {
717 readOutputArch();
718 } else if (Tok == "OUTPUT_FORMAT") {
719 readOutputFormat();
720 } else if (Tok == "PHDRS") {
721 readPhdrs();
722 } else if (Tok == "SEARCH_DIR") {
723 readSearchDir();
724 } else if (Tok == "SECTIONS") {
725 readSections();
726 } else if (Tok == "VERSION") {
727 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000728 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000729 if (Opt.HasContents)
730 Opt.Commands.emplace_back(Cmd);
731 else
732 Opt.Assignments.emplace_back(Cmd);
733 } else {
George Rimar57610422016-03-11 14:43:02 +0000734 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000735 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000736 }
737}
738
Rui Ueyama717677a2016-02-11 21:17:59 +0000739void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000740 if (IsUnderSysroot && S.startswith("/")) {
741 SmallString<128> Path;
742 (Config->Sysroot + S).toStringRef(Path);
743 if (sys::fs::exists(Path)) {
744 Driver->addFile(Saver.save(Path.str()));
745 return;
746 }
747 }
748
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000749 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000750 Driver->addFile(S);
751 } else if (S.startswith("=")) {
752 if (Config->Sysroot.empty())
753 Driver->addFile(S.substr(1));
754 else
755 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
756 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000757 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000758 } else if (sys::fs::exists(S)) {
759 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000760 } else {
761 std::string Path = findFromSearchPaths(S);
762 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000763 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000764 else
765 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000766 }
767}
768
Rui Ueyama717677a2016-02-11 21:17:59 +0000769void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000770 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000771 bool Orig = Config->AsNeeded;
772 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000773 while (!Error && !skip(")"))
774 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000775 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000776}
777
Rui Ueyama717677a2016-02-11 21:17:59 +0000778void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000779 // -e <symbol> takes predecence over ENTRY(<symbol>).
780 expect("(");
781 StringRef Tok = next();
782 if (Config->Entry.empty())
783 Config->Entry = Tok;
784 expect(")");
785}
786
Rui Ueyama717677a2016-02-11 21:17:59 +0000787void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000788 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000789 while (!Error && !skip(")"))
790 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000791}
792
Rui Ueyama717677a2016-02-11 21:17:59 +0000793void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000794 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000795 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000796 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000797 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000798 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000799 else
800 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000801 }
802}
803
Rui Ueyama717677a2016-02-11 21:17:59 +0000804void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000805 StringRef Tok = next();
806 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000807 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000808 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000809 return;
810 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000811 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000812 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
813 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000814 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000815}
816
Rui Ueyama717677a2016-02-11 21:17:59 +0000817void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000818 // -o <file> takes predecence over OUTPUT(<file>).
819 expect("(");
820 StringRef Tok = next();
821 if (Config->OutputFile.empty())
822 Config->OutputFile = Tok;
823 expect(")");
824}
825
Rui Ueyama717677a2016-02-11 21:17:59 +0000826void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000827 // Error checking only for now.
828 expect("(");
829 next();
830 expect(")");
831}
832
Rui Ueyama717677a2016-02-11 21:17:59 +0000833void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000834 // Error checking only for now.
835 expect("(");
836 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000837 StringRef Tok = next();
838 if (Tok == ")")
839 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000840 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000841 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000842 return;
843 }
Davide Italiano6836c612015-10-12 21:08:41 +0000844 next();
845 expect(",");
846 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000847 expect(")");
848}
849
Eugene Leviantbbe38602016-07-19 09:25:43 +0000850void ScriptParser::readPhdrs() {
851 expect("{");
852 while (!Error && !skip("}")) {
853 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000854 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000855 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
856
857 PhdrCmd.Type = readPhdrType();
858 do {
859 Tok = next();
860 if (Tok == ";")
861 break;
862 if (Tok == "FILEHDR")
863 PhdrCmd.HasFilehdr = true;
864 else if (Tok == "PHDRS")
865 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000866 else if (Tok == "FLAGS") {
867 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000868 // Passing 0 for the value of dot is a bit of a hack. It means that
869 // we accept expressions like ".|1".
870 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000871 expect(")");
872 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000873 setError("unexpected header attribute: " + Tok);
874 } while (!Error);
875 }
876}
877
Rui Ueyama717677a2016-02-11 21:17:59 +0000878void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000879 expect("(");
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000880 if (!Config->Nostdlib)
881 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000882 expect(")");
883}
884
Rui Ueyama717677a2016-02-11 21:17:59 +0000885void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000886 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000887 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000888 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000889 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000890 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000891 if (!Cmd) {
892 if (Tok == "ASSERT")
893 Cmd = new AssertCommand(readAssert());
894 else
895 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000896 }
Rui Ueyama10416562016-08-04 02:03:27 +0000897 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000898 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000899}
900
Rui Ueyama708019c2016-07-24 18:19:40 +0000901static int precedence(StringRef Op) {
902 return StringSwitch<int>(Op)
903 .Case("*", 4)
904 .Case("/", 4)
905 .Case("+", 3)
906 .Case("-", 3)
907 .Case("<", 2)
908 .Case(">", 2)
909 .Case(">=", 2)
910 .Case("<=", 2)
911 .Case("==", 2)
912 .Case("!=", 2)
913 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +0000914 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +0000915 .Default(-1);
916}
917
George Rimarc91930a2016-09-02 21:17:20 +0000918Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +0000919 std::vector<StringRef> V;
920 while (!Error && !skip(")"))
921 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +0000922 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +0000923}
924
Rui Ueyama742c3832016-08-04 22:27:00 +0000925SortKind ScriptParser::readSortKind() {
926 if (skip("SORT") || skip("SORT_BY_NAME"))
927 return SortByName;
928 if (skip("SORT_BY_ALIGNMENT"))
929 return SortByAlignment;
930 return SortNone;
931}
932
George Rimara2496cb2016-08-30 09:46:59 +0000933InputSectionDescription *
934ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +0000935 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000936 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000937
Rui Ueyama742c3832016-08-04 22:27:00 +0000938 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000939 if (skip("EXCLUDE_FILE")) {
940 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000941 Cmd->ExcludedFileRe = readFilePatterns();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000942 }
George Rimar06598002016-07-28 21:51:30 +0000943
Rui Ueyama742c3832016-08-04 22:27:00 +0000944 // Read SORT().
945 if (SortKind K1 = readSortKind()) {
946 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000947 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000948 if (SortKind K2 = readSortKind()) {
949 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000950 expect("(");
George Rimarc91930a2016-09-02 21:17:20 +0000951 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000952 expect(")");
953 } else {
George Rimarc91930a2016-09-02 21:17:20 +0000954 Cmd->SectionRe = readFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000955 }
George Rimar0702c4e2016-07-29 15:32:46 +0000956 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000957 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000958 }
George Rimar0702c4e2016-07-29 15:32:46 +0000959
George Rimarc91930a2016-09-02 21:17:20 +0000960 Cmd->SectionRe = readFilePatterns();
Rui Ueyama10416562016-08-04 02:03:27 +0000961 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000962}
963
George Rimara2496cb2016-08-30 09:46:59 +0000964InputSectionDescription *
965ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +0000966 // Input section wildcard can be surrounded by KEEP.
967 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +0000968 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000969 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +0000970 StringRef FilePattern = next();
971 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +0000972 expect(")");
George Rimarc91930a2016-09-02 21:17:20 +0000973 Opt.KeptSections.push_back(&Cmd->SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +0000974 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000975 }
George Rimara2496cb2016-08-30 09:46:59 +0000976 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +0000977}
978
George Rimar03fc0102016-07-28 07:18:23 +0000979void ScriptParser::readSort() {
980 expect("(");
981 expect("CONSTRUCTORS");
982 expect(")");
983}
984
George Rimareefa7582016-08-04 09:29:31 +0000985Expr ScriptParser::readAssert() {
986 expect("(");
987 Expr E = readExpr();
988 expect(",");
989 StringRef Msg = next();
990 expect(")");
991 return [=](uint64_t Dot) {
992 uint64_t V = E(Dot);
993 if (!V)
994 error(Msg);
995 return V;
996 };
997}
998
Rui Ueyama25150e82016-09-06 17:46:43 +0000999// Reads a FILL(expr) command. We handle the FILL command as an
1000// alias for =fillexp section attribute, which is different from
1001// what GNU linkers do.
1002// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001003std::vector<uint8_t> ScriptParser::readFill() {
1004 expect("(");
1005 std::vector<uint8_t> V = readOutputSectionFiller(next());
1006 expect(")");
1007 expect(";");
1008 return V;
1009}
1010
Rui Ueyama10416562016-08-04 02:03:27 +00001011OutputSectionCommand *
1012ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001013 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001014
1015 // Read an address expression.
1016 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1017 if (peek() != ":")
1018 Cmd->AddrExpr = readExpr();
1019
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001020 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001021
George Rimar8ceadb32016-08-17 07:44:19 +00001022 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001023 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001024 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001025 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001026 if (skip("SUBALIGN"))
1027 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001028
Davide Italiano246f6812016-07-22 03:36:24 +00001029 // Parse constraints.
1030 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001031 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001032 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001033 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001034 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001035
Rui Ueyama025d59b2016-02-02 20:27:59 +00001036 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001037 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001038 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001039 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001040 else if (Tok == "FILL")
1041 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001042 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001043 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001044 else if (peek() == "(")
1045 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001046 else
1047 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001048 }
George Rimar076fe152016-07-21 06:43:01 +00001049 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001050 if (peek().startswith("="))
1051 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001052 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001053}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001054
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001055// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1056// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1057//
1058// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1059// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1060// as 32-bit big-endian values. We will do the same as ld.gold does
1061// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001062std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001063 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001064 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001065 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001066 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001067 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001068 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001069}
1070
Petr Hoseka35e39c2016-08-16 01:11:16 +00001071SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001072 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001073 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001074 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001075 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001076 expect(")");
1077 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001078 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001079}
1080
Eugene Leviantdb741e72016-09-07 07:08:43 +00001081SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1082 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001083 SymbolAssignment *Cmd = nullptr;
1084 if (peek() == "=" || peek() == "+=") {
1085 Cmd = readAssignment(Tok);
1086 expect(";");
1087 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001088 Cmd = readProvideHidden(true, false);
1089 } else if (Tok == "HIDDEN") {
1090 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001091 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001092 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001093 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001094 if (Cmd && MakeAbsolute)
1095 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001096 return Cmd;
1097}
1098
George Rimar30835ea2016-07-28 21:08:56 +00001099static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1100 if (S == ".")
1101 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001102
George Rimara9c5a522016-07-26 18:18:58 +00001103 switch (Config->EKind) {
1104 case ELF32LEKind:
1105 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1106 return B->getVA<ELF32LE>();
1107 break;
1108 case ELF32BEKind:
1109 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1110 return B->getVA<ELF32BE>();
1111 break;
1112 case ELF64LEKind:
1113 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1114 return B->getVA<ELF64LE>();
1115 break;
1116 case ELF64BEKind:
1117 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1118 return B->getVA<ELF64BE>();
1119 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001120 default:
George Rimarb567b622016-07-26 18:46:13 +00001121 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001122 }
1123 error("symbol not found: " + S);
1124 return 0;
1125}
1126
George Rimar9e694502016-07-29 16:18:47 +00001127static uint64_t getSectionSize(StringRef Name) {
1128 switch (Config->EKind) {
1129 case ELF32LEKind:
1130 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1131 case ELF32BEKind:
1132 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1133 case ELF64LEKind:
1134 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1135 case ELF64BEKind:
1136 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1137 default:
1138 llvm_unreachable("unsupported target");
1139 }
George Rimar9e694502016-07-29 16:18:47 +00001140}
1141
George Rimar96659df2016-08-30 09:54:01 +00001142static uint64_t getSectionAddress(StringRef Name) {
1143 switch (Config->EKind) {
1144 case ELF32LEKind:
1145 return Script<ELF32LE>::X->getOutputSectionAddress(Name);
1146 case ELF32BEKind:
1147 return Script<ELF32BE>::X->getOutputSectionAddress(Name);
1148 case ELF64LEKind:
1149 return Script<ELF64LE>::X->getOutputSectionAddress(Name);
1150 case ELF64BEKind:
1151 return Script<ELF64BE>::X->getOutputSectionAddress(Name);
1152 default:
1153 llvm_unreachable("unsupported target");
1154 }
1155}
1156
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001157static uint64_t getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +00001158 switch (Config->EKind) {
1159 case ELF32LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001160 return Script<ELF32LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001161 case ELF32BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001162 return Script<ELF32BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001163 case ELF64LEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001164 return Script<ELF64LE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001165 case ELF64BEKind:
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001166 return Script<ELF64BE>::X->getHeaderSize();
George Rimare32a3592016-08-10 07:59:34 +00001167 default:
1168 llvm_unreachable("unsupported target");
1169 }
1170}
1171
George Rimar30835ea2016-07-28 21:08:56 +00001172SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1173 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001174 bool IsAbsolute = false;
1175 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001176 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001177 if (skip("ABSOLUTE")) {
1178 E = readParenExpr();
1179 IsAbsolute = true;
1180 } else {
1181 E = readExpr();
1182 }
George Rimar30835ea2016-07-28 21:08:56 +00001183 if (Op == "+=")
1184 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001185 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001186}
1187
1188// This is an operator-precedence parser to parse a linker
1189// script expression.
1190Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1191
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001192static Expr combine(StringRef Op, Expr L, Expr R) {
1193 if (Op == "*")
1194 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1195 if (Op == "/") {
1196 return [=](uint64_t Dot) -> uint64_t {
1197 uint64_t RHS = R(Dot);
1198 if (RHS == 0) {
1199 error("division by zero");
1200 return 0;
1201 }
1202 return L(Dot) / RHS;
1203 };
1204 }
1205 if (Op == "+")
1206 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1207 if (Op == "-")
1208 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1209 if (Op == "<")
1210 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1211 if (Op == ">")
1212 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1213 if (Op == ">=")
1214 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1215 if (Op == "<=")
1216 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1217 if (Op == "==")
1218 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1219 if (Op == "!=")
1220 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1221 if (Op == "&")
1222 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001223 if (Op == "|")
1224 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001225 llvm_unreachable("invalid operator");
1226}
1227
Rui Ueyama708019c2016-07-24 18:19:40 +00001228// This is a part of the operator-precedence parser. This function
1229// assumes that the remaining token stream starts with an operator.
1230Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1231 while (!atEOF() && !Error) {
1232 // Read an operator and an expression.
1233 StringRef Op1 = peek();
1234 if (Op1 == "?")
1235 return readTernary(Lhs);
1236 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001237 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001238 next();
1239 Expr Rhs = readPrimary();
1240
1241 // Evaluate the remaining part of the expression first if the
1242 // next operator has greater precedence than the previous one.
1243 // For example, if we have read "+" and "3", and if the next
1244 // operator is "*", then we'll evaluate 3 * ... part first.
1245 while (!atEOF()) {
1246 StringRef Op2 = peek();
1247 if (precedence(Op2) <= precedence(Op1))
1248 break;
1249 Rhs = readExpr1(Rhs, precedence(Op2));
1250 }
1251
1252 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001253 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001254 return Lhs;
1255}
1256
1257uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001258 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001259 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001260 if (S == "MAXPAGESIZE")
1261 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001262 error("unknown constant: " + S);
1263 return 0;
1264}
1265
Rui Ueyama626e0b02016-09-02 18:19:00 +00001266// Parses Tok as an integer. Returns true if successful.
1267// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1268// and decimal numbers. Decimal numbers may have "K" (kilo) or
1269// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001270static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001271 if (Tok.startswith("-")) {
1272 if (!readInteger(Tok.substr(1), Result))
1273 return false;
1274 Result = -Result;
1275 return true;
1276 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001277 if (Tok.startswith_lower("0x"))
1278 return !Tok.substr(2).getAsInteger(16, Result);
1279 if (Tok.endswith_lower("H"))
1280 return !Tok.drop_back().getAsInteger(16, Result);
1281
1282 int Suffix = 1;
1283 if (Tok.endswith_lower("K")) {
1284 Suffix = 1024;
1285 Tok = Tok.drop_back();
1286 } else if (Tok.endswith_lower("M")) {
1287 Suffix = 1024 * 1024;
1288 Tok = Tok.drop_back();
1289 }
1290 if (Tok.getAsInteger(10, Result))
1291 return false;
1292 Result *= Suffix;
1293 return true;
1294}
1295
Rui Ueyama708019c2016-07-24 18:19:40 +00001296Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001297 if (peek() == "(")
1298 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001299
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001300 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001301
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001302 if (Tok == "~") {
1303 Expr E = readPrimary();
1304 return [=](uint64_t Dot) { return ~E(Dot); };
1305 }
1306 if (Tok == "-") {
1307 Expr E = readPrimary();
1308 return [=](uint64_t Dot) { return -E(Dot); };
1309 }
1310
Rui Ueyama708019c2016-07-24 18:19:40 +00001311 // Built-in functions are parsed here.
1312 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001313 if (Tok == "ADDR") {
1314 expect("(");
1315 StringRef Name = next();
1316 expect(")");
1317 return [=](uint64_t Dot) { return getSectionAddress(Name); };
1318 }
George Rimareefa7582016-08-04 09:29:31 +00001319 if (Tok == "ASSERT")
1320 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001321 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001322 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001323 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1324 }
1325 if (Tok == "CONSTANT") {
1326 expect("(");
1327 StringRef Tok = next();
1328 expect(")");
1329 return [=](uint64_t Dot) { return getConstant(Tok); };
1330 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001331 if (Tok == "SEGMENT_START") {
1332 expect("(");
1333 next();
1334 expect(",");
1335 uint64_t Val;
1336 next().getAsInteger(0, Val);
1337 expect(")");
1338 return [=](uint64_t Dot) { return Val; };
1339 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001340 if (Tok == "DATA_SEGMENT_ALIGN") {
1341 expect("(");
1342 Expr E = readExpr();
1343 expect(",");
1344 readExpr();
1345 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001346 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001347 }
1348 if (Tok == "DATA_SEGMENT_END") {
1349 expect("(");
1350 expect(".");
1351 expect(")");
1352 return [](uint64_t Dot) { return Dot; };
1353 }
George Rimar276b4e62016-07-26 17:58:44 +00001354 // GNU linkers implements more complicated logic to handle
1355 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1356 // the next page boundary for simplicity.
1357 if (Tok == "DATA_SEGMENT_RELRO_END") {
1358 expect("(");
1359 next();
1360 expect(",");
1361 readExpr();
1362 expect(")");
1363 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1364 }
George Rimar9e694502016-07-29 16:18:47 +00001365 if (Tok == "SIZEOF") {
1366 expect("(");
1367 StringRef Name = next();
1368 expect(")");
1369 return [=](uint64_t Dot) { return getSectionSize(Name); };
1370 }
George Rimare32a3592016-08-10 07:59:34 +00001371 if (Tok == "SIZEOF_HEADERS")
Rui Ueyama4f7500b2016-08-12 04:00:22 +00001372 return [=](uint64_t Dot) { return getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001373
George Rimar9f2f7ad2016-09-02 16:01:42 +00001374 // Tok is a literal number.
1375 uint64_t V;
1376 if (readInteger(Tok, V))
1377 return [=](uint64_t Dot) { return V; };
1378
1379 // Tok is a symbol name.
1380 if (Tok != "." && !isValidCIdentifier(Tok))
1381 setError("malformed number: " + Tok);
1382 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001383}
1384
1385Expr ScriptParser::readTernary(Expr Cond) {
1386 next();
1387 Expr L = readExpr();
1388 expect(":");
1389 Expr R = readExpr();
1390 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1391}
1392
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001393Expr ScriptParser::readParenExpr() {
1394 expect("(");
1395 Expr E = readExpr();
1396 expect(")");
1397 return E;
1398}
1399
Eugene Leviantbbe38602016-07-19 09:25:43 +00001400std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1401 std::vector<StringRef> Phdrs;
1402 while (!Error && peek().startswith(":")) {
1403 StringRef Tok = next();
1404 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1405 if (Tok.empty()) {
1406 setError("section header name is empty");
1407 break;
1408 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001409 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001410 }
1411 return Phdrs;
1412}
1413
1414unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001415 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001416 unsigned Ret = StringSwitch<unsigned>(Tok)
1417 .Case("PT_NULL", PT_NULL)
1418 .Case("PT_LOAD", PT_LOAD)
1419 .Case("PT_DYNAMIC", PT_DYNAMIC)
1420 .Case("PT_INTERP", PT_INTERP)
1421 .Case("PT_NOTE", PT_NOTE)
1422 .Case("PT_SHLIB", PT_SHLIB)
1423 .Case("PT_PHDR", PT_PHDR)
1424 .Case("PT_TLS", PT_TLS)
1425 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1426 .Case("PT_GNU_STACK", PT_GNU_STACK)
1427 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1428 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001429
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001430 if (Ret == (unsigned)-1) {
1431 setError("invalid program header type: " + Tok);
1432 return PT_NULL;
1433 }
1434 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001435}
1436
Rui Ueyama95769b42016-08-31 20:03:54 +00001437void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001438 // Identifiers start at 2 because 0 and 1 are reserved
1439 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1440 size_t VersionId = Config->VersionDefinitions.size() + 2;
1441 Config->VersionDefinitions.push_back({VerStr, VersionId});
1442
1443 if (skip("global:") || peek() != "local:")
1444 readGlobal(VerStr);
1445 if (skip("local:"))
1446 readLocal();
1447 expect("}");
1448
1449 // Each version may have a parent version. For example, "Ver2" defined as
1450 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1451 // version hierarchy is, probably against your instinct, purely for human; the
1452 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1453 if (!VerStr.empty() && peek() != ";")
1454 next();
1455 expect(";");
1456}
1457
1458void ScriptParser::readLocal() {
1459 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1460 expect("*");
1461 expect(";");
1462}
1463
1464void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1465 expect("C++");
1466 expect("{");
1467
1468 for (;;) {
1469 if (peek() == "}" || Error)
1470 break;
1471 Globals->push_back({next(), true});
1472 expect(";");
1473 }
1474
1475 expect("}");
1476 expect(";");
1477}
1478
1479void ScriptParser::readGlobal(StringRef VerStr) {
1480 std::vector<SymbolVersion> *Globals;
1481 if (VerStr.empty())
1482 Globals = &Config->VersionScriptGlobals;
1483 else
1484 Globals = &Config->VersionDefinitions.back().Globals;
1485
1486 for (;;) {
1487 if (skip("extern"))
1488 readExtern(Globals);
1489
1490 StringRef Cur = peek();
1491 if (Cur == "}" || Cur == "local:" || Error)
1492 return;
1493 next();
1494 Globals->push_back({Cur, false});
1495 expect(";");
1496 }
1497}
1498
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001499static bool isUnderSysroot(StringRef Path) {
1500 if (Config->Sysroot == "")
1501 return false;
1502 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1503 if (sys::fs::equivalent(Config->Sysroot, Path))
1504 return true;
1505 return false;
1506}
1507
Rui Ueyama07320e42016-04-20 20:13:41 +00001508void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001509 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001510 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1511}
1512
1513void elf::readVersionScript(MemoryBufferRef MB) {
1514 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001515}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001516
Rui Ueyama07320e42016-04-20 20:13:41 +00001517template class elf::LinkerScript<ELF32LE>;
1518template class elf::LinkerScript<ELF32BE>;
1519template class elf::LinkerScript<ELF64LE>;
1520template class elf::LinkerScript<ELF64BE>;