blob: d6f406e5c287a55e642f595cdb05c2ddbd96451f [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
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000112// We need to use const_cast because match() is not a const function.
113// This function encapsulates that ugliness.
114static bool match(const Regex &Re, StringRef S) {
115 return const_cast<Regex &>(Re).match(S);
George Rimar06598002016-07-28 21:51:30 +0000116}
117
George Rimar575208c2016-09-15 19:15:12 +0000118static bool comparePriority(InputSectionData *A, InputSectionData *B) {
119 return getPriority(A->Name) < getPriority(B->Name);
120}
121
Rafael Espindolac0028d32016-09-08 20:47:52 +0000122static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000123 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000124}
George Rimar350ece42016-08-03 08:35:59 +0000125
Rafael Espindolac0028d32016-09-08 20:47:52 +0000126static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000127 // ">" is not a mistake. Larger alignments are placed before smaller
128 // alignments in order to reduce the amount of padding necessary.
129 // This is compatible with GNU.
130 return A->Alignment > B->Alignment;
131}
George Rimar350ece42016-08-03 08:35:59 +0000132
Rafael Espindolac0028d32016-09-08 20:47:52 +0000133static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000134getComparator(SortSectionPolicy K) {
135 switch (K) {
136 case SortSectionPolicy::Alignment:
137 return compareAlignment;
138 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000139 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000140 case SortSectionPolicy::Priority:
141 return comparePriority;
142 default:
143 llvm_unreachable("unknown sort policy");
144 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000145}
George Rimar0702c4e2016-07-29 15:32:46 +0000146
George Rimar8f66df92016-08-12 20:38:20 +0000147static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
148 bool RO = (Kind == ConstraintKind::ReadOnly);
149 bool RW = (Kind == ConstraintKind::ReadWrite);
150 bool Writable = Flags & SHF_WRITE;
Rui Ueyamaadcdb662016-09-06 22:50:48 +0000151 return !(RO && Writable) && !(RW && !Writable);
George Rimar8f66df92016-08-12 20:38:20 +0000152}
153
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000154template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000155static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000156 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000157 if (Kind == ConstraintKind::NoConstraint)
158 return true;
Rafael Espindolad3190792016-09-16 15:10:23 +0000159 return llvm::all_of(Sections, [=](InputSectionData *Sec2) {
160 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
George Rimar8f66df92016-08-12 20:38:20 +0000161 return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
George Rimar06ae6832016-08-12 09:07:57 +0000162 });
163}
164
Rafael Espindolad3190792016-09-16 15:10:23 +0000165// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000166template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000167void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000168 // Collects all sections that satisfy constraints of I
169 // and attach them to I.
170 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar395281c2016-09-16 17:42:10 +0000171 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000172 StringRef Filename = sys::path::filename(F->getName());
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000173 if (!match(I->FileRe, Filename) || match(Pat.ExcludedFileRe, Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000174 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000175
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000176 for (InputSectionBase<ELFT> *S : F->getSections())
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000177 if (!isDiscarded(S) && !S->OutSec && match(Pat.SectionRe, S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000178 I->Sections.push_back(S);
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000179 if (match(Pat.SectionRe, "COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000180 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000181 }
182 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000183
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000184 // Sort for SORT() commands.
Rui Ueyamab2a0abd2016-09-16 21:14:55 +0000185 if (I->SortInner != SortSectionPolicy::Default)
Rafael Espindolad3190792016-09-16 15:10:23 +0000186 std::stable_sort(I->Sections.begin(), I->Sections.end(),
187 getComparator(I->SortInner));
Rui Ueyamab2a0abd2016-09-16 21:14:55 +0000188 if (I->SortOuter != SortSectionPolicy::Default)
Rafael Espindolad3190792016-09-16 15:10:23 +0000189 std::stable_sort(I->Sections.begin(), I->Sections.end(),
190 getComparator(I->SortOuter));
191
192 // We do not add duplicate input sections, so mark them with a dummy output
193 // section for now.
194 for (InputSectionData *S : I->Sections) {
195 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
196 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
197 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000198}
199
200template <class ELFT>
201void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
202 for (InputSectionBase<ELFT> *S : V) {
203 S->Live = false;
204 reportDiscarded(S);
205 }
206}
207
George Rimar06ae6832016-08-12 09:07:57 +0000208template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000209std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000210LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000211 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000212
George Rimar06ae6832016-08-12 09:07:57 +0000213 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000214 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
215 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000216 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000217 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000218 for (InputSectionData *S : Cmd->Sections)
219 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000220 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000221
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000222 return Ret;
223}
224
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000225template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000226static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
227 StringRef OutsecName) {
228 // When using linker script the merge rules are different.
229 // Unfortunately, linker scripts are name based. This means that expressions
230 // like *(.foo*) can refer to multiple input sections that would normally be
231 // placed in different output sections. We cannot put them in different
232 // output sections or we would produce wrong results for
233 // start = .; *(.foo.*) end = .; *(.bar)
234 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
235 // another. The problem is that there is no way to layout those output
236 // sections such that the .foo sections are the only thing between the
237 // start and end symbols.
238
239 // An extra annoyance is that we cannot simply disable merging of the contents
240 // of SHF_MERGE sections, but our implementation requires one output section
241 // per "kind" (string or not, which size/aligment).
242 // Fortunately, creating symbols in the middle of a merge section is not
243 // supported by bfd or gold, so we can just create multiple section in that
244 // case.
245 const typename ELFT::Shdr *H = C->getSectionHdr();
246 typedef typename ELFT::uint uintX_t;
247 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
248
249 uintX_t Alignment = 0;
250 if (isa<MergeInputSection<ELFT>>(C))
251 Alignment = std::max(H->sh_addralign, H->sh_entsize);
252
253 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
254}
255
256template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000257void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
258 InputSectionBase<ELFT> *Sec,
259 StringRef Name) {
260 OutputSectionBase<ELFT> *OutSec;
261 bool IsNew;
262 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
263 if (IsNew)
264 OutputSections->push_back(OutSec);
265 OutSec->addSection(Sec);
266}
267
268template <class ELFT>
269void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000270
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000271 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
272 auto Iter = Opt.Commands.begin() + I;
273 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000274 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
275 if (shouldDefine<ELFT>(Cmd))
276 addRegular<ELFT>(Cmd);
277 continue;
278 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000279 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
280 // If we don't have SECTIONS then output sections have already been
281 // created by Writer<EFLT>. The LinkerScript<ELFT>::assignAddresses
282 // will not be called, so ASSERT should be evaluated now.
283 if (!Opt.HasSections)
284 Cmd->Expression(0);
285 continue;
286 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000287
Eugene Leviantceabe802016-08-11 07:56:43 +0000288 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000289 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
290
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000291 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000292 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000293 continue;
294 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000295
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000296 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
297 for (InputSectionBase<ELFT> *S : V)
298 S->OutSec = nullptr;
299 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000300 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000301 continue;
302 }
303
304 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
305 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
306 if (shouldDefine<ELFT>(OutCmd))
307 addSymbol<ELFT>(OutCmd);
308
Eugene Leviant97403d12016-09-01 09:55:57 +0000309 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000310 continue;
311
George Rimardb24d9c2016-08-19 15:18:23 +0000312 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000313 addSection(Factory, Sec, Cmd->Name);
314 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000315 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000316 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000317 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000318 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000319}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000320
Eugene Leviant20d03192016-09-16 15:30:47 +0000321template <class ELFT>
322void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
323 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000324 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000325 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
326 for (InputSectionBase<ELFT> *S : F->getSections())
327 if (!isDiscarded(S) && !S->OutSec)
328 addSection(Factory, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000329}
330
Eugene Leviantdb741e72016-09-07 07:08:43 +0000331// Sets value of a section-defined symbol. Two kinds of
332// symbols are processed: synthetic symbols, whose value
333// is an offset from beginning of section and regular
334// symbols whose value is absolute.
335template <class ELFT>
336static void assignSectionSymbol(SymbolAssignment *Cmd,
337 OutputSectionBase<ELFT> *Sec,
338 typename ELFT::uint Off) {
339 if (!Cmd->Sym)
340 return;
341
342 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
343 Body->Section = Sec;
344 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
345 return;
346 }
347 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
348 Body->Value = Cmd->Expression(Sec->getVA() + Off);
349}
350
Rafael Espindolad3190792016-09-16 15:10:23 +0000351template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
352 if (!AlreadyOutputIS.insert(S).second)
353 return;
354 bool IsTbss =
355 (CurOutSec->getFlags() & SHF_TLS) && CurOutSec->getType() == SHT_NOBITS;
Eugene Leviant20889c52016-08-31 08:13:33 +0000356
Rafael Espindolad3190792016-09-16 15:10:23 +0000357 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
358 Pos = alignTo(Pos, S->Alignment);
359 S->OutSecOff = Pos - CurOutSec->getVA();
360 Pos += S->getSize();
361
362 // Update output section size after adding each section. This is so that
363 // SIZEOF works correctly in the case below:
364 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
365 CurOutSec->setSize(Pos - CurOutSec->getVA());
366
367 if (!IsTbss)
368 Dot = Pos;
369}
370
371template <class ELFT> void LinkerScript<ELFT>::flush() {
372 if (auto *OutSec = dyn_cast_or_null<OutputSection<ELFT>>(CurOutSec)) {
373 for (InputSection<ELFT> *I : OutSec->Sections)
374 output(I);
375 AlreadyOutputOS.insert(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000376 }
377}
378
379template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000380void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
381 if (CurOutSec == Sec)
382 return;
383 if (AlreadyOutputOS.count(Sec))
384 return;
385
386 flush();
387 CurOutSec = Sec;
388
389 Dot = alignTo(Dot, CurOutSec->getAlignment());
390 CurOutSec->setVA(Dot);
391}
392
393template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
394 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
395 if (AssignCmd->Name == ".") {
396 // Update to location counter means update to section size.
397 Dot = AssignCmd->Expression(Dot);
398 CurOutSec->setSize(Dot - CurOutSec->getVA());
399 return;
400 }
401 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000402 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000403 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000404 auto &ICmd = cast<InputSectionDescription>(Base);
405 for (InputSectionData *ID : ICmd.Sections) {
406 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
407 switchTo(IB->OutSec);
408 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
409 output(I);
410 else if (AlreadyOutputOS.insert(CurOutSec).second)
411 Dot += CurOutSec->getSize();
Eugene Leviantceabe802016-08-11 07:56:43 +0000412 }
413}
414
George Rimar8f66df92016-08-12 20:38:20 +0000415template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000416static std::vector<OutputSectionBase<ELFT> *>
417findSections(OutputSectionCommand &Cmd,
Rafael Espindolad3190792016-09-16 15:10:23 +0000418 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000419 std::vector<OutputSectionBase<ELFT> *> Ret;
420 for (OutputSectionBase<ELFT> *Sec : Sections)
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000421 if (Sec->getName() == Cmd.Name)
George Rimara14b13d2016-09-07 10:46:07 +0000422 Ret.push_back(Sec);
423 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000424}
425
Rafael Espindolad3190792016-09-16 15:10:23 +0000426template <class ELFT>
427void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
428 std::vector<OutputSectionBase<ELFT> *> Sections =
429 findSections(*Cmd, *OutputSections);
430 if (Sections.empty())
431 return;
432 switchTo(Sections[0]);
433
434 // Find the last section output location. We will output orphan sections
435 // there so that end symbols point to the correct location.
436 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
437 [](const std::unique_ptr<BaseCommand> &Cmd) {
438 return !isa<SymbolAssignment>(*Cmd);
439 })
440 .base();
441 for (auto I = Cmd->Commands.begin(); I != E; ++I)
442 process(**I);
443 flush();
444 for (OutputSectionBase<ELFT> *Base : Sections) {
445 if (!AlreadyOutputOS.insert(Base).second)
446 continue;
447 switchTo(Base);
448 Dot += CurOutSec->getSize();
449 }
450 for (auto I = E, E = Cmd->Commands.end(); I != E; ++I)
451 process(**I);
452}
453
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000454template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000455 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000456 // are not explicitly placed into the output file by the linker script.
457 // We place orphan sections at end of file.
458 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000459 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000460
461 // The OutputSections are already in the correct order.
462 // This loops creates or moves commands as needed so that they are in the
463 // correct order.
464 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000465 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000466 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000467
468 // Find the last spot where we can insert a command and still get the
469 // correct order.
470 auto CmdIter = Opt.Commands.begin() + CmdIndex;
471 auto E = Opt.Commands.end();
472 while (CmdIter != E && !isa<OutputSectionCommand>(**CmdIter)) {
473 ++CmdIter;
474 ++CmdIndex;
475 }
476
477 auto Pos =
478 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
479 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
480 return Cmd && Cmd->Name == Name;
481 });
482 if (Pos == E) {
483 Opt.Commands.insert(CmdIter,
484 llvm::make_unique<OutputSectionCommand>(Name));
485 } else {
486 // If linker script lists alloc/non-alloc sections is the wrong order,
487 // this does a right rotate to bring the desired command in place.
Rafael Espindola373343b2016-09-16 22:47:34 +0000488 auto RPos = llvm::make_reverse_iterator(Pos + 1);
489 std::rotate(RPos, RPos + 1, llvm::make_reverse_iterator(CmdIter));
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000490 }
491 ++CmdIndex;
George Rimar652852c2016-04-16 10:10:32 +0000492 }
George Rimar652852c2016-04-16 10:10:32 +0000493
Rui Ueyama7c18c282016-04-18 21:00:40 +0000494 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama4f7500b2016-08-12 04:00:22 +0000495 Dot = getHeaderSize();
George Rimar652852c2016-04-16 10:10:32 +0000496
George Rimar076fe152016-07-21 06:43:01 +0000497 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
498 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000499 if (Cmd->Name == ".") {
500 Dot = Cmd->Expression(Dot);
501 } else if (Cmd->Sym) {
502 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
503 }
George Rimar652852c2016-04-16 10:10:32 +0000504 continue;
505 }
506
George Rimareefa7582016-08-04 09:29:31 +0000507 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
508 Cmd->Expression(Dot);
509 continue;
510 }
511
George Rimar076fe152016-07-21 06:43:01 +0000512 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000513
Rafael Espindolad3190792016-09-16 15:10:23 +0000514 if (Cmd->AddrExpr)
515 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000516
Rafael Espindolad3190792016-09-16 15:10:23 +0000517 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000518 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000519
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000520 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
521 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
522 if (Sec->getFlags() & SHF_ALLOC)
523 MinVA = std::min(MinVA, Sec->getVA());
524 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000525 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000526 }
527
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000528 uintX_t HeaderSize =
529 Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
530 if (HeaderSize > MinVA)
531 fatal("Not enough space for ELF and program headers");
532
Rafael Espindola64c32d62016-07-07 14:28:47 +0000533 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000534 // memory. Set their addresses accordingly.
Rafael Espindola4ec013a2016-09-15 21:22:11 +0000535 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Eugene Leviant467c4d52016-07-01 10:27:36 +0000536 Out<ELFT>::ElfHeader->setVA(MinVA);
537 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000538}
539
Rui Ueyama464daad2016-08-22 04:55:20 +0000540// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000541template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000542std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000543 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000544
Rui Ueyama464daad2016-08-22 04:55:20 +0000545 // Process PHDRS and FILEHDR keywords because they are not
546 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000547 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000548 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
549 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000550
551 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000552 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000553 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000554 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000555
556 if (Cmd.LMAExpr) {
557 Phdr.H.p_paddr = Cmd.LMAExpr(0);
558 Phdr.HasLMA = true;
559 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000560 }
561
Rui Ueyama464daad2016-08-22 04:55:20 +0000562 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000563 PhdrEntry<ELFT> *Load = nullptr;
564 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000565 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000566 if (!(Sec->getFlags() & SHF_ALLOC))
567 break;
568
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000569 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000570 if (!PhdrIds.empty()) {
571 // Assign headers specified by linker script
572 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000573 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000574 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000575 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000576 }
577 } else {
578 // If we have no load segment or flags've changed then we want new load
579 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000580 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000581 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000582 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000583 Flags = NewFlags;
584 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000585 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000586 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000587 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000588 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000589}
590
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000591template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
592 // Ignore .interp section in case we have PHDRS specification
593 // and PT_INTERP isn't listed.
594 return !Opt.PhdrsCommands.empty() &&
595 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
596 return Cmd.Type == PT_INTERP;
597 }) == Opt.PhdrsCommands.end();
598}
599
Eugene Leviantbbe38602016-07-19 09:25:43 +0000600template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000601ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000602 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
603 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
604 if (Cmd->Name == Name)
605 return Cmd->Filler;
606 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000607}
608
George Rimar206fffa2016-08-17 08:16:57 +0000609template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000610 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
611 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
612 if (Cmd->LmaExpr && Cmd->Name == Name)
613 return Cmd->LmaExpr;
614 return {};
615}
616
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000617// Returns the index of the given section name in linker script
618// SECTIONS commands. Sections are laid out as the same order as they
619// were in the script. If a given name did not appear in the script,
620// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000621template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000622 int I = 0;
623 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
624 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
625 if (Cmd->Name == Name)
626 return I;
627 ++I;
628 }
629 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000630}
631
632// A compartor to sort output sections. Returns -1 or 1 if
633// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000634template <class ELFT>
635int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000636 int I = getSectionIndex(A);
637 int J = getSectionIndex(B);
638 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000639 return 0;
640 return I < J ? -1 : 1;
641}
642
Eugene Leviantbbe38602016-07-19 09:25:43 +0000643template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
644 return !Opt.PhdrsCommands.empty();
645}
646
George Rimar9e694502016-07-29 16:18:47 +0000647template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000648uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000649 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
650 if (Sec->getName() == Name)
651 return Sec->getVA();
652 error("undefined section " + Name);
653 return 0;
654}
655
656template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000657uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000658 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
659 if (Sec->getName() == Name)
660 return Sec->getSize();
661 error("undefined section " + Name);
662 return 0;
663}
664
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000665template <class ELFT>
666uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
667 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
668 if (Sec->getName() == Name)
669 return Sec->getAlignment();
670 error("undefined section " + Name);
671 return 0;
672}
673
George Rimar884e7862016-09-08 08:19:13 +0000674template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
George Rimare32a3592016-08-10 07:59:34 +0000675 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
676}
677
George Rimar884e7862016-09-08 08:19:13 +0000678template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
679 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
680 return B->getVA<ELFT>();
681 error("symbol not found: " + S);
682 return 0;
683}
684
Eugene Leviantbbe38602016-07-19 09:25:43 +0000685// Returns indices of ELF headers containing specific section, identified
686// by Name. Each index is a zero based number of ELF header listed within
687// PHDRS {} script block.
688template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000689std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000690 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
691 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000692 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000693 continue;
694
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000695 std::vector<size_t> Ret;
696 for (StringRef PhdrName : Cmd->Phdrs)
697 Ret.push_back(getPhdrIndex(PhdrName));
698 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000699 }
George Rimar31d842f2016-07-20 16:43:03 +0000700 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000701}
702
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000703template <class ELFT>
704size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
705 size_t I = 0;
706 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
707 if (Cmd.Name == PhdrName)
708 return I;
709 ++I;
710 }
711 error("section header '" + PhdrName + "' is not listed in PHDRS");
712 return 0;
713}
714
Rui Ueyama07320e42016-04-20 20:13:41 +0000715class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000716 typedef void (ScriptParser::*Handler)();
717
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000718public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000719 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000720
George Rimar20b65982016-08-31 09:08:26 +0000721 void readLinkerScript();
722 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000723
724private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000725 void addFile(StringRef Path);
726
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000727 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000728 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000729 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000730 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000731 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000732 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000733 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000734 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000735 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000736 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000737 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000738 void readVersion();
739 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000740
Rui Ueyama113cdec2016-07-24 23:05:57 +0000741 SymbolAssignment *readAssignment(StringRef Name);
George Rimarff1f29e2016-09-06 13:51:57 +0000742 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000743 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000744 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000745 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000746 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000747 Regex readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +0000748 void readSectionExcludes(InputSectionDescription *Cmd);
George Rimara2496cb2016-08-30 09:46:59 +0000749 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000750 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000751 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000752 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000753 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000754 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000755 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000756
757 Expr readExpr();
758 Expr readExpr1(Expr Lhs, int MinPrec);
759 Expr readPrimary();
760 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000761 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000762
George Rimar20b65982016-08-31 09:08:26 +0000763 // For parsing version script.
764 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000765 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000766 void readGlobal(StringRef VerStr);
767 void readLocal();
768
Rui Ueyama07320e42016-04-20 20:13:41 +0000769 ScriptConfiguration &Opt = *ScriptConfig;
770 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000771 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000772};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000773
George Rimar20b65982016-08-31 09:08:26 +0000774void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000775 readVersionScriptCommand();
776 if (!atEOF())
777 setError("EOF expected, but got " + next());
778}
779
780void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000781 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000782 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000783 return;
784 }
785
Rui Ueyama95769b42016-08-31 20:03:54 +0000786 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000787 StringRef VerStr = next();
788 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000789 setError("anonymous version definition is used in "
790 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000791 return;
792 }
793 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000794 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000795 }
796}
797
Rui Ueyama95769b42016-08-31 20:03:54 +0000798void ScriptParser::readVersion() {
799 expect("{");
800 readVersionScriptCommand();
801 expect("}");
802}
803
George Rimar20b65982016-08-31 09:08:26 +0000804void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000805 while (!atEOF()) {
806 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000807 if (Tok == ";")
808 continue;
809
Eugene Leviant20d03192016-09-16 15:30:47 +0000810 if (Tok == "ASSERT") {
811 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
812 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000813 readEntry();
814 } else if (Tok == "EXTERN") {
815 readExtern();
816 } else if (Tok == "GROUP" || Tok == "INPUT") {
817 readGroup();
818 } else if (Tok == "INCLUDE") {
819 readInclude();
820 } else if (Tok == "OUTPUT") {
821 readOutput();
822 } else if (Tok == "OUTPUT_ARCH") {
823 readOutputArch();
824 } else if (Tok == "OUTPUT_FORMAT") {
825 readOutputFormat();
826 } else if (Tok == "PHDRS") {
827 readPhdrs();
828 } else if (Tok == "SEARCH_DIR") {
829 readSearchDir();
830 } else if (Tok == "SECTIONS") {
831 readSections();
832 } else if (Tok == "VERSION") {
833 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000834 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000835 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000836 } else {
George Rimar57610422016-03-11 14:43:02 +0000837 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000838 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000839 }
840}
841
Rui Ueyama717677a2016-02-11 21:17:59 +0000842void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000843 if (IsUnderSysroot && S.startswith("/")) {
844 SmallString<128> Path;
845 (Config->Sysroot + S).toStringRef(Path);
846 if (sys::fs::exists(Path)) {
847 Driver->addFile(Saver.save(Path.str()));
848 return;
849 }
850 }
851
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000852 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000853 Driver->addFile(S);
854 } else if (S.startswith("=")) {
855 if (Config->Sysroot.empty())
856 Driver->addFile(S.substr(1));
857 else
858 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
859 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000860 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000861 } else if (sys::fs::exists(S)) {
862 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000863 } else {
864 std::string Path = findFromSearchPaths(S);
865 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000866 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000867 else
868 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000869 }
870}
871
Rui Ueyama717677a2016-02-11 21:17:59 +0000872void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000873 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000874 bool Orig = Config->AsNeeded;
875 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000876 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +0000877 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +0000878 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000879}
880
Rui Ueyama717677a2016-02-11 21:17:59 +0000881void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000882 // -e <symbol> takes predecence over ENTRY(<symbol>).
883 expect("(");
884 StringRef Tok = next();
885 if (Config->Entry.empty())
886 Config->Entry = Tok;
887 expect(")");
888}
889
Rui Ueyama717677a2016-02-11 21:17:59 +0000890void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000891 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000892 while (!Error && !skip(")"))
893 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000894}
895
Rui Ueyama717677a2016-02-11 21:17:59 +0000896void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000897 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000898 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000899 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000900 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000901 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000902 else
George Rimarcd574a52016-09-09 14:35:36 +0000903 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000904 }
905}
906
Rui Ueyama717677a2016-02-11 21:17:59 +0000907void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000908 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +0000909 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +0000910 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000911 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000912 return;
913 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000914 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000915 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
916 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000917 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000918}
919
Rui Ueyama717677a2016-02-11 21:17:59 +0000920void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000921 // -o <file> takes predecence over OUTPUT(<file>).
922 expect("(");
923 StringRef Tok = next();
924 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +0000925 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +0000926 expect(")");
927}
928
Rui Ueyama717677a2016-02-11 21:17:59 +0000929void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000930 // Error checking only for now.
931 expect("(");
932 next();
933 expect(")");
934}
935
Rui Ueyama717677a2016-02-11 21:17:59 +0000936void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000937 // Error checking only for now.
938 expect("(");
939 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000940 StringRef Tok = next();
941 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +0000942 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000943 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000944 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000945 return;
946 }
Davide Italiano6836c612015-10-12 21:08:41 +0000947 next();
948 expect(",");
949 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000950 expect(")");
951}
952
Eugene Leviantbbe38602016-07-19 09:25:43 +0000953void ScriptParser::readPhdrs() {
954 expect("{");
955 while (!Error && !skip("}")) {
956 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000957 Opt.PhdrsCommands.push_back(
958 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000959 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
960
961 PhdrCmd.Type = readPhdrType();
962 do {
963 Tok = next();
964 if (Tok == ";")
965 break;
966 if (Tok == "FILEHDR")
967 PhdrCmd.HasFilehdr = true;
968 else if (Tok == "PHDRS")
969 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000970 else if (Tok == "AT")
971 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +0000972 else if (Tok == "FLAGS") {
973 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000974 // Passing 0 for the value of dot is a bit of a hack. It means that
975 // we accept expressions like ".|1".
976 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000977 expect(")");
978 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000979 setError("unexpected header attribute: " + Tok);
980 } while (!Error);
981 }
982}
983
Rui Ueyama717677a2016-02-11 21:17:59 +0000984void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000985 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +0000986 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +0000987 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +0000988 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +0000989 expect(")");
990}
991
Rui Ueyama717677a2016-02-11 21:17:59 +0000992void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +0000993 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000994 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000995 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000996 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000997 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000998 if (!Cmd) {
999 if (Tok == "ASSERT")
1000 Cmd = new AssertCommand(readAssert());
1001 else
1002 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001003 }
Rui Ueyama10416562016-08-04 02:03:27 +00001004 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001005 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001006}
1007
Rui Ueyama708019c2016-07-24 18:19:40 +00001008static int precedence(StringRef Op) {
1009 return StringSwitch<int>(Op)
1010 .Case("*", 4)
1011 .Case("/", 4)
1012 .Case("+", 3)
1013 .Case("-", 3)
1014 .Case("<", 2)
1015 .Case(">", 2)
1016 .Case(">=", 2)
1017 .Case("<=", 2)
1018 .Case("==", 2)
1019 .Case("!=", 2)
1020 .Case("&", 1)
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001021 .Case("|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001022 .Default(-1);
1023}
1024
George Rimarc91930a2016-09-02 21:17:20 +00001025Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001026 std::vector<StringRef> V;
1027 while (!Error && !skip(")"))
1028 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001029 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001030}
1031
George Rimarbe394db2016-09-16 20:21:55 +00001032SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama742c3832016-08-04 22:27:00 +00001033 if (skip("SORT") || skip("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001034 return SortSectionPolicy::Name;
Rui Ueyama742c3832016-08-04 22:27:00 +00001035 if (skip("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001036 return SortSectionPolicy::Alignment;
George Rimar575208c2016-09-15 19:15:12 +00001037 if (skip("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001038 return SortSectionPolicy::Priority;
George Rimarbe394db2016-09-16 20:21:55 +00001039 if (skip("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001040 return SortSectionPolicy::None;
1041 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001042}
1043
1044static void selectSortKind(InputSectionDescription *Cmd) {
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001045 if (Cmd->SortOuter == SortSectionPolicy::None) {
1046 Cmd->SortOuter = SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001047 return;
1048 }
1049
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001050 if (Cmd->SortOuter != SortSectionPolicy::Default) {
George Rimarbe394db2016-09-16 20:21:55 +00001051 // If the section sorting command in linker script is nested, the command
1052 // line option will be ignored.
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001053 if (Cmd->SortInner != SortSectionPolicy::Default)
George Rimarbe394db2016-09-16 20:21:55 +00001054 return;
1055 // If the section sorting command in linker script isn't nested, the
1056 // command line option will make the section sorting command to be treated
1057 // as nested sorting command.
1058 Cmd->SortInner = Config->SortSection;
1059 return;
1060 }
1061 // If sorting rule not specified, use command line option.
1062 Cmd->SortOuter = Config->SortSection;
Rui Ueyama742c3832016-08-04 22:27:00 +00001063}
1064
George Rimar395281c2016-09-16 17:42:10 +00001065// Method reads a list of sequence of excluded files and section globs given in
1066// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1067// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1068void ScriptParser::readSectionExcludes(InputSectionDescription *Cmd) {
Rui Ueyama027a9e82016-09-17 02:10:15 +00001069 Regex ExcludeFileRe;
George Rimar395281c2016-09-16 17:42:10 +00001070 std::vector<StringRef> V;
1071
1072 while (!Error) {
1073 if (skip(")")) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001074 Cmd->SectionPatterns.push_back(
George Rimar395281c2016-09-16 17:42:10 +00001075 {std::move(ExcludeFileRe), compileGlobPatterns(V)});
1076 return;
1077 }
1078
1079 if (skip("EXCLUDE_FILE")) {
1080 if (!V.empty()) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001081 Cmd->SectionPatterns.push_back(
George Rimar395281c2016-09-16 17:42:10 +00001082 {std::move(ExcludeFileRe), compileGlobPatterns(V)});
1083 V.clear();
1084 }
1085
1086 expect("(");
1087 ExcludeFileRe = readFilePatterns();
1088 continue;
1089 }
1090
1091 V.push_back(next());
1092 }
1093}
1094
George Rimara2496cb2016-08-30 09:46:59 +00001095InputSectionDescription *
1096ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001097 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001098 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +00001099
Rui Ueyama742c3832016-08-04 22:27:00 +00001100 // Read SORT().
George Rimarbe394db2016-09-16 20:21:55 +00001101 SortSectionPolicy K1 = readSortKind();
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001102 if (K1 != SortSectionPolicy::Default) {
Rui Ueyama742c3832016-08-04 22:27:00 +00001103 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +00001104 expect("(");
George Rimarbe394db2016-09-16 20:21:55 +00001105 SortSectionPolicy K2 = readSortKind();
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001106 if (K2 != SortSectionPolicy::Default) {
Rui Ueyama742c3832016-08-04 22:27:00 +00001107 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +00001108 expect("(");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001109 Cmd->SectionPatterns.push_back({Regex(), readFilePatterns()});
George Rimar350ece42016-08-03 08:35:59 +00001110 expect(")");
1111 } else {
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001112 Cmd->SectionPatterns.push_back({Regex(), readFilePatterns()});
George Rimar350ece42016-08-03 08:35:59 +00001113 }
George Rimar0702c4e2016-07-29 15:32:46 +00001114 expect(")");
George Rimarbe394db2016-09-16 20:21:55 +00001115 selectSortKind(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001116 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001117 }
George Rimar0702c4e2016-07-29 15:32:46 +00001118
George Rimarbe394db2016-09-16 20:21:55 +00001119 selectSortKind(Cmd);
George Rimar395281c2016-09-16 17:42:10 +00001120 readSectionExcludes(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001121 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001122}
1123
George Rimara2496cb2016-08-30 09:46:59 +00001124InputSectionDescription *
1125ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001126 // Input section wildcard can be surrounded by KEEP.
1127 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001128 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001129 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001130 StringRef FilePattern = next();
1131 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001132 expect(")");
Rui Ueyama4dc07be2016-09-17 02:23:40 +00001133 for (SectionPattern &Pat : Cmd->SectionPatterns)
1134 Opt.KeptSections.push_back(&Pat.SectionRe);
Rui Ueyama10416562016-08-04 02:03:27 +00001135 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001136 }
George Rimara2496cb2016-08-30 09:46:59 +00001137 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001138}
1139
George Rimar03fc0102016-07-28 07:18:23 +00001140void ScriptParser::readSort() {
1141 expect("(");
1142 expect("CONSTRUCTORS");
1143 expect(")");
1144}
1145
George Rimareefa7582016-08-04 09:29:31 +00001146Expr ScriptParser::readAssert() {
1147 expect("(");
1148 Expr E = readExpr();
1149 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001150 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001151 expect(")");
1152 return [=](uint64_t Dot) {
1153 uint64_t V = E(Dot);
1154 if (!V)
1155 error(Msg);
1156 return V;
1157 };
1158}
1159
Rui Ueyama25150e82016-09-06 17:46:43 +00001160// Reads a FILL(expr) command. We handle the FILL command as an
1161// alias for =fillexp section attribute, which is different from
1162// what GNU linkers do.
1163// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001164std::vector<uint8_t> ScriptParser::readFill() {
1165 expect("(");
1166 std::vector<uint8_t> V = readOutputSectionFiller(next());
1167 expect(")");
1168 expect(";");
1169 return V;
1170}
1171
Rui Ueyama10416562016-08-04 02:03:27 +00001172OutputSectionCommand *
1173ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001174 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001175
1176 // Read an address expression.
1177 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1178 if (peek() != ":")
1179 Cmd->AddrExpr = readExpr();
1180
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001181 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001182
George Rimar8ceadb32016-08-17 07:44:19 +00001183 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001184 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001185 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001186 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001187 if (skip("SUBALIGN"))
1188 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001189
Davide Italiano246f6812016-07-22 03:36:24 +00001190 // Parse constraints.
1191 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001192 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001193 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001194 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001195 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001196
Rui Ueyama025d59b2016-02-02 20:27:59 +00001197 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001198 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001199 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001200 Cmd->Commands.emplace_back(Assignment);
George Rimarff1f29e2016-09-06 13:51:57 +00001201 else if (Tok == "FILL")
1202 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001203 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001204 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001205 else if (peek() == "(")
1206 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001207 else
1208 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001209 }
George Rimar076fe152016-07-21 06:43:01 +00001210 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimarff1f29e2016-09-06 13:51:57 +00001211 if (peek().startswith("="))
1212 Cmd->Filler = readOutputSectionFiller(next().drop_front());
Rui Ueyama10416562016-08-04 02:03:27 +00001213 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001214}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001215
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001216// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1217// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1218//
1219// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1220// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1221// as 32-bit big-endian values. We will do the same as ld.gold does
1222// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001223std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001224 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001225 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001226 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001227 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001228 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001229 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001230}
1231
Petr Hoseka35e39c2016-08-16 01:11:16 +00001232SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001233 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001234 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001235 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001236 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001237 expect(")");
1238 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001239 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001240}
1241
Eugene Leviantdb741e72016-09-07 07:08:43 +00001242SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1243 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001244 SymbolAssignment *Cmd = nullptr;
1245 if (peek() == "=" || peek() == "+=") {
1246 Cmd = readAssignment(Tok);
1247 expect(";");
1248 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001249 Cmd = readProvideHidden(true, false);
1250 } else if (Tok == "HIDDEN") {
1251 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001252 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001253 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001254 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001255 if (Cmd && MakeAbsolute)
1256 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001257 return Cmd;
1258}
1259
George Rimar30835ea2016-07-28 21:08:56 +00001260static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1261 if (S == ".")
1262 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001263 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001264}
1265
George Rimar30835ea2016-07-28 21:08:56 +00001266SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1267 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001268 bool IsAbsolute = false;
1269 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001270 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001271 if (skip("ABSOLUTE")) {
1272 E = readParenExpr();
1273 IsAbsolute = true;
1274 } else {
1275 E = readExpr();
1276 }
George Rimar30835ea2016-07-28 21:08:56 +00001277 if (Op == "+=")
1278 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001279 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001280}
1281
1282// This is an operator-precedence parser to parse a linker
1283// script expression.
1284Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1285
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001286static Expr combine(StringRef Op, Expr L, Expr R) {
1287 if (Op == "*")
1288 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1289 if (Op == "/") {
1290 return [=](uint64_t Dot) -> uint64_t {
1291 uint64_t RHS = R(Dot);
1292 if (RHS == 0) {
1293 error("division by zero");
1294 return 0;
1295 }
1296 return L(Dot) / RHS;
1297 };
1298 }
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); };
1315 if (Op == "&")
1316 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001317 if (Op == "|")
1318 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001319 llvm_unreachable("invalid operator");
1320}
1321
Rui Ueyama708019c2016-07-24 18:19:40 +00001322// This is a part of the operator-precedence parser. This function
1323// assumes that the remaining token stream starts with an operator.
1324Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1325 while (!atEOF() && !Error) {
1326 // Read an operator and an expression.
1327 StringRef Op1 = peek();
1328 if (Op1 == "?")
1329 return readTernary(Lhs);
1330 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001331 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001332 next();
1333 Expr Rhs = readPrimary();
1334
1335 // Evaluate the remaining part of the expression first if the
1336 // next operator has greater precedence than the previous one.
1337 // For example, if we have read "+" and "3", and if the next
1338 // operator is "*", then we'll evaluate 3 * ... part first.
1339 while (!atEOF()) {
1340 StringRef Op2 = peek();
1341 if (precedence(Op2) <= precedence(Op1))
1342 break;
1343 Rhs = readExpr1(Rhs, precedence(Op2));
1344 }
1345
1346 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001347 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001348 return Lhs;
1349}
1350
1351uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001352 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001353 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001354 if (S == "MAXPAGESIZE")
1355 return Target->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001356 error("unknown constant: " + S);
1357 return 0;
1358}
1359
Rui Ueyama626e0b02016-09-02 18:19:00 +00001360// Parses Tok as an integer. Returns true if successful.
1361// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1362// and decimal numbers. Decimal numbers may have "K" (kilo) or
1363// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001364static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001365 if (Tok.startswith("-")) {
1366 if (!readInteger(Tok.substr(1), Result))
1367 return false;
1368 Result = -Result;
1369 return true;
1370 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001371 if (Tok.startswith_lower("0x"))
1372 return !Tok.substr(2).getAsInteger(16, Result);
1373 if (Tok.endswith_lower("H"))
1374 return !Tok.drop_back().getAsInteger(16, Result);
1375
1376 int Suffix = 1;
1377 if (Tok.endswith_lower("K")) {
1378 Suffix = 1024;
1379 Tok = Tok.drop_back();
1380 } else if (Tok.endswith_lower("M")) {
1381 Suffix = 1024 * 1024;
1382 Tok = Tok.drop_back();
1383 }
1384 if (Tok.getAsInteger(10, Result))
1385 return false;
1386 Result *= Suffix;
1387 return true;
1388}
1389
Rui Ueyama708019c2016-07-24 18:19:40 +00001390Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001391 if (peek() == "(")
1392 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001393
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001394 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001395
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001396 if (Tok == "~") {
1397 Expr E = readPrimary();
1398 return [=](uint64_t Dot) { return ~E(Dot); };
1399 }
1400 if (Tok == "-") {
1401 Expr E = readPrimary();
1402 return [=](uint64_t Dot) { return -E(Dot); };
1403 }
1404
Rui Ueyama708019c2016-07-24 18:19:40 +00001405 // Built-in functions are parsed here.
1406 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001407 if (Tok == "ADDR") {
1408 expect("(");
1409 StringRef Name = next();
1410 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001411 return
1412 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001413 }
George Rimareefa7582016-08-04 09:29:31 +00001414 if (Tok == "ASSERT")
1415 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001416 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001417 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001418 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1419 }
1420 if (Tok == "CONSTANT") {
1421 expect("(");
1422 StringRef Tok = next();
1423 expect(")");
1424 return [=](uint64_t Dot) { return getConstant(Tok); };
1425 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001426 if (Tok == "SEGMENT_START") {
1427 expect("(");
1428 next();
1429 expect(",");
1430 uint64_t Val;
Rafael Espindola3adbbc32016-09-15 13:36:44 +00001431 if (next().getAsInteger(0, Val))
1432 setError("integer expected");
Rafael Espindola54c145c2016-07-28 18:16:24 +00001433 expect(")");
1434 return [=](uint64_t Dot) { return Val; };
1435 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001436 if (Tok == "DATA_SEGMENT_ALIGN") {
1437 expect("(");
1438 Expr E = readExpr();
1439 expect(",");
1440 readExpr();
1441 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001442 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001443 }
1444 if (Tok == "DATA_SEGMENT_END") {
1445 expect("(");
1446 expect(".");
1447 expect(")");
1448 return [](uint64_t Dot) { return Dot; };
1449 }
George Rimar276b4e62016-07-26 17:58:44 +00001450 // GNU linkers implements more complicated logic to handle
1451 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1452 // the next page boundary for simplicity.
1453 if (Tok == "DATA_SEGMENT_RELRO_END") {
1454 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001455 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001456 expect(",");
1457 readExpr();
1458 expect(")");
1459 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1460 }
George Rimar9e694502016-07-29 16:18:47 +00001461 if (Tok == "SIZEOF") {
1462 expect("(");
1463 StringRef Name = next();
1464 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001465 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001466 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001467 if (Tok == "ALIGNOF") {
1468 expect("(");
1469 StringRef Name = next();
1470 expect(")");
1471 return
1472 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1473 }
George Rimare32a3592016-08-10 07:59:34 +00001474 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001475 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001476
George Rimar9f2f7ad2016-09-02 16:01:42 +00001477 // Tok is a literal number.
1478 uint64_t V;
1479 if (readInteger(Tok, V))
1480 return [=](uint64_t Dot) { return V; };
1481
1482 // Tok is a symbol name.
1483 if (Tok != "." && !isValidCIdentifier(Tok))
1484 setError("malformed number: " + Tok);
1485 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001486}
1487
1488Expr ScriptParser::readTernary(Expr Cond) {
1489 next();
1490 Expr L = readExpr();
1491 expect(":");
1492 Expr R = readExpr();
1493 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1494}
1495
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001496Expr ScriptParser::readParenExpr() {
1497 expect("(");
1498 Expr E = readExpr();
1499 expect(")");
1500 return E;
1501}
1502
Eugene Leviantbbe38602016-07-19 09:25:43 +00001503std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1504 std::vector<StringRef> Phdrs;
1505 while (!Error && peek().startswith(":")) {
1506 StringRef Tok = next();
1507 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1508 if (Tok.empty()) {
1509 setError("section header name is empty");
1510 break;
1511 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001512 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001513 }
1514 return Phdrs;
1515}
1516
1517unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001518 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001519 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001520 .Case("PT_NULL", PT_NULL)
1521 .Case("PT_LOAD", PT_LOAD)
1522 .Case("PT_DYNAMIC", PT_DYNAMIC)
1523 .Case("PT_INTERP", PT_INTERP)
1524 .Case("PT_NOTE", PT_NOTE)
1525 .Case("PT_SHLIB", PT_SHLIB)
1526 .Case("PT_PHDR", PT_PHDR)
1527 .Case("PT_TLS", PT_TLS)
1528 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1529 .Case("PT_GNU_STACK", PT_GNU_STACK)
1530 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1531 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001532
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001533 if (Ret == (unsigned)-1) {
1534 setError("invalid program header type: " + Tok);
1535 return PT_NULL;
1536 }
1537 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001538}
1539
Rui Ueyama95769b42016-08-31 20:03:54 +00001540void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001541 // Identifiers start at 2 because 0 and 1 are reserved
1542 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1543 size_t VersionId = Config->VersionDefinitions.size() + 2;
1544 Config->VersionDefinitions.push_back({VerStr, VersionId});
1545
1546 if (skip("global:") || peek() != "local:")
1547 readGlobal(VerStr);
1548 if (skip("local:"))
1549 readLocal();
1550 expect("}");
1551
1552 // Each version may have a parent version. For example, "Ver2" defined as
1553 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1554 // version hierarchy is, probably against your instinct, purely for human; the
1555 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1556 if (!VerStr.empty() && peek() != ";")
1557 next();
1558 expect(";");
1559}
1560
1561void ScriptParser::readLocal() {
1562 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1563 expect("*");
1564 expect(";");
1565}
1566
1567void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001568 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001569 expect("{");
1570
1571 for (;;) {
1572 if (peek() == "}" || Error)
1573 break;
George Rimarcd574a52016-09-09 14:35:36 +00001574 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1575 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001576 expect(";");
1577 }
1578
1579 expect("}");
1580 expect(";");
1581}
1582
1583void ScriptParser::readGlobal(StringRef VerStr) {
1584 std::vector<SymbolVersion> *Globals;
1585 if (VerStr.empty())
1586 Globals = &Config->VersionScriptGlobals;
1587 else
1588 Globals = &Config->VersionDefinitions.back().Globals;
1589
1590 for (;;) {
1591 if (skip("extern"))
1592 readExtern(Globals);
1593
1594 StringRef Cur = peek();
1595 if (Cur == "}" || Cur == "local:" || Error)
1596 return;
1597 next();
George Rimarcd574a52016-09-09 14:35:36 +00001598 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001599 expect(";");
1600 }
1601}
1602
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001603static bool isUnderSysroot(StringRef Path) {
1604 if (Config->Sysroot == "")
1605 return false;
1606 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1607 if (sys::fs::equivalent(Config->Sysroot, Path))
1608 return true;
1609 return false;
1610}
1611
Rui Ueyama07320e42016-04-20 20:13:41 +00001612void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001613 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001614 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1615}
1616
1617void elf::readVersionScript(MemoryBufferRef MB) {
1618 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001619}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001620
Rui Ueyama07320e42016-04-20 20:13:41 +00001621template class elf::LinkerScript<ELF32LE>;
1622template class elf::LinkerScript<ELF32BE>;
1623template class elf::LinkerScript<ELF64LE>;
1624template class elf::LinkerScript<ELF64BE>;