blob: b0a83d8d5cf337d67f8474522d92e5719f1761e9 [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;
George Rimare38cbab2016-09-26 19:22:50 +000041using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000042using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000043using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000044
George Rimar884e7862016-09-08 08:19:13 +000045LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000046ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000047
George Rimar6c55f0e2016-09-08 08:20:30 +000048template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +000049 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
50 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
51 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000052
53 // If we have no SECTIONS then we don't have '.' and don't call
54 // assignAddresses(). We calculate symbol value immediately in this case.
55 if (!ScriptConfig->HasSections)
56 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000057}
58
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000059template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000060 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
61 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000062 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000063}
64
Eugene Leviantdb741e72016-09-07 07:08:43 +000065template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
66 if (Cmd->IsAbsolute)
67 addRegular<ELFT>(Cmd);
68 else
69 addSynthetic<ELFT>(Cmd);
70}
Rui Ueyama16024212016-08-11 23:22:52 +000071// If a symbol was in PROVIDE(), we need to define it only when
72// it is an undefined symbol.
73template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
74 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000075 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000076 if (!Cmd->Provide)
77 return true;
78 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
79 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000080}
81
George Rimar076fe152016-07-21 06:43:01 +000082bool SymbolAssignment::classof(const BaseCommand *C) {
83 return C->Kind == AssignmentKind;
84}
85
86bool OutputSectionCommand::classof(const BaseCommand *C) {
87 return C->Kind == OutputSectionKind;
88}
89
George Rimareea31142016-07-21 14:26:59 +000090bool InputSectionDescription::classof(const BaseCommand *C) {
91 return C->Kind == InputSectionKind;
92}
93
George Rimareefa7582016-08-04 09:29:31 +000094bool AssertCommand::classof(const BaseCommand *C) {
95 return C->Kind == AssertKind;
96}
97
George Rimare38cbab2016-09-26 19:22:50 +000098bool BytesDataCommand::classof(const BaseCommand *C) {
99 return C->Kind == BytesDataKind;
100}
101
Rui Ueyama36a153c2016-07-23 14:09:58 +0000102template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000103 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000104}
105
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000106template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
107template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
108
Rui Ueyama07320e42016-04-20 20:13:41 +0000109template <class ELFT>
110bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000111 for (InputSectionDescription *ID : Opt.KeptSections) {
112 StringRef Filename = S->getFile()->getName();
113 if (!ID->FileRe.match(sys::path::filename(Filename)))
114 continue;
115
116 for (SectionPattern &P : ID->SectionPatterns)
117 if (P.SectionRe.match(S->Name))
118 return true;
119 }
George Rimareea31142016-07-21 14:26:59 +0000120 return false;
121}
122
George Rimar575208c2016-09-15 19:15:12 +0000123static bool comparePriority(InputSectionData *A, InputSectionData *B) {
124 return getPriority(A->Name) < getPriority(B->Name);
125}
126
Rafael Espindolac0028d32016-09-08 20:47:52 +0000127static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000128 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000129}
George Rimar350ece42016-08-03 08:35:59 +0000130
Rafael Espindolac0028d32016-09-08 20:47:52 +0000131static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000132 // ">" is not a mistake. Larger alignments are placed before smaller
133 // alignments in order to reduce the amount of padding necessary.
134 // This is compatible with GNU.
135 return A->Alignment > B->Alignment;
136}
George Rimar350ece42016-08-03 08:35:59 +0000137
Rafael Espindolac0028d32016-09-08 20:47:52 +0000138static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000139getComparator(SortSectionPolicy K) {
140 switch (K) {
141 case SortSectionPolicy::Alignment:
142 return compareAlignment;
143 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000144 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000145 case SortSectionPolicy::Priority:
146 return comparePriority;
147 default:
148 llvm_unreachable("unknown sort policy");
149 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000150}
George Rimar0702c4e2016-07-29 15:32:46 +0000151
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000152template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000153static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000154 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000155 if (Kind == ConstraintKind::NoConstraint)
156 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000157 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000158 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindolae746e522016-09-21 18:33:44 +0000159 return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000160 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000161 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
162 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000163}
164
George Rimar07171f22016-09-21 15:56:44 +0000165static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000166 SortSectionPolicy K) {
167 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000168 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000169}
170
Rafael Espindolad3190792016-09-16 15:10:23 +0000171// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000172template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000173void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000174 // Collects all sections that satisfy constraints of I
175 // and attach them to I.
176 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000177 size_t SizeBefore = I->Sections.size();
George Rimar395281c2016-09-16 17:42:10 +0000178 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000179 StringRef Filename = sys::path::filename(F->getName());
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000180 if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000181 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000182
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000183 for (InputSectionBase<ELFT> *S : F->getSections())
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000184 if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000185 I->Sections.push_back(S);
Rafael Espindolaf135f0e2016-09-19 13:33:38 +0000186 if (Pat.SectionRe.match("COMMON"))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000187 I->Sections.push_back(CommonInputSection<ELFT>::X);
George Rimar395281c2016-09-16 17:42:10 +0000188 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000189
George Rimar07171f22016-09-21 15:56:44 +0000190 // Sort sections as instructed by SORT-family commands and --sort-section
191 // option. Because SORT-family commands can be nested at most two depth
192 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
193 // line option is respected even if a SORT command is given, the exact
194 // behavior we have here is a bit complicated. Here are the rules.
195 //
196 // 1. If two SORT commands are given, --sort-section is ignored.
197 // 2. If one SORT command is given, and if it is not SORT_NONE,
198 // --sort-section is handled as an inner SORT command.
199 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
200 // 4. If no SORT command is given, sort according to --sort-section.
201 InputSectionData **Begin = I->Sections.data() + SizeBefore;
202 InputSectionData **End = I->Sections.data() + I->Sections.size();
203 if (Pat.SortOuter != SortSectionPolicy::None) {
204 if (Pat.SortInner == SortSectionPolicy::Default)
205 sortSections(Begin, End, Config->SortSection);
206 else
207 sortSections(Begin, End, Pat.SortInner);
208 sortSections(Begin, End, Pat.SortOuter);
209 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000210 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000211
212 // We do not add duplicate input sections, so mark them with a dummy output
213 // section for now.
214 for (InputSectionData *S : I->Sections) {
215 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
216 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
217 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000218}
219
220template <class ELFT>
221void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
222 for (InputSectionBase<ELFT> *S : V) {
223 S->Live = false;
224 reportDiscarded(S);
225 }
226}
227
George Rimar06ae6832016-08-12 09:07:57 +0000228template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000229std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000230LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000231 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000232
George Rimar06ae6832016-08-12 09:07:57 +0000233 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000234 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
235 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000236 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000237 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000238 for (InputSectionData *S : Cmd->Sections)
239 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000240 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000241
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000242 return Ret;
243}
244
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000245template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000246static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
247 StringRef OutsecName) {
248 // When using linker script the merge rules are different.
249 // Unfortunately, linker scripts are name based. This means that expressions
250 // like *(.foo*) can refer to multiple input sections that would normally be
251 // placed in different output sections. We cannot put them in different
252 // output sections or we would produce wrong results for
253 // start = .; *(.foo.*) end = .; *(.bar)
254 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
255 // another. The problem is that there is no way to layout those output
256 // sections such that the .foo sections are the only thing between the
257 // start and end symbols.
258
259 // An extra annoyance is that we cannot simply disable merging of the contents
260 // of SHF_MERGE sections, but our implementation requires one output section
261 // per "kind" (string or not, which size/aligment).
262 // Fortunately, creating symbols in the middle of a merge section is not
263 // supported by bfd or gold, so we can just create multiple section in that
264 // case.
265 const typename ELFT::Shdr *H = C->getSectionHdr();
266 typedef typename ELFT::uint uintX_t;
267 uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
268
269 uintX_t Alignment = 0;
270 if (isa<MergeInputSection<ELFT>>(C))
271 Alignment = std::max(H->sh_addralign, H->sh_entsize);
272
273 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
274}
275
276template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000277void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
278 InputSectionBase<ELFT> *Sec,
279 StringRef Name) {
280 OutputSectionBase<ELFT> *OutSec;
281 bool IsNew;
282 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
283 if (IsNew)
284 OutputSections->push_back(OutSec);
285 OutSec->addSection(Sec);
286}
287
288template <class ELFT>
289void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000290
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000291 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
292 auto Iter = Opt.Commands.begin() + I;
293 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000294 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
295 if (shouldDefine<ELFT>(Cmd))
296 addRegular<ELFT>(Cmd);
297 continue;
298 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000299 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
300 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000301 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000302 // will not be called, so ASSERT should be evaluated now.
303 if (!Opt.HasSections)
304 Cmd->Expression(0);
305 continue;
306 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000307
Eugene Leviantceabe802016-08-11 07:56:43 +0000308 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000309 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
310
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000311 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000312 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000313 continue;
314 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000315
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000316 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
317 for (InputSectionBase<ELFT> *S : V)
318 S->OutSec = nullptr;
319 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000320 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000321 continue;
322 }
323
324 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
325 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
326 if (shouldDefine<ELFT>(OutCmd))
327 addSymbol<ELFT>(OutCmd);
328
Eugene Leviant97403d12016-09-01 09:55:57 +0000329 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000330 continue;
331
George Rimardb24d9c2016-08-19 15:18:23 +0000332 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000333 addSection(Factory, Sec, Cmd->Name);
334 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000335 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000336 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000337 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000338 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000339}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000340
Eugene Leviant20d03192016-09-16 15:30:47 +0000341template <class ELFT>
342void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
343 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000344 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000345 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
346 for (InputSectionBase<ELFT> *S : F->getSections())
347 if (!isDiscarded(S) && !S->OutSec)
348 addSection(Factory, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000349}
350
Eugene Leviantdb741e72016-09-07 07:08:43 +0000351// Sets value of a section-defined symbol. Two kinds of
352// symbols are processed: synthetic symbols, whose value
353// is an offset from beginning of section and regular
354// symbols whose value is absolute.
355template <class ELFT>
356static void assignSectionSymbol(SymbolAssignment *Cmd,
357 OutputSectionBase<ELFT> *Sec,
358 typename ELFT::uint Off) {
359 if (!Cmd->Sym)
360 return;
361
362 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
363 Body->Section = Sec;
364 Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
365 return;
366 }
367 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
368 Body->Value = Cmd->Expression(Sec->getVA() + Off);
369}
370
Rafael Espindolaa940e532016-09-22 12:35:44 +0000371template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
372 return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
373}
374
Rafael Espindolad3190792016-09-16 15:10:23 +0000375template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
376 if (!AlreadyOutputIS.insert(S).second)
377 return;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000378 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000379
Rafael Espindolad3190792016-09-16 15:10:23 +0000380 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
381 Pos = alignTo(Pos, S->Alignment);
382 S->OutSecOff = Pos - CurOutSec->getVA();
383 Pos += S->getSize();
384
385 // Update output section size after adding each section. This is so that
386 // SIZEOF works correctly in the case below:
387 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
388 CurOutSec->setSize(Pos - CurOutSec->getVA());
389
Rafael Espindola7252ae52016-09-22 12:00:08 +0000390 if (IsTbss)
391 ThreadBssOffset = Pos - Dot;
392 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000393 Dot = Pos;
394}
395
396template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000397 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
398 return;
399 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000400 for (InputSection<ELFT> *I : OutSec->Sections)
401 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000402 } else {
403 Dot += CurOutSec->getSize();
Eugene Leviant20889c52016-08-31 08:13:33 +0000404 }
405}
406
407template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000408void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
409 if (CurOutSec == Sec)
410 return;
411 if (AlreadyOutputOS.count(Sec))
412 return;
413
414 flush();
415 CurOutSec = Sec;
416
417 Dot = alignTo(Dot, CurOutSec->getAlignment());
Rafael Espindolaa940e532016-09-22 12:35:44 +0000418 CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000419}
420
421template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000422 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000423 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
424 if (AssignCmd->Name == ".") {
425 // Update to location counter means update to section size.
426 Dot = AssignCmd->Expression(Dot);
427 CurOutSec->setSize(Dot - CurOutSec->getVA());
428 return;
429 }
430 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
Eugene Leviantceabe802016-08-11 07:56:43 +0000431 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000432 }
George Rimare38cbab2016-09-26 19:22:50 +0000433
434 // Handle BYTE(), SHORT(), LONG(), or QUAD().
435 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
436 DataCmd->Offset = Dot - CurOutSec->getVA();
437 Dot += DataCmd->Size;
438 CurOutSec->setSize(Dot - CurOutSec->getVA());
439 return;
440 }
441
442 // It handles single input section description command,
443 // calculates and assigns the offsets for each section and also
444 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000445 auto &ICmd = cast<InputSectionDescription>(Base);
446 for (InputSectionData *ID : ICmd.Sections) {
447 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
448 switchTo(IB->OutSec);
449 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
450 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000451 else
452 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000453 }
454}
455
George Rimar8f66df92016-08-12 20:38:20 +0000456template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000457static std::vector<OutputSectionBase<ELFT> *>
458findSections(OutputSectionCommand &Cmd,
Rafael Espindolad3190792016-09-16 15:10:23 +0000459 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000460 std::vector<OutputSectionBase<ELFT> *> Ret;
461 for (OutputSectionBase<ELFT> *Sec : Sections)
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000462 if (Sec->getName() == Cmd.Name)
George Rimara14b13d2016-09-07 10:46:07 +0000463 Ret.push_back(Sec);
464 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000465}
466
Rafael Espindolad3190792016-09-16 15:10:23 +0000467template <class ELFT>
468void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
469 std::vector<OutputSectionBase<ELFT> *> Sections =
470 findSections(*Cmd, *OutputSections);
471 if (Sections.empty())
472 return;
473 switchTo(Sections[0]);
474
475 // Find the last section output location. We will output orphan sections
476 // there so that end symbols point to the correct location.
477 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
478 [](const std::unique_ptr<BaseCommand> &Cmd) {
479 return !isa<SymbolAssignment>(*Cmd);
480 })
481 .base();
482 for (auto I = Cmd->Commands.begin(); I != E; ++I)
483 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000484 for (OutputSectionBase<ELFT> *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000485 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000486 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000487 std::for_each(E, Cmd->Commands.end(),
488 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000489}
490
Rafael Espindola9546fff2016-09-22 14:40:50 +0000491template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000492 // It is common practice to use very generic linker scripts. So for any
493 // given run some of the output sections in the script will be empty.
494 // We could create corresponding empty output sections, but that would
495 // clutter the output.
496 // We instead remove trivially empty sections. The bfd linker seems even
497 // more aggressive at removing them.
498 auto Pos = std::remove_if(
499 Opt.Commands.begin(), Opt.Commands.end(),
500 [&](const std::unique_ptr<BaseCommand> &Base) {
501 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
502 if (!Cmd)
503 return false;
504 std::vector<OutputSectionBase<ELFT> *> Secs =
505 findSections(*Cmd, *OutputSections);
506 if (!Secs.empty())
507 return false;
508 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
509 if (!isa<InputSectionDescription>(I.get()))
510 return false;
511 return true;
512 });
513 Opt.Commands.erase(Pos, Opt.Commands.end());
514
Rafael Espindola9546fff2016-09-22 14:40:50 +0000515 // If the output section contains only symbol assignments, create a
516 // corresponding output section. The bfd linker seems to only create them if
517 // '.' is assigned to, but creating these section should not have any bad
518 // consequeces and gives us a section to put the symbol in.
519 uintX_t Flags = SHF_ALLOC;
520 uint32_t Type = 0;
521 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
522 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
523 if (!Cmd)
524 continue;
525 std::vector<OutputSectionBase<ELFT> *> Secs =
526 findSections(*Cmd, *OutputSections);
527 if (!Secs.empty()) {
528 Flags = Secs[0]->getFlags();
529 Type = Secs[0]->getType();
530 continue;
531 }
532
533 auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
534 Out<ELFT>::Pool.emplace_back(OutSec);
535 OutputSections->push_back(OutSec);
536 }
537}
538
Rafael Espindola15c57952016-09-22 18:05:49 +0000539// When placing orphan sections, we want to place them after symbol assignments
540// so that an orphan after
541// begin_foo = .;
542// foo : { *(foo) }
543// end_foo = .;
544// doesn't break the intended meaning of the begin/end symbols.
545// We don't want to go over sections since Writer<ELFT>::sortSections is the
546// one in charge of deciding the order of the sections.
547// We don't want to go over alignments, since doing so in
548// rx_sec : { *(rx_sec) }
549// . = ALIGN(0x1000);
550// /* The RW PT_LOAD starts here*/
551// rw_sec : { *(rw_sec) }
552// would mean that the RW PT_LOAD would become unaligned.
553static bool shouldSkip(const BaseCommand &Cmd) {
554 if (isa<OutputSectionCommand>(Cmd))
555 return false;
556 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
557 if (!Assign)
558 return true;
559 return Assign->Name != ".";
560}
561
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000562template <class ELFT>
563void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
George Rimar652852c2016-04-16 10:10:32 +0000564 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000565 // are not explicitly placed into the output file by the linker script.
566 // We place orphan sections at end of file.
567 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000568 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000569
570 // The OutputSections are already in the correct order.
571 // This loops creates or moves commands as needed so that they are in the
572 // correct order.
573 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000574 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000575 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000576
577 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000578 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000579 auto CmdIter = Opt.Commands.begin() + CmdIndex;
580 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000581 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000582 ++CmdIter;
583 ++CmdIndex;
584 }
585
586 auto Pos =
587 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
588 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
589 return Cmd && Cmd->Name == Name;
590 });
591 if (Pos == E) {
592 Opt.Commands.insert(CmdIter,
593 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000594 ++CmdIndex;
595 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000596 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000597
598 // Continue from where we found it.
599 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
600 continue;
George Rimar652852c2016-04-16 10:10:32 +0000601 }
George Rimar652852c2016-04-16 10:10:32 +0000602
Rui Ueyama7c18c282016-04-18 21:00:40 +0000603 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000604 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000605
George Rimar076fe152016-07-21 06:43:01 +0000606 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
607 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000608 if (Cmd->Name == ".") {
609 Dot = Cmd->Expression(Dot);
610 } else if (Cmd->Sym) {
611 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
612 }
George Rimar652852c2016-04-16 10:10:32 +0000613 continue;
614 }
615
George Rimareefa7582016-08-04 09:29:31 +0000616 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
617 Cmd->Expression(Dot);
618 continue;
619 }
620
George Rimar076fe152016-07-21 06:43:01 +0000621 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000622
Rafael Espindolad3190792016-09-16 15:10:23 +0000623 if (Cmd->AddrExpr)
624 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000625
Rafael Espindolad3190792016-09-16 15:10:23 +0000626 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000627 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000628
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000629 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
630 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
631 if (Sec->getFlags() & SHF_ALLOC)
632 MinVA = std::min(MinVA, Sec->getVA());
633 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000634 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000635 }
636
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000637 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000638 auto FirstPTLoad =
639 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
640 return E.H.p_type == PT_LOAD;
641 });
642 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
643 // ELF and Program headers need to be right before the first section in
644 // memory. Set their addresses accordingly.
645 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
646 Out<ELFT>::ElfHeader->setVA(MinVA);
647 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
648 FirstPTLoad->First = Out<ELFT>::ElfHeader;
649 if (!FirstPTLoad->Last)
650 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
651 }
George Rimar652852c2016-04-16 10:10:32 +0000652}
653
Rui Ueyama464daad2016-08-22 04:55:20 +0000654// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000655template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000656std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000657 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000658
Rui Ueyama464daad2016-08-22 04:55:20 +0000659 // Process PHDRS and FILEHDR keywords because they are not
660 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000661 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000662 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
663 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000664
665 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000666 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000667 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000668 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000669
670 if (Cmd.LMAExpr) {
671 Phdr.H.p_paddr = Cmd.LMAExpr(0);
672 Phdr.HasLMA = true;
673 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000674 }
675
Rui Ueyama464daad2016-08-22 04:55:20 +0000676 // Add output sections to program headers.
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000677 PhdrEntry<ELFT> *Load = nullptr;
678 uintX_t Flags = PF_R;
Rui Ueyama464daad2016-08-22 04:55:20 +0000679 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000680 if (!(Sec->getFlags() & SHF_ALLOC))
681 break;
682
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000683 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000684 if (!PhdrIds.empty()) {
685 // Assign headers specified by linker script
686 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000687 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000688 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000689 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000690 }
691 } else {
692 // If we have no load segment or flags've changed then we want new load
693 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000694 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000695 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000696 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000697 Flags = NewFlags;
698 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000699 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000700 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000701 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000702 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000703}
704
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000705template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
706 // Ignore .interp section in case we have PHDRS specification
707 // and PT_INTERP isn't listed.
708 return !Opt.PhdrsCommands.empty() &&
709 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
710 return Cmd.Type == PT_INTERP;
711 }) == Opt.PhdrsCommands.end();
712}
713
Eugene Leviantbbe38602016-07-19 09:25:43 +0000714template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000715ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000716 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
717 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
718 if (Cmd->Name == Name)
719 return Cmd->Filler;
720 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000721}
722
George Rimare38cbab2016-09-26 19:22:50 +0000723template <class ELFT>
724static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
725 const endianness E = ELFT::TargetEndianness;
726
727 switch (Size) {
728 case 1:
729 *Buf = (uint8_t)Data;
730 break;
731 case 2:
732 write16<E>(Buf, Data);
733 break;
734 case 4:
735 write32<E>(Buf, Data);
736 break;
737 case 8:
738 write64<E>(Buf, Data);
739 break;
740 default:
741 llvm_unreachable("unsupported Size argument");
742 }
743}
744
745template <class ELFT>
746void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
747 int I = getSectionIndex(Name);
748 if (I == INT_MAX)
749 return;
750
751 OutputSectionCommand *Cmd =
752 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
753 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
754 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
755 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
756}
757
George Rimar206fffa2016-08-17 08:16:57 +0000758template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000759 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
760 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
761 if (Cmd->LmaExpr && Cmd->Name == Name)
762 return Cmd->LmaExpr;
763 return {};
764}
765
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000766// Returns the index of the given section name in linker script
767// SECTIONS commands. Sections are laid out as the same order as they
768// were in the script. If a given name did not appear in the script,
769// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000770template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000771 int I = 0;
772 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
773 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
774 if (Cmd->Name == Name)
775 return I;
776 ++I;
777 }
778 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000779}
780
Eugene Leviantbbe38602016-07-19 09:25:43 +0000781template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
782 return !Opt.PhdrsCommands.empty();
783}
784
George Rimar9e694502016-07-29 16:18:47 +0000785template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000786uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000787 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
788 if (Sec->getName() == Name)
789 return Sec->getVA();
790 error("undefined section " + Name);
791 return 0;
792}
793
794template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000795uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000796 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
797 if (Sec->getName() == Name)
798 return Sec->getSize();
799 error("undefined section " + Name);
800 return 0;
801}
802
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000803template <class ELFT>
804uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
805 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
806 if (Sec->getName() == Name)
807 return Sec->getAlignment();
808 error("undefined section " + Name);
809 return 0;
810}
811
George Rimar884e7862016-09-08 08:19:13 +0000812template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000813 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000814}
815
George Rimar884e7862016-09-08 08:19:13 +0000816template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
817 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
818 return B->getVA<ELFT>();
819 error("symbol not found: " + S);
820 return 0;
821}
822
George Rimarf34f45f2016-09-23 13:17:23 +0000823template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
824 return Symtab<ELFT>::X->find(S) != nullptr;
825}
826
Eugene Leviantbbe38602016-07-19 09:25:43 +0000827// Returns indices of ELF headers containing specific section, identified
828// by Name. Each index is a zero based number of ELF header listed within
829// PHDRS {} script block.
830template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000831std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000832 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
833 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000834 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000835 continue;
836
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000837 std::vector<size_t> Ret;
838 for (StringRef PhdrName : Cmd->Phdrs)
839 Ret.push_back(getPhdrIndex(PhdrName));
840 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000841 }
George Rimar31d842f2016-07-20 16:43:03 +0000842 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000843}
844
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000845template <class ELFT>
846size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
847 size_t I = 0;
848 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
849 if (Cmd.Name == PhdrName)
850 return I;
851 ++I;
852 }
853 error("section header '" + PhdrName + "' is not listed in PHDRS");
854 return 0;
855}
856
Rui Ueyama07320e42016-04-20 20:13:41 +0000857class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000858 typedef void (ScriptParser::*Handler)();
859
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000860public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000861 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000862
George Rimar20b65982016-08-31 09:08:26 +0000863 void readLinkerScript();
864 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000865
866private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000867 void addFile(StringRef Path);
868
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000869 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000870 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000871 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000872 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000873 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000874 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000875 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000876 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000877 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000878 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000879 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000880 void readVersion();
881 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000882
Rui Ueyama113cdec2016-07-24 23:05:57 +0000883 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000884 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000885 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000886 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000887 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000888 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000889 InputSectionDescription *readInputSectionDescription(StringRef Tok);
George Rimarc91930a2016-09-02 21:17:20 +0000890 Regex readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000891 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000892 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000893 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000894 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000895 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000896 SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
George Rimar03fc0102016-07-28 07:18:23 +0000897 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000898 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000899
900 Expr readExpr();
901 Expr readExpr1(Expr Lhs, int MinPrec);
902 Expr readPrimary();
903 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000904 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000905
George Rimar20b65982016-08-31 09:08:26 +0000906 // For parsing version script.
907 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000908 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000909 void readGlobal(StringRef VerStr);
910 void readLocal();
911
Rui Ueyama07320e42016-04-20 20:13:41 +0000912 ScriptConfiguration &Opt = *ScriptConfig;
913 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000914 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000915};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000916
George Rimar20b65982016-08-31 09:08:26 +0000917void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000918 readVersionScriptCommand();
919 if (!atEOF())
920 setError("EOF expected, but got " + next());
921}
922
923void ScriptParser::readVersionScriptCommand() {
George Rimar20b65982016-08-31 09:08:26 +0000924 if (skip("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000925 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000926 return;
927 }
928
Rui Ueyama95769b42016-08-31 20:03:54 +0000929 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000930 StringRef VerStr = next();
931 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000932 setError("anonymous version definition is used in "
933 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000934 return;
935 }
936 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000937 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000938 }
939}
940
Rui Ueyama95769b42016-08-31 20:03:54 +0000941void ScriptParser::readVersion() {
942 expect("{");
943 readVersionScriptCommand();
944 expect("}");
945}
946
George Rimar20b65982016-08-31 09:08:26 +0000947void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000948 while (!atEOF()) {
949 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000950 if (Tok == ";")
951 continue;
952
Eugene Leviant20d03192016-09-16 15:30:47 +0000953 if (Tok == "ASSERT") {
954 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
955 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000956 readEntry();
957 } else if (Tok == "EXTERN") {
958 readExtern();
959 } else if (Tok == "GROUP" || Tok == "INPUT") {
960 readGroup();
961 } else if (Tok == "INCLUDE") {
962 readInclude();
963 } else if (Tok == "OUTPUT") {
964 readOutput();
965 } else if (Tok == "OUTPUT_ARCH") {
966 readOutputArch();
967 } else if (Tok == "OUTPUT_FORMAT") {
968 readOutputFormat();
969 } else if (Tok == "PHDRS") {
970 readPhdrs();
971 } else if (Tok == "SEARCH_DIR") {
972 readSearchDir();
973 } else if (Tok == "SECTIONS") {
974 readSections();
975 } else if (Tok == "VERSION") {
976 readVersion();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000977 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000978 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000979 } else {
George Rimar57610422016-03-11 14:43:02 +0000980 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000981 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000982 }
983}
984
Rui Ueyama717677a2016-02-11 21:17:59 +0000985void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000986 if (IsUnderSysroot && S.startswith("/")) {
987 SmallString<128> Path;
988 (Config->Sysroot + S).toStringRef(Path);
989 if (sys::fs::exists(Path)) {
990 Driver->addFile(Saver.save(Path.str()));
991 return;
992 }
993 }
994
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000995 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000996 Driver->addFile(S);
997 } else if (S.startswith("=")) {
998 if (Config->Sysroot.empty())
999 Driver->addFile(S.substr(1));
1000 else
1001 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1002 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001003 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001004 } else if (sys::fs::exists(S)) {
1005 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001006 } else {
1007 std::string Path = findFromSearchPaths(S);
1008 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001009 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001010 else
1011 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001012 }
1013}
1014
Rui Ueyama717677a2016-02-11 21:17:59 +00001015void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001016 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001017 bool Orig = Config->AsNeeded;
1018 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001019 while (!Error && !skip(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001020 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001021 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001022}
1023
Rui Ueyama717677a2016-02-11 21:17:59 +00001024void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001025 // -e <symbol> takes predecence over ENTRY(<symbol>).
1026 expect("(");
1027 StringRef Tok = next();
1028 if (Config->Entry.empty())
1029 Config->Entry = Tok;
1030 expect(")");
1031}
1032
Rui Ueyama717677a2016-02-11 21:17:59 +00001033void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001034 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001035 while (!Error && !skip(")"))
1036 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001037}
1038
Rui Ueyama717677a2016-02-11 21:17:59 +00001039void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001040 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001041 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001042 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001043 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001044 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001045 else
George Rimarcd574a52016-09-09 14:35:36 +00001046 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001047 }
1048}
1049
Rui Ueyama717677a2016-02-11 21:17:59 +00001050void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001051 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001052 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001053 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001054 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001055 return;
1056 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001057 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001058 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1059 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001060 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001061}
1062
Rui Ueyama717677a2016-02-11 21:17:59 +00001063void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001064 // -o <file> takes predecence over OUTPUT(<file>).
1065 expect("(");
1066 StringRef Tok = next();
1067 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001068 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001069 expect(")");
1070}
1071
Rui Ueyama717677a2016-02-11 21:17:59 +00001072void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001073 // Error checking only for now.
1074 expect("(");
1075 next();
1076 expect(")");
1077}
1078
Rui Ueyama717677a2016-02-11 21:17:59 +00001079void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001080 // Error checking only for now.
1081 expect("(");
1082 next();
Davide Italiano6836c612015-10-12 21:08:41 +00001083 StringRef Tok = next();
1084 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001085 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001086 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001087 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001088 return;
1089 }
Davide Italiano6836c612015-10-12 21:08:41 +00001090 next();
1091 expect(",");
1092 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001093 expect(")");
1094}
1095
Eugene Leviantbbe38602016-07-19 09:25:43 +00001096void ScriptParser::readPhdrs() {
1097 expect("{");
1098 while (!Error && !skip("}")) {
1099 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001100 Opt.PhdrsCommands.push_back(
1101 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001102 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1103
1104 PhdrCmd.Type = readPhdrType();
1105 do {
1106 Tok = next();
1107 if (Tok == ";")
1108 break;
1109 if (Tok == "FILEHDR")
1110 PhdrCmd.HasFilehdr = true;
1111 else if (Tok == "PHDRS")
1112 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001113 else if (Tok == "AT")
1114 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001115 else if (Tok == "FLAGS") {
1116 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001117 // Passing 0 for the value of dot is a bit of a hack. It means that
1118 // we accept expressions like ".|1".
1119 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001120 expect(")");
1121 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001122 setError("unexpected header attribute: " + Tok);
1123 } while (!Error);
1124 }
1125}
1126
Rui Ueyama717677a2016-02-11 21:17:59 +00001127void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001128 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001129 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001130 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001131 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001132 expect(")");
1133}
1134
Rui Ueyama717677a2016-02-11 21:17:59 +00001135void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001136 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001137 expect("{");
George Rimar652852c2016-04-16 10:10:32 +00001138 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001139 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001140 BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001141 if (!Cmd) {
1142 if (Tok == "ASSERT")
1143 Cmd = new AssertCommand(readAssert());
1144 else
1145 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001146 }
Rui Ueyama10416562016-08-04 02:03:27 +00001147 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001148 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001149}
1150
Rui Ueyama708019c2016-07-24 18:19:40 +00001151static int precedence(StringRef Op) {
1152 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001153 .Cases("*", "/", 5)
1154 .Cases("+", "-", 4)
1155 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001156 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001157 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001158 .Default(-1);
1159}
1160
George Rimarc91930a2016-09-02 21:17:20 +00001161Regex ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001162 std::vector<StringRef> V;
1163 while (!Error && !skip(")"))
1164 V.push_back(next());
George Rimarc91930a2016-09-02 21:17:20 +00001165 return compileGlobPatterns(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001166}
1167
George Rimarbe394db2016-09-16 20:21:55 +00001168SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama742c3832016-08-04 22:27:00 +00001169 if (skip("SORT") || skip("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001170 return SortSectionPolicy::Name;
Rui Ueyama742c3832016-08-04 22:27:00 +00001171 if (skip("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001172 return SortSectionPolicy::Alignment;
George Rimar575208c2016-09-15 19:15:12 +00001173 if (skip("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001174 return SortSectionPolicy::Priority;
George Rimarbe394db2016-09-16 20:21:55 +00001175 if (skip("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001176 return SortSectionPolicy::None;
1177 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001178}
1179
George Rimar395281c2016-09-16 17:42:10 +00001180// Method reads a list of sequence of excluded files and section globs given in
1181// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1182// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001183// The semantics of that is next:
1184// * Include .foo.1 from every file.
1185// * Include .foo.2 from every file but a.o
1186// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001187std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1188 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001189 while (!Error && peek() != ")") {
1190 Regex ExcludeFileRe;
George Rimar395281c2016-09-16 17:42:10 +00001191 if (skip("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001192 expect("(");
1193 ExcludeFileRe = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001194 }
1195
George Rimar601e9892016-09-21 08:53:21 +00001196 std::vector<StringRef> V;
1197 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1198 V.push_back(next());
1199
1200 if (!V.empty())
George Rimar07171f22016-09-21 15:56:44 +00001201 Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
George Rimar601e9892016-09-21 08:53:21 +00001202 else
1203 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001204 }
George Rimar07171f22016-09-21 15:56:44 +00001205 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001206}
1207
George Rimar07171f22016-09-21 15:56:44 +00001208// Section pattern grammar can have complex expressions, for example:
1209// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1210// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1211// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1212// This methods handles wrapping sequences of excluded files and section globs
1213// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001214InputSectionDescription *
1215ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001216 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001217 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001218 while (!HasError && !skip(")")) {
1219 SortSectionPolicy Outer = readSortKind();
1220 SortSectionPolicy Inner = SortSectionPolicy::Default;
1221 std::vector<SectionPattern> V;
1222 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001223 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001224 Inner = readSortKind();
1225 if (Inner != SortSectionPolicy::Default) {
1226 expect("(");
1227 V = readInputSectionsList();
1228 expect(")");
1229 } else {
1230 V = readInputSectionsList();
1231 }
George Rimar350ece42016-08-03 08:35:59 +00001232 expect(")");
1233 } else {
George Rimar07171f22016-09-21 15:56:44 +00001234 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001235 }
George Rimar0702c4e2016-07-29 15:32:46 +00001236
George Rimar07171f22016-09-21 15:56:44 +00001237 for (SectionPattern &Pat : V) {
1238 Pat.SortInner = Inner;
1239 Pat.SortOuter = Outer;
1240 }
1241
1242 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1243 }
Rui Ueyama10416562016-08-04 02:03:27 +00001244 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001245}
1246
George Rimara2496cb2016-08-30 09:46:59 +00001247InputSectionDescription *
1248ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001249 // Input section wildcard can be surrounded by KEEP.
1250 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001251 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001252 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001253 StringRef FilePattern = next();
1254 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001255 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001256 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001257 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001258 }
George Rimara2496cb2016-08-30 09:46:59 +00001259 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001260}
1261
George Rimar03fc0102016-07-28 07:18:23 +00001262void ScriptParser::readSort() {
1263 expect("(");
1264 expect("CONSTRUCTORS");
1265 expect(")");
1266}
1267
George Rimareefa7582016-08-04 09:29:31 +00001268Expr ScriptParser::readAssert() {
1269 expect("(");
1270 Expr E = readExpr();
1271 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001272 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001273 expect(")");
1274 return [=](uint64_t Dot) {
1275 uint64_t V = E(Dot);
1276 if (!V)
1277 error(Msg);
1278 return V;
1279 };
1280}
1281
Rui Ueyama25150e82016-09-06 17:46:43 +00001282// Reads a FILL(expr) command. We handle the FILL command as an
1283// alias for =fillexp section attribute, which is different from
1284// what GNU linkers do.
1285// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001286std::vector<uint8_t> ScriptParser::readFill() {
1287 expect("(");
1288 std::vector<uint8_t> V = readOutputSectionFiller(next());
1289 expect(")");
1290 expect(";");
1291 return V;
1292}
1293
Rui Ueyama10416562016-08-04 02:03:27 +00001294OutputSectionCommand *
1295ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001296 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001297
1298 // Read an address expression.
1299 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1300 if (peek() != ":")
1301 Cmd->AddrExpr = readExpr();
1302
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001303 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001304
George Rimar8ceadb32016-08-17 07:44:19 +00001305 if (skip("AT"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001306 Cmd->LmaExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001307 if (skip("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001308 Cmd->AlignExpr = readParenExpr();
George Rimardb24d9c2016-08-19 15:18:23 +00001309 if (skip("SUBALIGN"))
1310 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001311
Davide Italiano246f6812016-07-22 03:36:24 +00001312 // Parse constraints.
1313 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001314 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +00001315 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001316 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001317 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001318
Rui Ueyama025d59b2016-02-02 20:27:59 +00001319 while (!Error && !skip("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001320 StringRef Tok = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001321 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
Eugene Leviantceabe802016-08-11 07:56:43 +00001322 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001323 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1324 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001325 else if (Tok == "FILL")
1326 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001327 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001328 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001329 else if (peek() == "(")
1330 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001331 else
1332 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001333 }
George Rimar076fe152016-07-21 06:43:01 +00001334 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001335
1336 if (skip("="))
1337 Cmd->Filler = readOutputSectionFiller(next());
1338 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001339 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001340
Rui Ueyama10416562016-08-04 02:03:27 +00001341 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001342}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001343
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001344// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1345// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1346//
1347// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1348// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1349// as 32-bit big-endian values. We will do the same as ld.gold does
1350// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001351std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001352 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001353 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001354 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001355 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001356 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001357 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001358}
1359
Petr Hoseka35e39c2016-08-16 01:11:16 +00001360SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001361 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001362 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001363 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001364 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001365 expect(")");
1366 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001367 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001368}
1369
Eugene Leviantdb741e72016-09-07 07:08:43 +00001370SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1371 bool MakeAbsolute) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001372 SymbolAssignment *Cmd = nullptr;
1373 if (peek() == "=" || peek() == "+=") {
1374 Cmd = readAssignment(Tok);
1375 expect(";");
1376 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001377 Cmd = readProvideHidden(true, false);
1378 } else if (Tok == "HIDDEN") {
1379 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001380 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001381 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001382 }
Eugene Leviantdb741e72016-09-07 07:08:43 +00001383 if (Cmd && MakeAbsolute)
1384 Cmd->IsAbsolute = true;
Eugene Leviantceabe802016-08-11 07:56:43 +00001385 return Cmd;
1386}
1387
George Rimar30835ea2016-07-28 21:08:56 +00001388static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1389 if (S == ".")
1390 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001391 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001392}
1393
George Rimar30835ea2016-07-28 21:08:56 +00001394SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1395 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001396 bool IsAbsolute = false;
1397 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001398 assert(Op == "=" || Op == "+=");
Eugene Leviantdb741e72016-09-07 07:08:43 +00001399 if (skip("ABSOLUTE")) {
1400 E = readParenExpr();
1401 IsAbsolute = true;
1402 } else {
1403 E = readExpr();
1404 }
George Rimar30835ea2016-07-28 21:08:56 +00001405 if (Op == "+=")
1406 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001407 return new SymbolAssignment(Name, E, IsAbsolute);
George Rimar30835ea2016-07-28 21:08:56 +00001408}
1409
1410// This is an operator-precedence parser to parse a linker
1411// script expression.
1412Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1413
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001414static Expr combine(StringRef Op, Expr L, Expr R) {
1415 if (Op == "*")
1416 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1417 if (Op == "/") {
1418 return [=](uint64_t Dot) -> uint64_t {
1419 uint64_t RHS = R(Dot);
1420 if (RHS == 0) {
1421 error("division by zero");
1422 return 0;
1423 }
1424 return L(Dot) / RHS;
1425 };
1426 }
1427 if (Op == "+")
1428 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1429 if (Op == "-")
1430 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001431 if (Op == "<<")
1432 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1433 if (Op == ">>")
1434 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001435 if (Op == "<")
1436 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1437 if (Op == ">")
1438 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1439 if (Op == ">=")
1440 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1441 if (Op == "<=")
1442 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1443 if (Op == "==")
1444 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1445 if (Op == "!=")
1446 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1447 if (Op == "&")
1448 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001449 if (Op == "|")
1450 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001451 llvm_unreachable("invalid operator");
1452}
1453
Rui Ueyama708019c2016-07-24 18:19:40 +00001454// This is a part of the operator-precedence parser. This function
1455// assumes that the remaining token stream starts with an operator.
1456Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1457 while (!atEOF() && !Error) {
1458 // Read an operator and an expression.
1459 StringRef Op1 = peek();
1460 if (Op1 == "?")
1461 return readTernary(Lhs);
1462 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001463 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001464 next();
1465 Expr Rhs = readPrimary();
1466
1467 // Evaluate the remaining part of the expression first if the
1468 // next operator has greater precedence than the previous one.
1469 // For example, if we have read "+" and "3", and if the next
1470 // operator is "*", then we'll evaluate 3 * ... part first.
1471 while (!atEOF()) {
1472 StringRef Op2 = peek();
1473 if (precedence(Op2) <= precedence(Op1))
1474 break;
1475 Rhs = readExpr1(Rhs, precedence(Op2));
1476 }
1477
1478 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001479 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001480 return Lhs;
1481}
1482
1483uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001484 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001485 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001486 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001487 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001488 error("unknown constant: " + S);
1489 return 0;
1490}
1491
Rui Ueyama626e0b02016-09-02 18:19:00 +00001492// Parses Tok as an integer. Returns true if successful.
1493// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1494// and decimal numbers. Decimal numbers may have "K" (kilo) or
1495// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001496static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001497 if (Tok.startswith("-")) {
1498 if (!readInteger(Tok.substr(1), Result))
1499 return false;
1500 Result = -Result;
1501 return true;
1502 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001503 if (Tok.startswith_lower("0x"))
1504 return !Tok.substr(2).getAsInteger(16, Result);
1505 if (Tok.endswith_lower("H"))
1506 return !Tok.drop_back().getAsInteger(16, Result);
1507
1508 int Suffix = 1;
1509 if (Tok.endswith_lower("K")) {
1510 Suffix = 1024;
1511 Tok = Tok.drop_back();
1512 } else if (Tok.endswith_lower("M")) {
1513 Suffix = 1024 * 1024;
1514 Tok = Tok.drop_back();
1515 }
1516 if (Tok.getAsInteger(10, Result))
1517 return false;
1518 Result *= Suffix;
1519 return true;
1520}
1521
George Rimare38cbab2016-09-26 19:22:50 +00001522BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1523 int Size = StringSwitch<unsigned>(Tok)
1524 .Case("BYTE", 1)
1525 .Case("SHORT", 2)
1526 .Case("LONG", 4)
1527 .Case("QUAD", 8)
1528 .Default(-1);
1529 if (Size == -1)
1530 return nullptr;
1531
1532 expect("(");
1533 uint64_t Val = 0;
1534 StringRef S = next();
1535 if (!readInteger(S, Val))
1536 setError("unexpected value: " + S);
1537 expect(")");
1538 return new BytesDataCommand(Val, Size);
1539}
1540
Rui Ueyama708019c2016-07-24 18:19:40 +00001541Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001542 if (peek() == "(")
1543 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001544
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001545 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001546
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001547 if (Tok == "~") {
1548 Expr E = readPrimary();
1549 return [=](uint64_t Dot) { return ~E(Dot); };
1550 }
1551 if (Tok == "-") {
1552 Expr E = readPrimary();
1553 return [=](uint64_t Dot) { return -E(Dot); };
1554 }
1555
Rui Ueyama708019c2016-07-24 18:19:40 +00001556 // Built-in functions are parsed here.
1557 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001558 if (Tok == "ADDR") {
1559 expect("(");
1560 StringRef Name = next();
1561 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001562 return
1563 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001564 }
George Rimareefa7582016-08-04 09:29:31 +00001565 if (Tok == "ASSERT")
1566 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001567 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001568 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001569 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1570 }
1571 if (Tok == "CONSTANT") {
1572 expect("(");
1573 StringRef Tok = next();
1574 expect(")");
1575 return [=](uint64_t Dot) { return getConstant(Tok); };
1576 }
George Rimarf34f45f2016-09-23 13:17:23 +00001577 if (Tok == "DEFINED") {
1578 expect("(");
1579 StringRef Tok = next();
1580 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001581 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001582 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001583 if (Tok == "SEGMENT_START") {
1584 expect("(");
1585 next();
1586 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001587 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001588 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001589 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001590 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001591 if (Tok == "DATA_SEGMENT_ALIGN") {
1592 expect("(");
1593 Expr E = readExpr();
1594 expect(",");
1595 readExpr();
1596 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001597 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001598 }
1599 if (Tok == "DATA_SEGMENT_END") {
1600 expect("(");
1601 expect(".");
1602 expect(")");
1603 return [](uint64_t Dot) { return Dot; };
1604 }
George Rimar276b4e62016-07-26 17:58:44 +00001605 // GNU linkers implements more complicated logic to handle
1606 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1607 // the next page boundary for simplicity.
1608 if (Tok == "DATA_SEGMENT_RELRO_END") {
1609 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001610 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001611 expect(",");
1612 readExpr();
1613 expect(")");
1614 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1615 }
George Rimar9e694502016-07-29 16:18:47 +00001616 if (Tok == "SIZEOF") {
1617 expect("(");
1618 StringRef Name = next();
1619 expect(")");
George Rimar884e7862016-09-08 08:19:13 +00001620 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001621 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001622 if (Tok == "ALIGNOF") {
1623 expect("(");
1624 StringRef Name = next();
1625 expect(")");
1626 return
1627 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1628 }
George Rimare32a3592016-08-10 07:59:34 +00001629 if (Tok == "SIZEOF_HEADERS")
George Rimar884e7862016-09-08 08:19:13 +00001630 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001631
George Rimar9f2f7ad2016-09-02 16:01:42 +00001632 // Tok is a literal number.
1633 uint64_t V;
1634 if (readInteger(Tok, V))
1635 return [=](uint64_t Dot) { return V; };
1636
1637 // Tok is a symbol name.
1638 if (Tok != "." && !isValidCIdentifier(Tok))
1639 setError("malformed number: " + Tok);
1640 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001641}
1642
1643Expr ScriptParser::readTernary(Expr Cond) {
1644 next();
1645 Expr L = readExpr();
1646 expect(":");
1647 Expr R = readExpr();
1648 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1649}
1650
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001651Expr ScriptParser::readParenExpr() {
1652 expect("(");
1653 Expr E = readExpr();
1654 expect(")");
1655 return E;
1656}
1657
Eugene Leviantbbe38602016-07-19 09:25:43 +00001658std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1659 std::vector<StringRef> Phdrs;
1660 while (!Error && peek().startswith(":")) {
1661 StringRef Tok = next();
1662 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1663 if (Tok.empty()) {
1664 setError("section header name is empty");
1665 break;
1666 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001667 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001668 }
1669 return Phdrs;
1670}
1671
1672unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001673 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001674 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001675 .Case("PT_NULL", PT_NULL)
1676 .Case("PT_LOAD", PT_LOAD)
1677 .Case("PT_DYNAMIC", PT_DYNAMIC)
1678 .Case("PT_INTERP", PT_INTERP)
1679 .Case("PT_NOTE", PT_NOTE)
1680 .Case("PT_SHLIB", PT_SHLIB)
1681 .Case("PT_PHDR", PT_PHDR)
1682 .Case("PT_TLS", PT_TLS)
1683 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1684 .Case("PT_GNU_STACK", PT_GNU_STACK)
1685 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1686 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001687
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001688 if (Ret == (unsigned)-1) {
1689 setError("invalid program header type: " + Tok);
1690 return PT_NULL;
1691 }
1692 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001693}
1694
Rui Ueyama95769b42016-08-31 20:03:54 +00001695void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001696 // Identifiers start at 2 because 0 and 1 are reserved
1697 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1698 size_t VersionId = Config->VersionDefinitions.size() + 2;
1699 Config->VersionDefinitions.push_back({VerStr, VersionId});
1700
1701 if (skip("global:") || peek() != "local:")
1702 readGlobal(VerStr);
1703 if (skip("local:"))
1704 readLocal();
1705 expect("}");
1706
1707 // Each version may have a parent version. For example, "Ver2" defined as
1708 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1709 // version hierarchy is, probably against your instinct, purely for human; the
1710 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1711 if (!VerStr.empty() && peek() != ";")
1712 next();
1713 expect(";");
1714}
1715
1716void ScriptParser::readLocal() {
1717 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1718 expect("*");
1719 expect(";");
1720}
1721
1722void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001723 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001724 expect("{");
1725
1726 for (;;) {
1727 if (peek() == "}" || Error)
1728 break;
George Rimarcd574a52016-09-09 14:35:36 +00001729 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1730 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001731 expect(";");
1732 }
1733
1734 expect("}");
1735 expect(";");
1736}
1737
1738void ScriptParser::readGlobal(StringRef VerStr) {
1739 std::vector<SymbolVersion> *Globals;
1740 if (VerStr.empty())
1741 Globals = &Config->VersionScriptGlobals;
1742 else
1743 Globals = &Config->VersionDefinitions.back().Globals;
1744
1745 for (;;) {
1746 if (skip("extern"))
1747 readExtern(Globals);
1748
1749 StringRef Cur = peek();
1750 if (Cur == "}" || Cur == "local:" || Error)
1751 return;
1752 next();
George Rimarcd574a52016-09-09 14:35:36 +00001753 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001754 expect(";");
1755 }
1756}
1757
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001758static bool isUnderSysroot(StringRef Path) {
1759 if (Config->Sysroot == "")
1760 return false;
1761 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1762 if (sys::fs::equivalent(Config->Sysroot, Path))
1763 return true;
1764 return false;
1765}
1766
Rui Ueyama07320e42016-04-20 20:13:41 +00001767void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001768 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001769 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1770}
1771
1772void elf::readVersionScript(MemoryBufferRef MB) {
1773 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001774}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001775
Rui Ueyama07320e42016-04-20 20:13:41 +00001776template class elf::LinkerScript<ELF32LE>;
1777template class elf::LinkerScript<ELF32BE>;
1778template class elf::LinkerScript<ELF64LE>;
1779template class elf::LinkerScript<ELF64BE>;