blob: e4f8378417c4ace8e8ba75a5a343006afdf7535c [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
George Rimar884e7862016-09-08 08:19:13 +000044LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000045ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000046
George Rimar6c55f0e2016-09-08 08:20:30 +000047template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000048 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 Leviant20d03192016-09-16 15:30:47 +000051
52 // If we have no SECTIONS then we don't have '.' and don't call
53 // assignAddresses(). We calculate symbol value immediately in this case.
54 if (!ScriptConfig->HasSections)
55 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000056}
57
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000058template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000059 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
60 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000061 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000062}
63
Eugene Leviantdb741e72016-09-07 07:08:43 +000064template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
65 if (Cmd->IsAbsolute)
66 addRegular<ELFT>(Cmd);
67 else
68 addSynthetic<ELFT>(Cmd);
69}
Rui Ueyama16024212016-08-11 23:22:52 +000070// If a symbol was in PROVIDE(), we need to define it only when
71// it is an undefined symbol.
72template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
73 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000074 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000075 if (!Cmd->Provide)
76 return true;
77 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
78 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000079}
80
George Rimar076fe152016-07-21 06:43:01 +000081bool SymbolAssignment::classof(const BaseCommand *C) {
82 return C->Kind == AssignmentKind;
83}
84
85bool OutputSectionCommand::classof(const BaseCommand *C) {
86 return C->Kind == OutputSectionKind;
87}
88
George Rimareea31142016-07-21 14:26:59 +000089bool InputSectionDescription::classof(const BaseCommand *C) {
90 return C->Kind == InputSectionKind;
91}
92
George Rimareefa7582016-08-04 09:29:31 +000093bool AssertCommand::classof(const BaseCommand *C) {
94 return C->Kind == AssertKind;
95}
96
Rui Ueyama36a153c2016-07-23 14:09:58 +000097template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000098 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000099}
100
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000101template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
102template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
103
Rui Ueyama07320e42016-04-20 20:13:41 +0000104template <class ELFT>
105bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
George Rimarc91930a2016-09-02 21:17:20 +0000106 for (Regex *Re : Opt.KeptSections)
Rafael Espindola042a3f22016-09-08 14:06:08 +0000107 if (Re->match(S->Name))
George Rimareea31142016-07-21 14:26:59 +0000108 return true;
109 return false;
110}
111
George Rimar575208c2016-09-15 19:15:12 +0000112static bool comparePriority(InputSectionData *A, InputSectionData *B) {
113 return getPriority(A->Name) < getPriority(B->Name);
114}
115
Rafael Espindolac0028d32016-09-08 20:47:52 +0000116static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000117 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000118}
George Rimar350ece42016-08-03 08:35:59 +0000119
Rafael Espindolac0028d32016-09-08 20:47:52 +0000120static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000121 // ">" is not a mistake. Larger alignments are placed before smaller
122 // alignments in order to reduce the amount of padding necessary.
123 // This is compatible with GNU.
124 return A->Alignment > B->Alignment;
125}
George Rimar350ece42016-08-03 08:35:59 +0000126
Rafael Espindolac0028d32016-09-08 20:47:52 +0000127static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000128getComparator(SortSectionPolicy K) {
129 switch (K) {
130 case SortSectionPolicy::Alignment:
131 return compareAlignment;
132 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000133 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000134 case SortSectionPolicy::Priority:
135 return comparePriority;
136 default:
137 llvm_unreachable("unknown sort policy");
138 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000139}
George Rimar0702c4e2016-07-29 15:32:46 +0000140
George Rimar8f66df92016-08-12 20:38:20 +0000141static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
142 bool RO = (Kind == ConstraintKind::ReadOnly);
143 bool RW = (Kind == ConstraintKind::ReadWrite);
144 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000145 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000146}
147
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000148template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000149static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000150 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000151 if (Kind == ConstraintKind::NoConstraint)
152 return true;
Rafael Espindolad3190792016-09-16 15:10:23 +0000153 return llvm::all_of(Sections, [=](InputSectionData *Sec2) {
154 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
George Rimar8f66df92016-08-12 20:38:20 +0000155 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000156 });
157}
158
Rafael Espindolad3190792016-09-16 15:10:23 +0000159// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000160template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000161void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000162 // Collects all sections that satisfy constraints of I
163 // and attach them to I.
164 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar395281c2016-09-16 17:42:10 +0000165 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000166 StringRef Filename = sys::path::filename(F->getName());
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000167 if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000168 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000169
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000170 for (InputSectionBase<ELFT> *S : F->getSections())
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000171 if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000172 I->Sections.push_back(S);
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000173 if (Pat.SectionRe.match("COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000174 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000175 }
176 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000177
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000178 // Sort for SORT() commands.
Rui Ueyamab2a0abd2016-09-16 21:14:55 +0000179 if (I->SortInner != SortSectionPolicy::Default)
Rafael Espindolad3190792016-09-16 15:10:23 +0000180 std::stable_sort(I->Sections.begin(), I->Sections.end(),
181 getComparator(I->SortInner));
Rui Ueyamab2a0abd2016-09-16 21:14:55 +0000182 if (I->SortOuter != SortSectionPolicy::Default)
Rafael Espindolad3190792016-09-16 15:10:23 +0000183 std::stable_sort(I->Sections.begin(), I->Sections.end(),
184 getComparator(I->SortOuter));
185
186 // We do not add duplicate input sections, so mark them with a dummy output
187 // section for now.
188 for (InputSectionData *S : I->Sections) {
189 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
190 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
191 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000192}
193
194template <class ELFT>
195void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
196 for (InputSectionBase<ELFT> *S : V) {
197 S->Live = false;
198 reportDiscarded(S);
199 }
200}
201
George Rimar06ae6832016-08-12 09:07:57 +0000202template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000203std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000204LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000205 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000206
George Rimar06ae6832016-08-12 09:07:57 +0000207 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000208 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
209 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000210 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000211 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000212 for (InputSectionData *S : Cmd->Sections)
213 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000214 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000215
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000216 return Ret;
217}
218
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000219template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000220static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
221 StringRef OutsecName) {
222 // When using linker script the merge rules are different.
223 // Unfortunately, linker scripts are name based. This means that expressions
224 // like *(.foo*) can refer to multiple input sections that would normally be
225 // placed in different output sections. We cannot put them in different
226 // output sections or we would produce wrong results for
227 // start = .; *(.foo.*) end = .; *(.bar)
228 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
229 // another. The problem is that there is no way to layout those output
230 // sections such that the .foo sections are the only thing between the
231 // start and end symbols.
232
233 // An extra annoyance is that we cannot simply disable merging of the contents
234 // of SHF_MERGE sections, but our implementation requires one output section
235 // per "kind" (string or not, which size/aligment).
236 // Fortunately, creating symbols in the middle of a merge section is not
237 // supported by bfd or gold, so we can just create multiple section in that
238 // case.
239 const typename ELFT::Shdr *H = C->getSectionHdr();
240 typedef typename ELFT::uint uintX_t;
241 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
242
243 uintX_t Alignment = 0;
244 if (isa<MergeInputSection<ELFT>>(C))
245 Alignment = std::max(H->sh_addralign, H->sh_entsize);
246
247 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
248}
249
250template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000251void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
252 InputSectionBase<ELFT> *Sec,
253 StringRef Name) {
254 OutputSectionBase<ELFT> *OutSec;
255 bool IsNew;
256 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
257 if (IsNew)
258 OutputSections->push_back(OutSec);
259 OutSec->addSection(Sec);
260}
261
262template <class ELFT>
263void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000264
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000265 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
266 auto Iter = Opt.Commands.begin() + I;
267 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000268 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
269 if (shouldDefine<ELFT>(Cmd))
270 addRegular<ELFT>(Cmd);
271 continue;
272 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000273 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
274 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000275 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000276 // will not be called, so ASSERT should be evaluated now.
277 if (!Opt.HasSections)
278 Cmd->Expression(0);
279 continue;
280 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000281
Eugene Leviantceabe802016-08-11 07:56:43 +0000282 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000283 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
284
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000285 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000286 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000287 continue;
288 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000289
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000290 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
291 for (InputSectionBase<ELFT> *S : V)
292 S->OutSec = nullptr;
293 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000294 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000295 continue;
296 }
297
298 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
299 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
300 if (shouldDefine<ELFT>(OutCmd))
301 addSymbol<ELFT>(OutCmd);
302
Eugene Leviant97403d12016-09-01 09:55:57 +0000303 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000304 continue;
305
George Rimardb24d9c2016-08-19 15:18:23 +0000306 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000307 addSection(Factory, Sec, Cmd->Name);
308 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000309 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000310 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000311 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000312 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000313}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000314
Eugene Leviant20d03192016-09-16 15:30:47 +0000315template <class ELFT>
316void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
317 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000318 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000319 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
320 for (InputSectionBase<ELFT> *S : F->getSections())
321 if (!isDiscarded(S) && !S->OutSec)
322 addSection(Factory, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000323}
324
Eugene Leviantdb741e72016-09-07 07:08:43 +0000325// Sets value of a section-defined symbol. Two kinds of
326// symbols are processed: synthetic symbols, whose value
327// is an offset from beginning of section and regular
328// symbols whose value is absolute.
329template <class ELFT>
330static void assignSectionSymbol(SymbolAssignment *Cmd,
331 OutputSectionBase<ELFT> *Sec,
332 typename ELFT::uint Off) {
333 if (!Cmd->Sym)
334 return;
335
336 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
337 Body->Section = Sec;
338 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
339 return;
340 }
341 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
342 Body->Value = Cmd->Expression(Sec->getVA() + Off);
343}
344
Rafael Espindolad3190792016-09-16 15:10:23 +0000345template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
346 if (!AlreadyOutputIS.insert(S).second)
347 return;
348 bool IsTbss =
349 (CurOutSec->getFlags() & SHF_TLS) && CurOutSec->getType() == SHT_NOBITS;
Eugene Leviant20889c52016-08-31 08:13:33 +0000350
Rafael Espindolad3190792016-09-16 15:10:23 +0000351 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
352 Pos = alignTo(Pos, S->Alignment);
353 S->OutSecOff = Pos - CurOutSec->getVA();
354 Pos += S->getSize();
355
356 // Update output section size after adding each section. This is so that
357 // SIZEOF works correctly in the case below:
358 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
359 CurOutSec->setSize(Pos - CurOutSec->getVA());
360
361 if (!IsTbss)
362 Dot = Pos;
363}
364
365template <class ELFT> void LinkerScript<ELFT>::flush() {
366 if (auto *OutSec = dyn_cast_or_null<OutputSection<ELFT>>(CurOutSec)) {
367 for (InputSection<ELFT> *I : OutSec->Sections)
368 output(I);
369 AlreadyOutputOS.insert(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000370 }
371}
372
373template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000374void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
375 if (CurOutSec == Sec)
376 return;
377 if (AlreadyOutputOS.count(Sec))
378 return;
379
380 flush();
381 CurOutSec = Sec;
382
383 Dot = alignTo(Dot, CurOutSec->getAlignment());
384 CurOutSec->setVA(Dot);
385}
386
387template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
388 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
389 if (AssignCmd->Name == ".") {
390 // Update to location counter means update to section size.
391 Dot = AssignCmd->Expression(Dot);
392 CurOutSec->setSize(Dot - CurOutSec->getVA());
393 return;
394 }
395 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000396 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000397 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000398 auto &ICmd = cast<InputSectionDescription>(Base);
399 for (InputSectionData *ID : ICmd.Sections) {
400 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
401 switchTo(IB->OutSec);
402 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
403 output(I);
404 else if (AlreadyOutputOS.insert(CurOutSec).second)
405 Dot += CurOutSec->getSize();
Eugene Leviantceabe802016-08-11 07:56:43 +0000406 }
407}
408
George Rimar8f66df92016-08-12 20:38:20 +0000409template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000410static std::vector<OutputSectionBase<ELFT> *>
411findSections(OutputSectionCommand &Cmd,
Rafael Espindolad3190792016-09-16 15:10:23 +0000412 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000413 std::vector<OutputSectionBase<ELFT> *> Ret;
414 for (OutputSectionBase<ELFT> *Sec : Sections)
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000415 if (Sec->getName() == Cmd.Name)
George Rimara14b13d2016-09-07 10:46:07 +0000416 Ret.push_back(Sec);
417 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000418}
419
Rafael Espindolad3190792016-09-16 15:10:23 +0000420template <class ELFT>
421void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
422 std::vector<OutputSectionBase<ELFT> *> Sections =
423 findSections(*Cmd, *OutputSections);
424 if (Sections.empty())
425 return;
426 switchTo(Sections[0]);
427
428 // Find the last section output location. We will output orphan sections
429 // there so that end symbols point to the correct location.
430 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
431 [](const std::unique_ptr<BaseCommand> &Cmd) {
432 return !isa<SymbolAssignment>(*Cmd);
433 })
434 .base();
435 for (auto I = Cmd->Commands.begin(); I != E; ++I)
436 process(**I);
437 flush();
438 for (OutputSectionBase<ELFT> *Base : Sections) {
439 if (!AlreadyOutputOS.insert(Base).second)
440 continue;
441 switchTo(Base);
442 Dot += CurOutSec->getSize();
443 }
George Rimarb31dd372016-09-19 13:27:31 +0000444 std::for_each(E, Cmd->Commands.end(),
445 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000446}
447
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000448template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000449 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000450 // are not explicitly placed into the output file by the linker script.
451 // We place orphan sections at end of file.
452 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000453 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000454
455 // The OutputSections are already in the correct order.
456 // This loops creates or moves commands as needed so that they are in the
457 // correct order.
458 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000459 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000460 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000461
462 // Find the last spot where we can insert a command and still get the
463 // correct order.
464 auto CmdIter = Opt.Commands.begin() + CmdIndex;
465 auto E = Opt.Commands.end();
466 while (CmdIter != E && !isa<OutputSectionCommand>(**CmdIter)) {
467 ++CmdIter;
468 ++CmdIndex;
469 }
470
471 auto Pos =
472 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
473 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
474 return Cmd && Cmd->Name == Name;
475 });
476 if (Pos == E) {
477 Opt.Commands.insert(CmdIter,
478 llvm::make_unique<OutputSectionCommand>(Name));
479 } else {
480 // If linker script lists alloc/non-alloc sections is the wrong order,
481 // this does a right rotate to bring the desired command in place.
Rafael Espindola373343b2016-09-16 22:47:34 +0000482 auto RPos = llvm::make_reverse_iterator(Pos + 1);
483 std::rotate(RPos, RPos + 1, llvm::make_reverse_iterator(CmdIter));
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000484 }
485 ++CmdIndex;
George Rimar652852c2016-04-16 10:10:32 +0000486 }
George Rimar652852c2016-04-16 10:10:32 +0000487
Rui Ueyama7c18c282016-04-18 21:00:40 +0000488 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000489 Dot = getHeaderSize();
George Rimar652852c2016-04-16 10:10:32 +0000490
George Rimar076fe152016-07-21 06:43:01 +0000491 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
492 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000493 if (Cmd->Name == ".") {
494 Dot = Cmd->Expression(Dot);
495 } else if (Cmd->Sym) {
496 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
497 }
George Rimar652852c2016-04-16 10:10:32 +0000498 continue;
499 }
500
George Rimareefa7582016-08-04 09:29:31 +0000501 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
502 Cmd->Expression(Dot);
503 continue;
504 }
505
George Rimar076fe152016-07-21 06:43:01 +0000506 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000507
Rafael Espindolad3190792016-09-16 15:10:23 +0000508 if (Cmd->AddrExpr)
509 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000510
Rafael Espindolad3190792016-09-16 15:10:23 +0000511 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000512 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000513
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000514 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
515 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
516 if (Sec->getFlags() & SHF_ALLOC)
517 MinVA = std::min(MinVA, Sec->getVA());
518 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000519 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000520 }
521
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000522 uintX_t HeaderSize =
523 Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
524 if (HeaderSize > MinVA)
525 fatal("Not enough space for ELF and program headers");
526
Rafael Espindola64c32d62016-07-07 14:28:47 +0000527 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000528 // memory. Set their addresses accordingly.
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000529 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Eugene Leviant467c4d52016-07-01 10:27:36 +0000530 Out<ELFT>::ElfHeader->setVA(MinVA);
531 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000532}
533
Rui Ueyama464daad2016-08-22 04:55:20 +0000534// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000535template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000536std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000537 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000538
Rui Ueyama464daad2016-08-22 04:55:20 +0000539 // Process PHDRS and FILEHDR keywords because they are not
540 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000541 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000542 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
543 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000544
545 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000546 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000547 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000548 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000549
550 if (Cmd.LMAExpr) {
551 Phdr.H.p_paddr = Cmd.LMAExpr(0);
552 Phdr.HasLMA = true;
553 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000554 }
555
Rui Ueyama464daad2016-08-22 04:55:20 +0000556 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000557 PhdrEntry<ELFT> *Load = nullptr;
558 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000559 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000560 if (!(Sec->getFlags() & SHF_ALLOC))
561 break;
562
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000563 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000564 if (!PhdrIds.empty()) {
565 // Assign headers specified by linker script
566 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000567 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000568 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000569 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000570 }
571 } else {
572 // If we have no load segment or flags've changed then we want new load
573 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000574 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000575 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000576 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000577 Flags = NewFlags;
578 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000579 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000580 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000581 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000582 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000583}
584
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000585template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
586 // Ignore .interp section in case we have PHDRS specification
587 // and PT_INTERP isn't listed.
588 return !Opt.PhdrsCommands.empty() &&
589 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
590 return Cmd.Type == PT_INTERP;
591 }) == Opt.PhdrsCommands.end();
592}
593
Eugene Leviantbbe38602016-07-19 09:25:43 +0000594template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000595ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000596 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
597 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
598 if (Cmd->Name == Name)
599 return Cmd->Filler;
600 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000601}
602
George Rimar206fffa2016-08-17 08:16:57 +0000603template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000604 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
605 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
606 if (Cmd->LmaExpr && Cmd->Name == Name)
607 return Cmd->LmaExpr;
608 return {};
609}
610
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000611// Returns the index of the given section name in linker script
612// SECTIONS commands. Sections are laid out as the same order as they
613// were in the script. If a given name did not appear in the script,
614// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000615template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000616 int I = 0;
617 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
618 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
619 if (Cmd->Name == Name)
620 return I;
621 ++I;
622 }
623 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000624}
625
626// A compartor to sort output sections. Returns -1 or 1 if
627// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000628template <class ELFT>
629int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000630 int I = getSectionIndex(A);
631 int J = getSectionIndex(B);
632 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000633 return 0;
634 return I < J ? -1 : 1;
635}
636
Eugene Leviantbbe38602016-07-19 09:25:43 +0000637template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
638 return !Opt.PhdrsCommands.empty();
639}
640
George Rimar9e694502016-07-29 16:18:47 +0000641template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000642uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000643 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
644 if (Sec->getName() == Name)
645 return Sec->getVA();
646 error("undefined section " + Name);
647 return 0;
648}
649
650template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000651uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000652 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
653 if (Sec->getName() == Name)
654 return Sec->getSize();
655 error("undefined section " + Name);
656 return 0;
657}
658
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000659template <class ELFT>
660uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
661 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
662 if (Sec->getName() == Name)
663 return Sec->getAlignment();
664 error("undefined section " + Name);
665 return 0;
666}
667
George Rimar884e7862016-09-08 08:19:13 +0000668template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000669 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
670}
671
George Rimar884e7862016-09-08 08:19:13 +0000672template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
673 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
674 return B->getVA<ELFT>();
675 error("symbol not found: " + S);
676 return 0;
677}
678
Eugene Leviantbbe38602016-07-19 09:25:43 +0000679// Returns indices of ELF headers containing specific section, identified
680// by Name. Each index is a zero based number of ELF header listed within
681// PHDRS {} script block.
682template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000683std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000684 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
685 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000686 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000687 continue;
688
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000689 std::vector<size_t> Ret;
690 for (StringRef PhdrName : Cmd->Phdrs)
691 Ret.push_back(getPhdrIndex(PhdrName));
692 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000693 }
George Rimar31d842f2016-07-20 16:43:03 +0000694 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000695}
696
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000697template <class ELFT>
698size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
699 size_t I = 0;
700 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
701 if (Cmd.Name == PhdrName)
702 return I;
703 ++I;
704 }
705 error("section header '" + PhdrName + "' is not listed in PHDRS");
706 return 0;
707}
708
Rui Ueyama07320e42016-04-20 20:13:41 +0000709class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000710 typedef void (ScriptParser::*Handler)();
711
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000712public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000713 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000714
George Rimar20b65982016-08-31 09:08:26 +0000715 void readLinkerScript();
716 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000717
718private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000719 void addFile(StringRef Path);
720
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000721 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000722 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000723 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000724 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000725 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000726 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000727 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000728 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000729 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000730 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000731 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000732 void readVersion();
733 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000734
Rui Ueyama113cdec2016-07-24 23:05:57 +0000735 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000736 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000737 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000738 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000739 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000740 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000741 Regex readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +0000742 void readSectionExcludes(InputSectionDescription *Cmd);
George Rimara2496cb2016-08-30 09:46:59 +0000743 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000744 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000745 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000746 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000747 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000748 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000749 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000750
751 Expr readExpr();
752 Expr readExpr1(Expr Lhs, int MinPrec);
753 Expr readPrimary();
754 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000755 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000756
George Rimar20b65982016-08-31 09:08:26 +0000757 // For parsing version script.
758 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000759 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000760 void readGlobal(StringRef VerStr);
761 void readLocal();
762
Rui Ueyama07320e42016-04-20 20:13:41 +0000763 ScriptConfiguration &Opt = *ScriptConfig;
764 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000765 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000766};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000767
George Rimar20b65982016-08-31 09:08:26 +0000768void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000769 readVersionScriptCommand();
770 if (!atEOF())
771 setError("EOF expected, but got " + next());
772}
773
774void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000775 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000776 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000777 return;
778 }
779
Rui Ueyama95769b42016-08-31 20:03:54 +0000780 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000781 StringRef VerStr = next();
782 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000783 setError("anonymous version definition is used in "
784 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000785 return;
786 }
787 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000788 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000789 }
790}
791
Rui Ueyama95769b42016-08-31 20:03:54 +0000792void ScriptParser::readVersion() {
793 expect("{");
794 readVersionScriptCommand();
795 expect("}");
796}
797
George Rimar20b65982016-08-31 09:08:26 +0000798void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000799 while (!atEOF()) {
800 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000801 if (Tok == ";")
802 continue;
803
Eugene Leviant20d03192016-09-16 15:30:47 +0000804 if (Tok == "ASSERT") {
805 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
806 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000807 readEntry();
808 } else if (Tok == "EXTERN") {
809 readExtern();
810 } else if (Tok == "GROUP" || Tok == "INPUT") {
811 readGroup();
812 } else if (Tok == "INCLUDE") {
813 readInclude();
814 } else if (Tok == "OUTPUT") {
815 readOutput();
816 } else if (Tok == "OUTPUT_ARCH") {
817 readOutputArch();
818 } else if (Tok == "OUTPUT_FORMAT") {
819 readOutputFormat();
820 } else if (Tok == "PHDRS") {
821 readPhdrs();
822 } else if (Tok == "SEARCH_DIR") {
823 readSearchDir();
824 } else if (Tok == "SECTIONS") {
825 readSections();
826 } else if (Tok == "VERSION") {
827 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000828 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000829 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000830 } else {
George Rimar57610422016-03-11 14:43:02 +0000831 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000832 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000833 }
834}
835
Rui Ueyama717677a2016-02-11 21:17:59 +0000836void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000837 if (IsUnderSysroot && S.startswith("/")) {
838 SmallString<128> Path;
839 (Config->Sysroot + S).toStringRef(Path);
840 if (sys::fs::exists(Path)) {
841 Driver->addFile(Saver.save(Path.str()));
842 return;
843 }
844 }
845
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000846 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000847 Driver->addFile(S);
848 } else if (S.startswith("=")) {
849 if (Config->Sysroot.empty())
850 Driver->addFile(S.substr(1));
851 else
852 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
853 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000854 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000855 } else if (sys::fs::exists(S)) {
856 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000857 } else {
858 std::string Path = findFromSearchPaths(S);
859 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000860 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000861 else
862 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000863 }
864}
865
Rui Ueyama717677a2016-02-11 21:17:59 +0000866void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000867 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000868 bool Orig = Config->AsNeeded;
869 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000870 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000871 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000872 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000873}
874
Rui Ueyama717677a2016-02-11 21:17:59 +0000875void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000876 // -e <symbol> takes predecence over ENTRY(<symbol>).
877 expect("(");
878 StringRef Tok = next();
879 if (Config->Entry.empty())
880 Config->Entry = Tok;
881 expect(")");
882}
883
Rui Ueyama717677a2016-02-11 21:17:59 +0000884void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000885 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000886 while (!Error && !skip(")"))
887 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000888}
889
Rui Ueyama717677a2016-02-11 21:17:59 +0000890void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000891 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000892 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000893 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000894 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000895 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000896 else
George Rimarcd574a52016-09-09 14:35:36 +0000897 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000898 }
899}
900
Rui Ueyama717677a2016-02-11 21:17:59 +0000901void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000902 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000903 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000904 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000905 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000906 return;
907 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000908 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000909 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
910 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000911 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000912}
913
Rui Ueyama717677a2016-02-11 21:17:59 +0000914void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000915 // -o <file> takes predecence over OUTPUT(<file>).
916 expect("(");
917 StringRef Tok = next();
918 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +0000919 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +0000920 expect(")");
921}
922
Rui Ueyama717677a2016-02-11 21:17:59 +0000923void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000924 // Error checking only for now.
925 expect("(");
926 next();
927 expect(")");
928}
929
Rui Ueyama717677a2016-02-11 21:17:59 +0000930void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000931 // Error checking only for now.
932 expect("(");
933 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000934 StringRef Tok = next();
935 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000936 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000937 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000938 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000939 return;
940 }
Davide Italiano6836c612015-10-12 21:08:41 +0000941 next();
942 expect(",");
943 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000944 expect(")");
945}
946
Eugene Leviantbbe38602016-07-19 09:25:43 +0000947void ScriptParser::readPhdrs() {
948 expect("{");
949 while (!Error && !skip("}")) {
950 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000951 Opt.PhdrsCommands.push_back(
952 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000953 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
954
955 PhdrCmd.Type = readPhdrType();
956 do {
957 Tok = next();
958 if (Tok == ";")
959 break;
960 if (Tok == "FILEHDR")
961 PhdrCmd.HasFilehdr = true;
962 else if (Tok == "PHDRS")
963 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000964 else if (Tok == "AT")
965 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +0000966 else if (Tok == "FLAGS") {
967 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000968 // Passing 0 for the value of dot is a bit of a hack. It means that
969 // we accept expressions like ".|1".
970 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000971 expect(")");
972 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000973 setError("unexpected header attribute: " + Tok);
974 } while (!Error);
975 }
976}
977
Rui Ueyama717677a2016-02-11 21:17:59 +0000978void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000979 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +0000980 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000981 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +0000982 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +0000983 expect(")");
984}
985
Rui Ueyama717677a2016-02-11 21:17:59 +0000986void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +0000987 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000988 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000989 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000990 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000991 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000992 if (!Cmd) {
993 if (Tok == "ASSERT")
994 Cmd = new AssertCommand(readAssert());
995 else
996 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000997 }
Rui Ueyama10416562016-08-04 02:03:27 +0000998 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000999 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001000}
1001
Rui Ueyama708019c2016-07-24 18:19:40 +00001002static int precedence(StringRef Op) {
1003 return StringSwitch<int>(Op)
1004 .Case("*", 4)
1005 .Case("/", 4)
1006 .Case("+", 3)
1007 .Case("-", 3)
1008 .Case("<", 2)
1009 .Case(">", 2)
1010 .Case(">=", 2)
1011 .Case("<=", 2)
1012 .Case("==", 2)
1013 .Case("!=", 2)
1014 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001015 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001016 .Default(-1);
1017}
1018
George Rimarc91930a2016-09-02 21:17:20 +00001019Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001020 std::vector<StringRef> V;
1021 while (!Error && !skip(")"))
1022 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001023 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001024}
1025
George Rimarbe394db2016-09-16 20:21:55 +00001026SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama742c3832016-08-04 22:27:00 +00001027 if (skip("SORT") || skip("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001028 return SortSectionPolicy::Name;
Rui Ueyama742c3832016-08-04 22:27:00 +00001029 if (skip("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001030 return SortSectionPolicy::Alignment;
George Rimar575208c2016-09-15 19:15:12 +00001031 if (skip("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001032 return SortSectionPolicy::Priority;
George Rimarbe394db2016-09-16 20:21:55 +00001033 if (skip("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001034 return SortSectionPolicy::None;
1035 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001036}
1037
1038static void selectSortKind(InputSectionDescription *Cmd) {
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001039 if (Cmd->SortOuter == SortSectionPolicy::None) {
1040 Cmd->SortOuter = SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001041 return;
1042 }
1043
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001044 if (Cmd->SortOuter != SortSectionPolicy::Default) {
George Rimarbe394db2016-09-16 20:21:55 +00001045 // If the section sorting command in linker script is nested, the command
1046 // line option will be ignored.
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001047 if (Cmd->SortInner != SortSectionPolicy::Default)
George Rimarbe394db2016-09-16 20:21:55 +00001048 return;
1049 // If the section sorting command in linker script isn't nested, the
1050 // command line option will make the section sorting command to be treated
1051 // as nested sorting command.
1052 Cmd->SortInner = Config->SortSection;
1053 return;
1054 }
1055 // If sorting rule not specified, use command line option.
1056 Cmd->SortOuter = Config->SortSection;
Rui Ueyama742c3832016-08-04 22:27:00 +00001057}
1058
George Rimar395281c2016-09-16 17:42:10 +00001059// Method reads a list of sequence of excluded files and section globs given in
1060// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1061// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001062// The semantics of that is next:
1063// * Include .foo.1 from every file.
1064// * Include .foo.2 from every file but a.o
1065// * Include .foo.3 from every file but b.o
George Rimar395281c2016-09-16 17:42:10 +00001066void ScriptParser::readSectionExcludes(InputSectionDescription *Cmd) {
Rui Ueyama027a9e82016-09-17 02:10:15 +00001067 Regex ExcludeFileRe;
George Rimar395281c2016-09-16 17:42:10 +00001068 std::vector<StringRef> V;
1069
1070 while (!Error) {
1071 if (skip(")")) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001072 Cmd->SectionPatterns.push_back(
George Rimar395281c2016-09-16 17:42:10 +00001073 {std::move(ExcludeFileRe), compileGlobPatterns(V)});
1074 return;
1075 }
1076
1077 if (skip("EXCLUDE_FILE")) {
1078 if (!V.empty()) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001079 Cmd->SectionPatterns.push_back(
George Rimar395281c2016-09-16 17:42:10 +00001080 {std::move(ExcludeFileRe), compileGlobPatterns(V)});
1081 V.clear();
1082 }
1083
1084 expect("(");
1085 ExcludeFileRe = readFilePatterns();
1086 continue;
1087 }
1088
1089 V.push_back(next());
1090 }
1091}
1092
George Rimara2496cb2016-08-30 09:46:59 +00001093InputSectionDescription *
1094ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001095 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001096 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +00001097
Rui Ueyama742c3832016-08-04 22:27:00 +00001098 // Read SORT().
George Rimarbe394db2016-09-16 20:21:55 +00001099 SortSectionPolicy K1 = readSortKind();
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001100 if (K1 != SortSectionPolicy::Default) {
Rui Ueyama742c3832016-08-04 22:27:00 +00001101 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +00001102 expect("(");
George Rimarbe394db2016-09-16 20:21:55 +00001103 SortSectionPolicy K2 = readSortKind();
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001104 if (K2 != SortSectionPolicy::Default) {
Rui Ueyama742c3832016-08-04 22:27:00 +00001105 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +00001106 expect("(");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001107 Cmd->SectionPatterns.push_back({Regex(), readFilePatterns()});
George Rimar350ece42016-08-03 08:35:59 +00001108 expect(")");
1109 } else {
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001110 Cmd->SectionPatterns.push_back({Regex(), readFilePatterns()});
George Rimar350ece42016-08-03 08:35:59 +00001111 }
George Rimar0702c4e2016-07-29 15:32:46 +00001112 expect(")");
George Rimarbe394db2016-09-16 20:21:55 +00001113 selectSortKind(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001114 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001115 }
George Rimar0702c4e2016-07-29 15:32:46 +00001116
George Rimarbe394db2016-09-16 20:21:55 +00001117 selectSortKind(Cmd);
George Rimar395281c2016-09-16 17:42:10 +00001118 readSectionExcludes(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001119 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001120}
1121
George Rimara2496cb2016-08-30 09:46:59 +00001122InputSectionDescription *
1123ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001124 // Input section wildcard can be surrounded by KEEP.
1125 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001126 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001127 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001128 StringRef FilePattern = next();
1129 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001130 expect(")");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001131 for (SectionPattern &Pat : Cmd->SectionPatterns)
1132 Opt.KeptSections.push_back(&Pat.SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +00001133 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001134 }
George Rimara2496cb2016-08-30 09:46:59 +00001135 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001136}
1137
George Rimar03fc0102016-07-28 07:18:23 +00001138void ScriptParser::readSort() {
1139 expect("(");
1140 expect("CONSTRUCTORS");
1141 expect(")");
1142}
1143
George Rimareefa7582016-08-04 09:29:31 +00001144Expr ScriptParser::readAssert() {
1145 expect("(");
1146 Expr E = readExpr();
1147 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001148 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001149 expect(")");
1150 return [=](uint64_t Dot) {
1151 uint64_t V = E(Dot);
1152 if (!V)
1153 error(Msg);
1154 return V;
1155 };
1156}
1157
Rui Ueyama25150e82016-09-06 17:46:43 +00001158// Reads a FILL(expr) command. We handle the FILL command as an
1159// alias for =fillexp section attribute, which is different from
1160// what GNU linkers do.
1161// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001162std::vector<uint8_t> ScriptParser::readFill() {
1163 expect("(");
1164 std::vector<uint8_t> V = readOutputSectionFiller(next());
1165 expect(")");
1166 expect(";");
1167 return V;
1168}
1169
Rui Ueyama10416562016-08-04 02:03:27 +00001170OutputSectionCommand *
1171ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001172 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001173
1174 // Read an address expression.
1175 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1176 if (peek() != ":")
1177 Cmd->AddrExpr = readExpr();
1178
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001179 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001180
George Rimar8ceadb32016-08-17 07:44:19 +00001181 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001182 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001183 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001184 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001185 if (skip("SUBALIGN"))
1186 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001187
Davide Italiano246f6812016-07-22 03:36:24 +00001188 // Parse constraints.
1189 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001190 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001191 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001192 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001193 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001194
Rui Ueyama025d59b2016-02-02 20:27:59 +00001195 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001196 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001197 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001198 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001199 else if (Tok == "FILL")
1200 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001201 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001202 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001203 else if (peek() == "(")
1204 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001205 else
1206 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001207 }
George Rimar076fe152016-07-21 06:43:01 +00001208 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001209 if (peek().startswith("="))
1210 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001211 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001212}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001213
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001214// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1215// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1216//
1217// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1218// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1219// as 32-bit big-endian values. We will do the same as ld.gold does
1220// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001221std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001222 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001223 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001224 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001225 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001226 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001227 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001228}
1229
Petr Hoseka35e39c2016-08-16 01:11:16 +00001230SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001231 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001232 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001233 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001234 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001235 expect(")");
1236 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001237 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001238}
1239
Eugene Leviantdb741e72016-09-07 07:08:43 +00001240SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1241 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001242 SymbolAssignment *Cmd = nullptr;
1243 if (peek() == "=" || peek() == "+=") {
1244 Cmd = readAssignment(Tok);
1245 expect(";");
1246 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001247 Cmd = readProvideHidden(true, false);
1248 } else if (Tok == "HIDDEN") {
1249 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001250 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001251 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001252 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001253 if (Cmd && MakeAbsolute)
1254 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001255 return Cmd;
1256}
1257
George Rimar30835ea2016-07-28 21:08:56 +00001258static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1259 if (S == ".")
1260 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001261 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001262}
1263
George Rimar30835ea2016-07-28 21:08:56 +00001264SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1265 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001266 bool IsAbsolute = false;
1267 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001268 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001269 if (skip("ABSOLUTE")) {
1270 E = readParenExpr();
1271 IsAbsolute = true;
1272 } else {
1273 E = readExpr();
1274 }
George Rimar30835ea2016-07-28 21:08:56 +00001275 if (Op == "+=")
1276 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001277 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001278}
1279
1280// This is an operator-precedence parser to parse a linker
1281// script expression.
1282Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1283
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001284static Expr combine(StringRef Op, Expr L, Expr R) {
1285 if (Op == "*")
1286 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1287 if (Op == "/") {
1288 return [=](uint64_t Dot) -> uint64_t {
1289 uint64_t RHS = R(Dot);
1290 if (RHS == 0) {
1291 error("division by zero");
1292 return 0;
1293 }
1294 return L(Dot) / RHS;
1295 };
1296 }
1297 if (Op == "+")
1298 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1299 if (Op == "-")
1300 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1301 if (Op == "<")
1302 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1303 if (Op == ">")
1304 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1305 if (Op == ">=")
1306 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1307 if (Op == "<=")
1308 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1309 if (Op == "==")
1310 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1311 if (Op == "!=")
1312 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1313 if (Op == "&")
1314 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001315 if (Op == "|")
1316 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001317 llvm_unreachable("invalid operator");
1318}
1319
Rui Ueyama708019c2016-07-24 18:19:40 +00001320// This is a part of the operator-precedence parser. This function
1321// assumes that the remaining token stream starts with an operator.
1322Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1323 while (!atEOF() && !Error) {
1324 // Read an operator and an expression.
1325 StringRef Op1 = peek();
1326 if (Op1 == "?")
1327 return readTernary(Lhs);
1328 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001329 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001330 next();
1331 Expr Rhs = readPrimary();
1332
1333 // Evaluate the remaining part of the expression first if the
1334 // next operator has greater precedence than the previous one.
1335 // For example, if we have read "+" and "3", and if the next
1336 // operator is "*", then we'll evaluate 3 * ... part first.
1337 while (!atEOF()) {
1338 StringRef Op2 = peek();
1339 if (precedence(Op2) <= precedence(Op1))
1340 break;
1341 Rhs = readExpr1(Rhs, precedence(Op2));
1342 }
1343
1344 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001345 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001346 return Lhs;
1347}
1348
1349uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001350 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001351 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001352 if (S == "MAXPAGESIZE")
1353 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001354 error("unknown constant: " + S);
1355 return 0;
1356}
1357
Rui Ueyama626e0b02016-09-02 18:19:00 +00001358// Parses Tok as an integer. Returns true if successful.
1359// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1360// and decimal numbers. Decimal numbers may have "K" (kilo) or
1361// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001362static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001363 if (Tok.startswith("-")) {
1364 if (!readInteger(Tok.substr(1), Result))
1365 return false;
1366 Result = -Result;
1367 return true;
1368 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001369 if (Tok.startswith_lower("0x"))
1370 return !Tok.substr(2).getAsInteger(16, Result);
1371 if (Tok.endswith_lower("H"))
1372 return !Tok.drop_back().getAsInteger(16, Result);
1373
1374 int Suffix = 1;
1375 if (Tok.endswith_lower("K")) {
1376 Suffix = 1024;
1377 Tok = Tok.drop_back();
1378 } else if (Tok.endswith_lower("M")) {
1379 Suffix = 1024 * 1024;
1380 Tok = Tok.drop_back();
1381 }
1382 if (Tok.getAsInteger(10, Result))
1383 return false;
1384 Result *= Suffix;
1385 return true;
1386}
1387
Rui Ueyama708019c2016-07-24 18:19:40 +00001388Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001389 if (peek() == "(")
1390 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001391
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001392 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001393
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001394 if (Tok == "~") {
1395 Expr E = readPrimary();
1396 return [=](uint64_t Dot) { return ~E(Dot); };
1397 }
1398 if (Tok == "-") {
1399 Expr E = readPrimary();
1400 return [=](uint64_t Dot) { return -E(Dot); };
1401 }
1402
Rui Ueyama708019c2016-07-24 18:19:40 +00001403 // Built-in functions are parsed here.
1404 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001405 if (Tok == "ADDR") {
1406 expect("(");
1407 StringRef Name = next();
1408 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001409 return
1410 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001411 }
George Rimareefa7582016-08-04 09:29:31 +00001412 if (Tok == "ASSERT")
1413 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001414 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001415 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001416 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1417 }
1418 if (Tok == "CONSTANT") {
1419 expect("(");
1420 StringRef Tok = next();
1421 expect(")");
1422 return [=](uint64_t Dot) { return getConstant(Tok); };
1423 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001424 if (Tok == "SEGMENT_START") {
1425 expect("(");
1426 next();
1427 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001428 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001429 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001430 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001431 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001432 if (Tok == "DATA_SEGMENT_ALIGN") {
1433 expect("(");
1434 Expr E = readExpr();
1435 expect(",");
1436 readExpr();
1437 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001438 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001439 }
1440 if (Tok == "DATA_SEGMENT_END") {
1441 expect("(");
1442 expect(".");
1443 expect(")");
1444 return [](uint64_t Dot) { return Dot; };
1445 }
George Rimar276b4e62016-07-26 17:58:44 +00001446 // GNU linkers implements more complicated logic to handle
1447 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1448 // the next page boundary for simplicity.
1449 if (Tok == "DATA_SEGMENT_RELRO_END") {
1450 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001451 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001452 expect(",");
1453 readExpr();
1454 expect(")");
1455 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1456 }
George Rimar9e694502016-07-29 16:18:47 +00001457 if (Tok == "SIZEOF") {
1458 expect("(");
1459 StringRef Name = next();
1460 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001461 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001462 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001463 if (Tok == "ALIGNOF") {
1464 expect("(");
1465 StringRef Name = next();
1466 expect(")");
1467 return
1468 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1469 }
George Rimare32a3592016-08-10 07:59:34 +00001470 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001471 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001472
George Rimar9f2f7ad2016-09-02 16:01:42 +00001473 // Tok is a literal number.
1474 uint64_t V;
1475 if (readInteger(Tok, V))
1476 return [=](uint64_t Dot) { return V; };
1477
1478 // Tok is a symbol name.
1479 if (Tok != "." && !isValidCIdentifier(Tok))
1480 setError("malformed number: " + Tok);
1481 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001482}
1483
1484Expr ScriptParser::readTernary(Expr Cond) {
1485 next();
1486 Expr L = readExpr();
1487 expect(":");
1488 Expr R = readExpr();
1489 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1490}
1491
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001492Expr ScriptParser::readParenExpr() {
1493 expect("(");
1494 Expr E = readExpr();
1495 expect(")");
1496 return E;
1497}
1498
Eugene Leviantbbe38602016-07-19 09:25:43 +00001499std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1500 std::vector<StringRef> Phdrs;
1501 while (!Error && peek().startswith(":")) {
1502 StringRef Tok = next();
1503 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1504 if (Tok.empty()) {
1505 setError("section header name is empty");
1506 break;
1507 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001508 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001509 }
1510 return Phdrs;
1511}
1512
1513unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001514 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001515 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001516 .Case("PT_NULL", PT_NULL)
1517 .Case("PT_LOAD", PT_LOAD)
1518 .Case("PT_DYNAMIC", PT_DYNAMIC)
1519 .Case("PT_INTERP", PT_INTERP)
1520 .Case("PT_NOTE", PT_NOTE)
1521 .Case("PT_SHLIB", PT_SHLIB)
1522 .Case("PT_PHDR", PT_PHDR)
1523 .Case("PT_TLS", PT_TLS)
1524 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1525 .Case("PT_GNU_STACK", PT_GNU_STACK)
1526 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1527 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001528
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001529 if (Ret == (unsigned)-1) {
1530 setError("invalid program header type: " + Tok);
1531 return PT_NULL;
1532 }
1533 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001534}
1535
Rui Ueyama95769b42016-08-31 20:03:54 +00001536void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001537 // Identifiers start at 2 because 0 and 1 are reserved
1538 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1539 size_t VersionId = Config->VersionDefinitions.size() + 2;
1540 Config->VersionDefinitions.push_back({VerStr, VersionId});
1541
1542 if (skip("global:") || peek() != "local:")
1543 readGlobal(VerStr);
1544 if (skip("local:"))
1545 readLocal();
1546 expect("}");
1547
1548 // Each version may have a parent version. For example, "Ver2" defined as
1549 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1550 // version hierarchy is, probably against your instinct, purely for human; the
1551 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1552 if (!VerStr.empty() && peek() != ";")
1553 next();
1554 expect(";");
1555}
1556
1557void ScriptParser::readLocal() {
1558 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1559 expect("*");
1560 expect(";");
1561}
1562
1563void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001564 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001565 expect("{");
1566
1567 for (;;) {
1568 if (peek() == "}" || Error)
1569 break;
George Rimarcd574a52016-09-09 14:35:36 +00001570 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1571 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001572 expect(";");
1573 }
1574
1575 expect("}");
1576 expect(";");
1577}
1578
1579void ScriptParser::readGlobal(StringRef VerStr) {
1580 std::vector<SymbolVersion> *Globals;
1581 if (VerStr.empty())
1582 Globals = &Config->VersionScriptGlobals;
1583 else
1584 Globals = &Config->VersionDefinitions.back().Globals;
1585
1586 for (;;) {
1587 if (skip("extern"))
1588 readExtern(Globals);
1589
1590 StringRef Cur = peek();
1591 if (Cur == "}" || Cur == "local:" || Error)
1592 return;
1593 next();
George Rimarcd574a52016-09-09 14:35:36 +00001594 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001595 expect(";");
1596 }
1597}
1598
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001599static bool isUnderSysroot(StringRef Path) {
1600 if (Config->Sysroot == "")
1601 return false;
1602 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1603 if (sys::fs::equivalent(Config->Sysroot, Path))
1604 return true;
1605 return false;
1606}
1607
Rui Ueyama07320e42016-04-20 20:13:41 +00001608void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001609 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001610 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1611}
1612
1613void elf::readVersionScript(MemoryBufferRef MB) {
1614 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001615}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001616
Rui Ueyama07320e42016-04-20 20:13:41 +00001617template class elf::LinkerScript<ELF32LE>;
1618template class elf::LinkerScript<ELF32BE>;
1619template class elf::LinkerScript<ELF64LE>;
1620template class elf::LinkerScript<ELF64BE>;