blob: 6b8e39dc832668dfd12051665302b880793d26de [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"
Rui Ueyama55518e72016-10-28 20:57:25 +000024#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000025#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000026#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000027#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000029#include "Symbols.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000030#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000031#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000032#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000033#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000034#include "llvm/Support/FileSystem.h"
35#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000036#include "llvm/Support/Path.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) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000049 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, nullptr,
Rafael Espindola093abab2016-10-27 17:45:40 +000051 STB_GLOBAL, STT_NOTYPE, 0);
Rui Ueyama16024212016-08-11 23:22:52 +000052 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000053
54 // If we have no SECTIONS then we don't have '.' and don't call
55 // assignAddresses(). We calculate symbol value immediately in this case.
56 if (!ScriptConfig->HasSections)
57 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000058}
59
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000060template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000061 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
62 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000063 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000064}
65
Eugene Leviantdb741e72016-09-07 07:08:43 +000066template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000067 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000068 addRegular<ELFT>(Cmd);
69 else
70 addSynthetic<ELFT>(Cmd);
71}
Rui Ueyama16024212016-08-11 23:22:52 +000072// If a symbol was in PROVIDE(), we need to define it only when
73// it is an undefined symbol.
74template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
75 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000076 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000077 if (!Cmd->Provide)
78 return true;
79 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
80 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000081}
82
George Rimar076fe152016-07-21 06:43:01 +000083bool SymbolAssignment::classof(const BaseCommand *C) {
84 return C->Kind == AssignmentKind;
85}
86
87bool OutputSectionCommand::classof(const BaseCommand *C) {
88 return C->Kind == OutputSectionKind;
89}
90
George Rimareea31142016-07-21 14:26:59 +000091bool InputSectionDescription::classof(const BaseCommand *C) {
92 return C->Kind == InputSectionKind;
93}
94
George Rimareefa7582016-08-04 09:29:31 +000095bool AssertCommand::classof(const BaseCommand *C) {
96 return C->Kind == AssertKind;
97}
98
George Rimare38cbab2016-09-26 19:22:50 +000099bool BytesDataCommand::classof(const BaseCommand *C) {
100 return C->Kind == BytesDataKind;
101}
102
Rui Ueyama36a153c2016-07-23 14:09:58 +0000103template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000104 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000105}
106
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000107template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
108template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
109
Rui Ueyama07320e42016-04-20 20:13:41 +0000110template <class ELFT>
111bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000112 for (InputSectionDescription *ID : Opt.KeptSections) {
113 StringRef Filename = S->getFile()->getName();
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000114 if (!ID->FilePat.match(sys::path::filename(Filename)))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000115 continue;
Rui Ueyamab66260a2016-10-05 20:09:50 +0000116
117 for (SectionPattern &P : ID->SectionPatterns)
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000118 if (P.SectionPat.match(S->Name))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000119 return true;
120 }
George Rimareea31142016-07-21 14:26:59 +0000121 return false;
122}
123
George Rimar575208c2016-09-15 19:15:12 +0000124static bool comparePriority(InputSectionData *A, InputSectionData *B) {
125 return getPriority(A->Name) < getPriority(B->Name);
126}
127
Rafael Espindolac0028d32016-09-08 20:47:52 +0000128static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000129 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000130}
George Rimar350ece42016-08-03 08:35:59 +0000131
Rafael Espindolac0028d32016-09-08 20:47:52 +0000132static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000133 // ">" is not a mistake. Larger alignments are placed before smaller
134 // alignments in order to reduce the amount of padding necessary.
135 // This is compatible with GNU.
136 return A->Alignment > B->Alignment;
137}
George Rimar350ece42016-08-03 08:35:59 +0000138
Rafael Espindolac0028d32016-09-08 20:47:52 +0000139static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000140getComparator(SortSectionPolicy K) {
141 switch (K) {
142 case SortSectionPolicy::Alignment:
143 return compareAlignment;
144 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000145 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000146 case SortSectionPolicy::Priority:
147 return comparePriority;
148 default:
149 llvm_unreachable("unknown sort policy");
150 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000151}
George Rimar0702c4e2016-07-29 15:32:46 +0000152
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000153template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000154static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000155 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000156 if (Kind == ConstraintKind::NoConstraint)
157 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000158 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000159 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000160 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000161 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000162 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
163 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000164}
165
George Rimar07171f22016-09-21 15:56:44 +0000166static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000167 SortSectionPolicy K) {
168 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000169 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000170}
171
Rafael Espindolad3190792016-09-16 15:10:23 +0000172// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000173template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000174void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000175 // Collects all sections that satisfy constraints of I
176 // and attach them to I.
177 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000178 size_t SizeBefore = I->Sections.size();
George Rimar395281c2016-09-16 17:42:10 +0000179 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000180 StringRef Filename = sys::path::filename(F->getName());
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000181 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000182 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000183
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000184 for (InputSectionBase<ELFT> *S : F->getSections())
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000185 if (!isDiscarded(S) && !S->OutSec && Pat.SectionPat.match(S->Name))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000186 I->Sections.push_back(S);
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000187 if (Pat.SectionPat.match("COMMON"))
Rafael Espindola0e090522016-10-26 00:54:03 +0000188 I->Sections.push_back(InputSection<ELFT>::CommonInputSection);
George Rimar395281c2016-09-16 17:42:10 +0000189 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000190
George Rimar07171f22016-09-21 15:56:44 +0000191 // Sort sections as instructed by SORT-family commands and --sort-section
192 // option. Because SORT-family commands can be nested at most two depth
193 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
194 // line option is respected even if a SORT command is given, the exact
195 // behavior we have here is a bit complicated. Here are the rules.
196 //
197 // 1. If two SORT commands are given, --sort-section is ignored.
198 // 2. If one SORT command is given, and if it is not SORT_NONE,
199 // --sort-section is handled as an inner SORT command.
200 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
201 // 4. If no SORT command is given, sort according to --sort-section.
202 InputSectionData **Begin = I->Sections.data() + SizeBefore;
203 InputSectionData **End = I->Sections.data() + I->Sections.size();
204 if (Pat.SortOuter != SortSectionPolicy::None) {
205 if (Pat.SortInner == SortSectionPolicy::Default)
206 sortSections(Begin, End, Config->SortSection);
207 else
208 sortSections(Begin, End, Pat.SortInner);
209 sortSections(Begin, End, Pat.SortOuter);
210 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000211 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000212
213 // We do not add duplicate input sections, so mark them with a dummy output
214 // section for now.
215 for (InputSectionData *S : I->Sections) {
216 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
217 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
218 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000219}
220
221template <class ELFT>
222void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
223 for (InputSectionBase<ELFT> *S : V) {
224 S->Live = false;
225 reportDiscarded(S);
226 }
227}
228
George Rimar06ae6832016-08-12 09:07:57 +0000229template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000230std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000231LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000232 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000233
George Rimar06ae6832016-08-12 09:07:57 +0000234 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000235 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
236 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000237 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000238 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000239 for (InputSectionData *S : Cmd->Sections)
240 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000241 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000242
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000243 // After we created final list we should now set OutSec pointer to null,
George Rimara4c7e742016-10-20 08:36:42 +0000244 // instead of -1. Otherwise we may get a crash when writing relocs, in
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000245 // case section is discarded by linker script
246 for (InputSectionBase<ELFT> *S : Ret)
247 S->OutSec = nullptr;
248
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000249 return Ret;
250}
251
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000252template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000253static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
254 StringRef OutsecName) {
255 // When using linker script the merge rules are different.
256 // Unfortunately, linker scripts are name based. This means that expressions
257 // like *(.foo*) can refer to multiple input sections that would normally be
258 // placed in different output sections. We cannot put them in different
259 // output sections or we would produce wrong results for
260 // start = .; *(.foo.*) end = .; *(.bar)
261 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
262 // another. The problem is that there is no way to layout those output
263 // sections such that the .foo sections are the only thing between the
264 // start and end symbols.
265
266 // An extra annoyance is that we cannot simply disable merging of the contents
267 // of SHF_MERGE sections, but our implementation requires one output section
268 // per "kind" (string or not, which size/aligment).
269 // Fortunately, creating symbols in the middle of a merge section is not
270 // supported by bfd or gold, so we can just create multiple section in that
271 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000272 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000273 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000274
275 uintX_t Alignment = 0;
276 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000277 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000278
279 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
280}
281
282template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000283void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
284 InputSectionBase<ELFT> *Sec,
285 StringRef Name) {
286 OutputSectionBase<ELFT> *OutSec;
287 bool IsNew;
288 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
289 if (IsNew)
290 OutputSections->push_back(OutSec);
291 OutSec->addSection(Sec);
292}
293
294template <class ELFT>
295void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola28c15972016-09-13 13:00:06 +0000296
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000297 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
298 auto Iter = Opt.Commands.begin() + I;
299 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000300 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
301 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000302 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000303 continue;
304 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000305 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
306 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000307 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000308 // will not be called, so ASSERT should be evaluated now.
309 if (!Opt.HasSections)
310 Cmd->Expression(0);
311 continue;
312 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000313
Eugene Leviantceabe802016-08-11 07:56:43 +0000314 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000315 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
316
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000317 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000318 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000319 continue;
320 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000321
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000322 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
323 for (InputSectionBase<ELFT> *S : V)
324 S->OutSec = nullptr;
325 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000326 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000327 continue;
328 }
329
330 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
331 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
332 if (shouldDefine<ELFT>(OutCmd))
333 addSymbol<ELFT>(OutCmd);
334
Eugene Leviant97403d12016-09-01 09:55:57 +0000335 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000336 continue;
337
George Rimardb24d9c2016-08-19 15:18:23 +0000338 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000339 addSection(Factory, Sec, Cmd->Name);
340 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000341 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000342 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000343 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000344 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000345}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000346
Eugene Leviant20d03192016-09-16 15:30:47 +0000347template <class ELFT>
348void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
349 processCommands(Factory);
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000350 // Add orphan sections.
Eugene Leviant20d03192016-09-16 15:30:47 +0000351 for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
352 for (InputSectionBase<ELFT> *S : F->getSections())
353 if (!isDiscarded(S) && !S->OutSec)
Rui Ueyama55518e72016-10-28 20:57:25 +0000354 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000355}
356
Eugene Leviantdb741e72016-09-07 07:08:43 +0000357// Sets value of a section-defined symbol. Two kinds of
358// symbols are processed: synthetic symbols, whose value
359// is an offset from beginning of section and regular
360// symbols whose value is absolute.
361template <class ELFT>
362static void assignSectionSymbol(SymbolAssignment *Cmd,
363 OutputSectionBase<ELFT> *Sec,
Rafael Espindola498ed712016-10-31 14:44:41 +0000364 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000365 if (!Cmd->Sym)
366 return;
367
368 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
369 Body->Section = Sec;
Rafael Espindola498ed712016-10-31 14:44:41 +0000370 Body->Value = Cmd->Expression(Value) - Sec->getVA();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000371 return;
372 }
373 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000374 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000375}
376
Rafael Espindolaa940e532016-09-22 12:35:44 +0000377template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
378 return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
379}
380
Rafael Espindolad3190792016-09-16 15:10:23 +0000381template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
382 if (!AlreadyOutputIS.insert(S).second)
383 return;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000384 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000385
Rafael Espindolad3190792016-09-16 15:10:23 +0000386 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
387 Pos = alignTo(Pos, S->Alignment);
388 S->OutSecOff = Pos - CurOutSec->getVA();
389 Pos += S->getSize();
390
391 // Update output section size after adding each section. This is so that
392 // SIZEOF works correctly in the case below:
393 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
394 CurOutSec->setSize(Pos - CurOutSec->getVA());
395
Rafael Espindola7252ae52016-09-22 12:00:08 +0000396 if (IsTbss)
397 ThreadBssOffset = Pos - Dot;
398 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000399 Dot = Pos;
400}
401
402template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000403 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
404 return;
405 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000406 for (InputSection<ELFT> *I : OutSec->Sections)
407 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000408 } else {
409 Dot += CurOutSec->getSize();
Eugene Leviant20889c52016-08-31 08:13:33 +0000410 }
411}
412
413template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000414void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
415 if (CurOutSec == Sec)
416 return;
417 if (AlreadyOutputOS.count(Sec))
418 return;
419
420 flush();
421 CurOutSec = Sec;
422
423 Dot = alignTo(Dot, CurOutSec->getAlignment());
Rafael Espindolaa940e532016-09-22 12:35:44 +0000424 CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000425
426 // If neither AT nor AT> is specified for an allocatable section, the linker
427 // will set the LMA such that the difference between VMA and LMA for the
428 // section is the same as the preceding output section in the same region
429 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
430 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000431}
432
433template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000434 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000435 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
436 if (AssignCmd->Name == ".") {
437 // Update to location counter means update to section size.
438 Dot = AssignCmd->Expression(Dot);
439 CurOutSec->setSize(Dot - CurOutSec->getVA());
440 return;
441 }
Rafael Espindola498ed712016-10-31 14:44:41 +0000442 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000443 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000444 }
George Rimare38cbab2016-09-26 19:22:50 +0000445
446 // Handle BYTE(), SHORT(), LONG(), or QUAD().
447 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
448 DataCmd->Offset = Dot - CurOutSec->getVA();
449 Dot += DataCmd->Size;
450 CurOutSec->setSize(Dot - CurOutSec->getVA());
451 return;
452 }
453
454 // It handles single input section description command,
455 // calculates and assigns the offsets for each section and also
456 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000457 auto &ICmd = cast<InputSectionDescription>(Base);
458 for (InputSectionData *ID : ICmd.Sections) {
459 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
460 switchTo(IB->OutSec);
461 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
462 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000463 else
464 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000465 }
466}
467
George Rimar8f66df92016-08-12 20:38:20 +0000468template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000469static std::vector<OutputSectionBase<ELFT> *>
Eugene Leviant92577642016-10-10 11:23:12 +0000470findSections(StringRef Name,
Rafael Espindolad3190792016-09-16 15:10:23 +0000471 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000472 std::vector<OutputSectionBase<ELFT> *> Ret;
473 for (OutputSectionBase<ELFT> *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000474 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000475 Ret.push_back(Sec);
476 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000477}
478
Rafael Espindolad3190792016-09-16 15:10:23 +0000479template <class ELFT>
480void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000481 if (Cmd->LMAExpr)
482 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000483 std::vector<OutputSectionBase<ELFT> *> Sections =
Eugene Leviant92577642016-10-10 11:23:12 +0000484 findSections(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000485 if (Sections.empty())
486 return;
487 switchTo(Sections[0]);
Rafael Espindolad3190792016-09-16 15:10:23 +0000488 // Find the last section output location. We will output orphan sections
489 // there so that end symbols point to the correct location.
490 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
491 [](const std::unique_ptr<BaseCommand> &Cmd) {
492 return !isa<SymbolAssignment>(*Cmd);
493 })
494 .base();
495 for (auto I = Cmd->Commands.begin(); I != E; ++I)
496 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000497 for (OutputSectionBase<ELFT> *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000498 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000499 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000500 std::for_each(E, Cmd->Commands.end(),
501 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000502}
503
Rafael Espindola9546fff2016-09-22 14:40:50 +0000504template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000505 // It is common practice to use very generic linker scripts. So for any
506 // given run some of the output sections in the script will be empty.
507 // We could create corresponding empty output sections, but that would
508 // clutter the output.
509 // We instead remove trivially empty sections. The bfd linker seems even
510 // more aggressive at removing them.
511 auto Pos = std::remove_if(
512 Opt.Commands.begin(), Opt.Commands.end(),
513 [&](const std::unique_ptr<BaseCommand> &Base) {
514 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
515 if (!Cmd)
516 return false;
517 std::vector<OutputSectionBase<ELFT> *> Secs =
Eugene Leviant92577642016-10-10 11:23:12 +0000518 findSections(Cmd->Name, *OutputSections);
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000519 if (!Secs.empty())
520 return false;
521 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
522 if (!isa<InputSectionDescription>(I.get()))
523 return false;
524 return true;
525 });
526 Opt.Commands.erase(Pos, Opt.Commands.end());
527
Rafael Espindola9546fff2016-09-22 14:40:50 +0000528 // If the output section contains only symbol assignments, create a
529 // corresponding output section. The bfd linker seems to only create them if
530 // '.' is assigned to, but creating these section should not have any bad
531 // consequeces and gives us a section to put the symbol in.
532 uintX_t Flags = SHF_ALLOC;
533 uint32_t Type = 0;
534 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
535 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
536 if (!Cmd)
537 continue;
538 std::vector<OutputSectionBase<ELFT> *> Secs =
Eugene Leviant92577642016-10-10 11:23:12 +0000539 findSections(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000540 if (!Secs.empty()) {
541 Flags = Secs[0]->getFlags();
542 Type = Secs[0]->getType();
543 continue;
544 }
545
Rui Ueyama95642b92016-11-01 23:09:07 +0000546 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000547 OutputSections->push_back(OutSec);
548 }
549}
550
Rafael Espindola15c57952016-09-22 18:05:49 +0000551// When placing orphan sections, we want to place them after symbol assignments
552// so that an orphan after
553// begin_foo = .;
554// foo : { *(foo) }
555// end_foo = .;
556// doesn't break the intended meaning of the begin/end symbols.
557// We don't want to go over sections since Writer<ELFT>::sortSections is the
558// one in charge of deciding the order of the sections.
559// We don't want to go over alignments, since doing so in
560// rx_sec : { *(rx_sec) }
561// . = ALIGN(0x1000);
562// /* The RW PT_LOAD starts here*/
563// rw_sec : { *(rw_sec) }
564// would mean that the RW PT_LOAD would become unaligned.
565static bool shouldSkip(const BaseCommand &Cmd) {
566 if (isa<OutputSectionCommand>(Cmd))
567 return false;
568 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
569 if (!Assign)
570 return true;
571 return Assign->Name != ".";
572}
573
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000574template <class ELFT>
575void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
George Rimar652852c2016-04-16 10:10:32 +0000576 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000577 // are not explicitly placed into the output file by the linker script.
578 // We place orphan sections at end of file.
579 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000580 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000581
582 // The OutputSections are already in the correct order.
583 // This loops creates or moves commands as needed so that they are in the
584 // correct order.
585 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000586 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000587 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000588
589 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000590 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000591 auto CmdIter = Opt.Commands.begin() + CmdIndex;
592 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000593 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000594 ++CmdIter;
595 ++CmdIndex;
596 }
597
598 auto Pos =
599 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
600 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
601 return Cmd && Cmd->Name == Name;
602 });
603 if (Pos == E) {
604 Opt.Commands.insert(CmdIter,
605 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000606 ++CmdIndex;
607 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000608 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000609
610 // Continue from where we found it.
611 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
612 continue;
George Rimar652852c2016-04-16 10:10:32 +0000613 }
George Rimar652852c2016-04-16 10:10:32 +0000614
Rui Ueyama7c18c282016-04-18 21:00:40 +0000615 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000616 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000617
George Rimar076fe152016-07-21 06:43:01 +0000618 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
619 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000620 if (Cmd->Name == ".") {
621 Dot = Cmd->Expression(Dot);
622 } else if (Cmd->Sym) {
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000623 assignSectionSymbol(Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0],
624 Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000625 }
George Rimar652852c2016-04-16 10:10:32 +0000626 continue;
627 }
628
George Rimareefa7582016-08-04 09:29:31 +0000629 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
630 Cmd->Expression(Dot);
631 continue;
632 }
633
George Rimar076fe152016-07-21 06:43:01 +0000634 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000635
Rafael Espindolad3190792016-09-16 15:10:23 +0000636 if (Cmd->AddrExpr)
637 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000638
Rafael Espindolad3190792016-09-16 15:10:23 +0000639 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000640 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000641
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000642 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
643 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
644 if (Sec->getFlags() & SHF_ALLOC)
645 MinVA = std::min(MinVA, Sec->getVA());
646 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000647 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000648 }
649
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000650 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000651 auto FirstPTLoad =
652 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
653 return E.H.p_type == PT_LOAD;
654 });
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000655
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000656 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000657 // If linker script specifies program headers and first PT_LOAD doesn't
658 // have both PHDRS and FILEHDR attributes then do nothing
659 if (!Opt.PhdrsCommands.empty()) {
660 size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
661 if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
662 !Opt.PhdrsCommands[SegNum].HasFilehdr)
663 return;
664 }
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000665 // ELF and Program headers need to be right before the first section in
666 // memory. Set their addresses accordingly.
667 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
668 Out<ELFT>::ElfHeader->setVA(MinVA);
669 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
670 FirstPTLoad->First = Out<ELFT>::ElfHeader;
671 if (!FirstPTLoad->Last)
672 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000673 } else if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000674 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000675 // This happens if (all conditions met):
676 // - Linker script is used
677 // - First section in ELF image is not RO
678 // - Not enough space for program headers.
679 // The code below removes empty PT_LOAD segment and updates
680 // program headers size.
681 Phdrs.erase(FirstPTLoad);
682 Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
683 Phdrs.size());
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000684 }
George Rimar652852c2016-04-16 10:10:32 +0000685}
686
Rui Ueyama464daad2016-08-22 04:55:20 +0000687// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000688template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000689std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000690 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000691
Rui Ueyama464daad2016-08-22 04:55:20 +0000692 // Process PHDRS and FILEHDR keywords because they are not
693 // real output sections and cannot be added in the following loop.
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000694 std::vector<size_t> DefPhdrIds;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000695 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000696 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
697 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000698
699 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000700 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000701 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000702 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000703
704 if (Cmd.LMAExpr) {
705 Phdr.H.p_paddr = Cmd.LMAExpr(0);
706 Phdr.HasLMA = true;
707 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000708
709 // If output section command doesn't specify any segments,
710 // and we haven't previously assigned any section to segment,
711 // then we simply assign section to the very first load segment.
712 // Below is an example of such linker script:
713 // PHDRS { seg PT_LOAD; }
714 // SECTIONS { .aaa : { *(.aaa) } }
715 if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
716 DefPhdrIds.push_back(Ret.size() - 1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000717 }
718
Rui Ueyama464daad2016-08-22 04:55:20 +0000719 // Add output sections to program headers.
Rui Ueyama464daad2016-08-22 04:55:20 +0000720 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000721 if (!(Sec->getFlags() & SHF_ALLOC))
722 break;
723
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000724 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000725 if (PhdrIds.empty())
726 PhdrIds = std::move(DefPhdrIds);
727
728 // Assign headers specified by linker script
729 for (size_t Id : PhdrIds) {
730 Ret[Id].add(Sec);
731 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
732 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000733 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000734 DefPhdrIds = std::move(PhdrIds);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000735 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000736 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000737}
738
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000739template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
740 // Ignore .interp section in case we have PHDRS specification
741 // and PT_INTERP isn't listed.
742 return !Opt.PhdrsCommands.empty() &&
743 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
744 return Cmd.Type == PT_INTERP;
745 }) == Opt.PhdrsCommands.end();
746}
747
Eugene Leviantbbe38602016-07-19 09:25:43 +0000748template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000749ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000750 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
751 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
752 if (Cmd->Name == Name)
753 return Cmd->Filler;
754 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000755}
756
George Rimare38cbab2016-09-26 19:22:50 +0000757template <class ELFT>
758static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
759 const endianness E = ELFT::TargetEndianness;
760
761 switch (Size) {
762 case 1:
763 *Buf = (uint8_t)Data;
764 break;
765 case 2:
766 write16<E>(Buf, Data);
767 break;
768 case 4:
769 write32<E>(Buf, Data);
770 break;
771 case 8:
772 write64<E>(Buf, Data);
773 break;
774 default:
775 llvm_unreachable("unsupported Size argument");
776 }
777}
778
779template <class ELFT>
780void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
781 int I = getSectionIndex(Name);
782 if (I == INT_MAX)
783 return;
784
785 OutputSectionCommand *Cmd =
786 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
787 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
788 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
789 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
790}
791
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000792template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000793 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
794 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000795 if (Cmd->LMAExpr && Cmd->Name == Name)
796 return true;
797 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000798}
799
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000800// Returns the index of the given section name in linker script
801// SECTIONS commands. Sections are laid out as the same order as they
802// were in the script. If a given name did not appear in the script,
803// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000804template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000805 int I = 0;
806 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
807 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
808 if (Cmd->Name == Name)
809 return I;
810 ++I;
811 }
812 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000813}
814
Eugene Leviantbbe38602016-07-19 09:25:43 +0000815template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
816 return !Opt.PhdrsCommands.empty();
817}
818
George Rimar9e694502016-07-29 16:18:47 +0000819template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000820uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000821 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
822 if (Sec->getName() == Name)
823 return Sec->getVA();
824 error("undefined section " + Name);
825 return 0;
826}
827
828template <class ELFT>
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000829uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
830 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
831 if (Sec->getName() == Name)
832 return Sec->getLMA();
833 error("undefined section " + Name);
834 return 0;
835}
836
837template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000838uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000839 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
840 if (Sec->getName() == Name)
841 return Sec->getSize();
842 error("undefined section " + Name);
843 return 0;
844}
845
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000846template <class ELFT>
847uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
848 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
849 if (Sec->getName() == Name)
850 return Sec->getAlignment();
851 error("undefined section " + Name);
852 return 0;
853}
854
George Rimar884e7862016-09-08 08:19:13 +0000855template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000856 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000857}
858
George Rimar884e7862016-09-08 08:19:13 +0000859template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
860 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
861 return B->getVA<ELFT>();
862 error("symbol not found: " + S);
863 return 0;
864}
865
George Rimarf34f45f2016-09-23 13:17:23 +0000866template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
867 return Symtab<ELFT>::X->find(S) != nullptr;
868}
869
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000870template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
871 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
872 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
873 return DR && !DR->Section;
874}
875
Eugene Leviantbbe38602016-07-19 09:25:43 +0000876// Returns indices of ELF headers containing specific section, identified
877// by Name. Each index is a zero based number of ELF header listed within
878// PHDRS {} script block.
879template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000880std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000881 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
882 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000883 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000884 continue;
885
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000886 std::vector<size_t> Ret;
887 for (StringRef PhdrName : Cmd->Phdrs)
888 Ret.push_back(getPhdrIndex(PhdrName));
889 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000890 }
George Rimar31d842f2016-07-20 16:43:03 +0000891 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000892}
893
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000894template <class ELFT>
895size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
896 size_t I = 0;
897 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
898 if (Cmd.Name == PhdrName)
899 return I;
900 ++I;
901 }
902 error("section header '" + PhdrName + "' is not listed in PHDRS");
903 return 0;
904}
905
Rui Ueyama07320e42016-04-20 20:13:41 +0000906class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000907 typedef void (ScriptParser::*Handler)();
908
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000909public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000910 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000911
George Rimar20b65982016-08-31 09:08:26 +0000912 void readLinkerScript();
913 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000914
915private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000916 void addFile(StringRef Path);
917
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000918 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000919 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000920 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000921 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000922 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000923 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000924 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000925 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000926 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000927 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000928 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000929 void readVersion();
930 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000931
Rui Ueyama113cdec2016-07-24 23:05:57 +0000932 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000933 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000934 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000935 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000936 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000937 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000938 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000939 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000940 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000941 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000942 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000943 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000944 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000945 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000946 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000947 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000948
949 Expr readExpr();
950 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000951 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000952 Expr readPrimary();
953 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000954 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000955
George Rimar20b65982016-08-31 09:08:26 +0000956 // For parsing version script.
957 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000958 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000959 void readGlobal(StringRef VerStr);
960 void readLocal();
961
Rui Ueyama07320e42016-04-20 20:13:41 +0000962 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000963 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000964};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000965
George Rimar20b65982016-08-31 09:08:26 +0000966void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000967 readVersionScriptCommand();
968 if (!atEOF())
969 setError("EOF expected, but got " + next());
970}
971
972void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +0000973 if (consume("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000974 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000975 return;
976 }
977
Rui Ueyama95769b42016-08-31 20:03:54 +0000978 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +0000979 StringRef VerStr = next();
980 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +0000981 setError("anonymous version definition is used in "
982 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +0000983 return;
984 }
985 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +0000986 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000987 }
988}
989
Rui Ueyama95769b42016-08-31 20:03:54 +0000990void ScriptParser::readVersion() {
991 expect("{");
992 readVersionScriptCommand();
993 expect("}");
994}
995
George Rimar20b65982016-08-31 09:08:26 +0000996void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000997 while (!atEOF()) {
998 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +0000999 if (Tok == ";")
1000 continue;
1001
Eugene Leviant20d03192016-09-16 15:30:47 +00001002 if (Tok == "ASSERT") {
1003 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1004 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001005 readEntry();
1006 } else if (Tok == "EXTERN") {
1007 readExtern();
1008 } else if (Tok == "GROUP" || Tok == "INPUT") {
1009 readGroup();
1010 } else if (Tok == "INCLUDE") {
1011 readInclude();
1012 } else if (Tok == "OUTPUT") {
1013 readOutput();
1014 } else if (Tok == "OUTPUT_ARCH") {
1015 readOutputArch();
1016 } else if (Tok == "OUTPUT_FORMAT") {
1017 readOutputFormat();
1018 } else if (Tok == "PHDRS") {
1019 readPhdrs();
1020 } else if (Tok == "SEARCH_DIR") {
1021 readSearchDir();
1022 } else if (Tok == "SECTIONS") {
1023 readSections();
1024 } else if (Tok == "VERSION") {
1025 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001026 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001027 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001028 } else {
George Rimar57610422016-03-11 14:43:02 +00001029 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001030 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001031 }
1032}
1033
Rui Ueyama717677a2016-02-11 21:17:59 +00001034void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001035 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001036 SmallString<128> PathData;
1037 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001038 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001039 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001040 return;
1041 }
1042 }
1043
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001044 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001045 Driver->addFile(S);
1046 } else if (S.startswith("=")) {
1047 if (Config->Sysroot.empty())
1048 Driver->addFile(S.substr(1));
1049 else
1050 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1051 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001052 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001053 } else if (sys::fs::exists(S)) {
1054 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001055 } else {
1056 std::string Path = findFromSearchPaths(S);
1057 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001058 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001059 else
1060 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001061 }
1062}
1063
Rui Ueyama717677a2016-02-11 21:17:59 +00001064void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001065 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001066 bool Orig = Config->AsNeeded;
1067 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001068 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001069 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001070 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001071}
1072
Rui Ueyama717677a2016-02-11 21:17:59 +00001073void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001074 // -e <symbol> takes predecence over ENTRY(<symbol>).
1075 expect("(");
1076 StringRef Tok = next();
1077 if (Config->Entry.empty())
1078 Config->Entry = Tok;
1079 expect(")");
1080}
1081
Rui Ueyama717677a2016-02-11 21:17:59 +00001082void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001083 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001084 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001085 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001086}
1087
Rui Ueyama717677a2016-02-11 21:17:59 +00001088void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001089 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001090 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001091 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001092 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001093 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001094 else
George Rimarcd574a52016-09-09 14:35:36 +00001095 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001096 }
1097}
1098
Rui Ueyama717677a2016-02-11 21:17:59 +00001099void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001100 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001101 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001102 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001103 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001104 return;
1105 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001106 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001107 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1108 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001109 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001110}
1111
Rui Ueyama717677a2016-02-11 21:17:59 +00001112void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001113 // -o <file> takes predecence over OUTPUT(<file>).
1114 expect("(");
1115 StringRef Tok = next();
1116 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001117 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001118 expect(")");
1119}
1120
Rui Ueyama717677a2016-02-11 21:17:59 +00001121void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001122 // Error checking only for now.
1123 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001124 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001125 expect(")");
1126}
1127
Rui Ueyama717677a2016-02-11 21:17:59 +00001128void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001129 // Error checking only for now.
1130 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001131 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001132 StringRef Tok = next();
1133 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001134 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001135 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001136 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001137 return;
1138 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001139 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001140 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001141 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001142 expect(")");
1143}
1144
Eugene Leviantbbe38602016-07-19 09:25:43 +00001145void ScriptParser::readPhdrs() {
1146 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001147 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001148 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001149 Opt.PhdrsCommands.push_back(
1150 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001151 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1152
1153 PhdrCmd.Type = readPhdrType();
1154 do {
1155 Tok = next();
1156 if (Tok == ";")
1157 break;
1158 if (Tok == "FILEHDR")
1159 PhdrCmd.HasFilehdr = true;
1160 else if (Tok == "PHDRS")
1161 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001162 else if (Tok == "AT")
1163 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001164 else if (Tok == "FLAGS") {
1165 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001166 // Passing 0 for the value of dot is a bit of a hack. It means that
1167 // we accept expressions like ".|1".
1168 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001169 expect(")");
1170 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001171 setError("unexpected header attribute: " + Tok);
1172 } while (!Error);
1173 }
1174}
1175
Rui Ueyama717677a2016-02-11 21:17:59 +00001176void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001177 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001178 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001179 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001180 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001181 expect(")");
1182}
1183
Rui Ueyama717677a2016-02-11 21:17:59 +00001184void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001185 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001186 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001187 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001188 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001189 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001190 if (!Cmd) {
1191 if (Tok == "ASSERT")
1192 Cmd = new AssertCommand(readAssert());
1193 else
1194 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001195 }
Rui Ueyama10416562016-08-04 02:03:27 +00001196 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001197 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001198}
1199
Rui Ueyama708019c2016-07-24 18:19:40 +00001200static int precedence(StringRef Op) {
1201 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001202 .Cases("*", "/", 5)
1203 .Cases("+", "-", 4)
1204 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001205 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001206 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001207 .Default(-1);
1208}
1209
Eugene Leviantdb688452016-11-03 10:54:58 +00001210StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001211 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001212 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001213 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001214 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001215}
1216
George Rimarbe394db2016-09-16 20:21:55 +00001217SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001218 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001219 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001220 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001221 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001222 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001223 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001224 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001225 return SortSectionPolicy::None;
1226 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001227}
1228
George Rimar395281c2016-09-16 17:42:10 +00001229// Method reads a list of sequence of excluded files and section globs given in
1230// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1231// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001232// The semantics of that is next:
1233// * Include .foo.1 from every file.
1234// * Include .foo.2 from every file but a.o
1235// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001236std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1237 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001238 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001239 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001240 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001241 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001242 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001243 }
1244
George Rimar601e9892016-09-21 08:53:21 +00001245 std::vector<StringRef> V;
1246 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1247 V.push_back(next());
1248
1249 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001250 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001251 else
1252 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001253 }
George Rimar07171f22016-09-21 15:56:44 +00001254 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001255}
1256
George Rimar07171f22016-09-21 15:56:44 +00001257// Section pattern grammar can have complex expressions, for example:
1258// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1259// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1260// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1261// This methods handles wrapping sequences of excluded files and section globs
1262// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001263InputSectionDescription *
1264ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001265 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001266 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001267 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001268 SortSectionPolicy Outer = readSortKind();
1269 SortSectionPolicy Inner = SortSectionPolicy::Default;
1270 std::vector<SectionPattern> V;
1271 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001272 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001273 Inner = readSortKind();
1274 if (Inner != SortSectionPolicy::Default) {
1275 expect("(");
1276 V = readInputSectionsList();
1277 expect(")");
1278 } else {
1279 V = readInputSectionsList();
1280 }
George Rimar350ece42016-08-03 08:35:59 +00001281 expect(")");
1282 } else {
George Rimar07171f22016-09-21 15:56:44 +00001283 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001284 }
George Rimar0702c4e2016-07-29 15:32:46 +00001285
George Rimar07171f22016-09-21 15:56:44 +00001286 for (SectionPattern &Pat : V) {
1287 Pat.SortInner = Inner;
1288 Pat.SortOuter = Outer;
1289 }
1290
1291 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1292 }
Rui Ueyama10416562016-08-04 02:03:27 +00001293 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001294}
1295
George Rimara2496cb2016-08-30 09:46:59 +00001296InputSectionDescription *
1297ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001298 // Input section wildcard can be surrounded by KEEP.
1299 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001300 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001301 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001302 StringRef FilePattern = next();
1303 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001304 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001305 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001306 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001307 }
George Rimara2496cb2016-08-30 09:46:59 +00001308 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001309}
1310
George Rimar03fc0102016-07-28 07:18:23 +00001311void ScriptParser::readSort() {
1312 expect("(");
1313 expect("CONSTRUCTORS");
1314 expect(")");
1315}
1316
George Rimareefa7582016-08-04 09:29:31 +00001317Expr ScriptParser::readAssert() {
1318 expect("(");
1319 Expr E = readExpr();
1320 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001321 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001322 expect(")");
1323 return [=](uint64_t Dot) {
1324 uint64_t V = E(Dot);
1325 if (!V)
1326 error(Msg);
1327 return V;
1328 };
1329}
1330
Rui Ueyama25150e82016-09-06 17:46:43 +00001331// Reads a FILL(expr) command. We handle the FILL command as an
1332// alias for =fillexp section attribute, which is different from
1333// what GNU linkers do.
1334// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001335std::vector<uint8_t> ScriptParser::readFill() {
1336 expect("(");
1337 std::vector<uint8_t> V = readOutputSectionFiller(next());
1338 expect(")");
1339 expect(";");
1340 return V;
1341}
1342
Rui Ueyama10416562016-08-04 02:03:27 +00001343OutputSectionCommand *
1344ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001345 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001346
1347 // Read an address expression.
1348 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1349 if (peek() != ":")
1350 Cmd->AddrExpr = readExpr();
1351
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001352 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001353
Rui Ueyama83043f22016-10-17 16:01:53 +00001354 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001355 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001356 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001357 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001358 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001359 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001360
Davide Italiano246f6812016-07-22 03:36:24 +00001361 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001362 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001363 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001364 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001365 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001366 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001367
Rui Ueyama83043f22016-10-17 16:01:53 +00001368 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001369 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001370 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001371 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001372 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1373 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001374 else if (Tok == "FILL")
1375 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001376 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001377 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001378 else if (peek() == "(")
1379 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001380 else
1381 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001382 }
George Rimar076fe152016-07-21 06:43:01 +00001383 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001384
Rui Ueyama83043f22016-10-17 16:01:53 +00001385 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001386 Cmd->Filler = readOutputSectionFiller(next());
1387 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001388 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001389
Rui Ueyama10416562016-08-04 02:03:27 +00001390 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001391}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001392
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001393// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1394// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1395//
1396// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1397// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1398// as 32-bit big-endian values. We will do the same as ld.gold does
1399// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001400std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001401 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001402 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001403 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001404 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001405 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001406 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001407}
1408
Petr Hoseka35e39c2016-08-16 01:11:16 +00001409SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001410 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001411 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001412 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001413 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001414 expect(")");
1415 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001416 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001417}
1418
Rafael Espindolac96da112016-11-01 11:30:45 +00001419SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001420 SymbolAssignment *Cmd = nullptr;
1421 if (peek() == "=" || peek() == "+=") {
1422 Cmd = readAssignment(Tok);
1423 expect(";");
1424 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001425 Cmd = readProvideHidden(true, false);
1426 } else if (Tok == "HIDDEN") {
1427 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001428 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001429 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001430 }
1431 return Cmd;
1432}
1433
George Rimar30835ea2016-07-28 21:08:56 +00001434static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1435 if (S == ".")
1436 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001437 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001438}
1439
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001440static bool isAbsolute(StringRef S) {
1441 if (S == ".")
1442 return false;
1443 return ScriptBase->isAbsolute(S);
1444}
1445
George Rimar30835ea2016-07-28 21:08:56 +00001446SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1447 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001448 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001449 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001450 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001451 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1452 // Call readExpr1 to read the whole expression.
1453 E = readExpr1(readParenExpr(), 0);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001454 E.IsAbsolute = []() { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001455 } else {
1456 E = readExpr();
1457 }
George Rimar30835ea2016-07-28 21:08:56 +00001458 if (Op == "+=")
1459 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001460 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001461}
1462
1463// This is an operator-precedence parser to parse a linker
1464// script expression.
1465Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1466
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001467static Expr combine(StringRef Op, Expr L, Expr R) {
1468 if (Op == "*")
1469 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1470 if (Op == "/") {
1471 return [=](uint64_t Dot) -> uint64_t {
1472 uint64_t RHS = R(Dot);
1473 if (RHS == 0) {
1474 error("division by zero");
1475 return 0;
1476 }
1477 return L(Dot) / RHS;
1478 };
1479 }
1480 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001481 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1482 [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001483 if (Op == "-")
1484 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001485 if (Op == "<<")
1486 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1487 if (Op == ">>")
1488 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001489 if (Op == "<")
1490 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1491 if (Op == ">")
1492 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1493 if (Op == ">=")
1494 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1495 if (Op == "<=")
1496 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1497 if (Op == "==")
1498 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1499 if (Op == "!=")
1500 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1501 if (Op == "&")
1502 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001503 if (Op == "|")
1504 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001505 llvm_unreachable("invalid operator");
1506}
1507
Rui Ueyama708019c2016-07-24 18:19:40 +00001508// This is a part of the operator-precedence parser. This function
1509// assumes that the remaining token stream starts with an operator.
1510Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1511 while (!atEOF() && !Error) {
1512 // Read an operator and an expression.
1513 StringRef Op1 = peek();
1514 if (Op1 == "?")
1515 return readTernary(Lhs);
1516 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001517 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001518 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001519 Expr Rhs = readPrimary();
1520
1521 // Evaluate the remaining part of the expression first if the
1522 // next operator has greater precedence than the previous one.
1523 // For example, if we have read "+" and "3", and if the next
1524 // operator is "*", then we'll evaluate 3 * ... part first.
1525 while (!atEOF()) {
1526 StringRef Op2 = peek();
1527 if (precedence(Op2) <= precedence(Op1))
1528 break;
1529 Rhs = readExpr1(Rhs, precedence(Op2));
1530 }
1531
1532 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001533 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001534 return Lhs;
1535}
1536
1537uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001538 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001539 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001540 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001541 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001542 error("unknown constant: " + S);
1543 return 0;
1544}
1545
Rui Ueyama626e0b02016-09-02 18:19:00 +00001546// Parses Tok as an integer. Returns true if successful.
1547// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1548// and decimal numbers. Decimal numbers may have "K" (kilo) or
1549// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001550static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001551 if (Tok.startswith("-")) {
1552 if (!readInteger(Tok.substr(1), Result))
1553 return false;
1554 Result = -Result;
1555 return true;
1556 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001557 if (Tok.startswith_lower("0x"))
1558 return !Tok.substr(2).getAsInteger(16, Result);
1559 if (Tok.endswith_lower("H"))
1560 return !Tok.drop_back().getAsInteger(16, Result);
1561
1562 int Suffix = 1;
1563 if (Tok.endswith_lower("K")) {
1564 Suffix = 1024;
1565 Tok = Tok.drop_back();
1566 } else if (Tok.endswith_lower("M")) {
1567 Suffix = 1024 * 1024;
1568 Tok = Tok.drop_back();
1569 }
1570 if (Tok.getAsInteger(10, Result))
1571 return false;
1572 Result *= Suffix;
1573 return true;
1574}
1575
George Rimare38cbab2016-09-26 19:22:50 +00001576BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1577 int Size = StringSwitch<unsigned>(Tok)
1578 .Case("BYTE", 1)
1579 .Case("SHORT", 2)
1580 .Case("LONG", 4)
1581 .Case("QUAD", 8)
1582 .Default(-1);
1583 if (Size == -1)
1584 return nullptr;
1585
1586 expect("(");
1587 uint64_t Val = 0;
1588 StringRef S = next();
1589 if (!readInteger(S, Val))
1590 setError("unexpected value: " + S);
1591 expect(")");
1592 return new BytesDataCommand(Val, Size);
1593}
1594
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001595StringRef ScriptParser::readParenLiteral() {
1596 expect("(");
1597 StringRef Tok = next();
1598 expect(")");
1599 return Tok;
1600}
1601
Rui Ueyama708019c2016-07-24 18:19:40 +00001602Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001603 if (peek() == "(")
1604 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001605
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001606 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001607
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001608 if (Tok == "~") {
1609 Expr E = readPrimary();
1610 return [=](uint64_t Dot) { return ~E(Dot); };
1611 }
1612 if (Tok == "-") {
1613 Expr E = readPrimary();
1614 return [=](uint64_t Dot) { return -E(Dot); };
1615 }
1616
Rui Ueyama708019c2016-07-24 18:19:40 +00001617 // Built-in functions are parsed here.
1618 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001619 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001620 StringRef Name = readParenLiteral();
George Rimar884e7862016-09-08 08:19:13 +00001621 return
1622 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001623 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001624 if (Tok == "LOADADDR") {
1625 StringRef Name = readParenLiteral();
1626 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1627 }
George Rimareefa7582016-08-04 09:29:31 +00001628 if (Tok == "ASSERT")
1629 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001630 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001631 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001632 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1633 }
1634 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001635 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001636 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001637 }
George Rimarf34f45f2016-09-23 13:17:23 +00001638 if (Tok == "DEFINED") {
1639 expect("(");
1640 StringRef Tok = next();
1641 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001642 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001643 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001644 if (Tok == "SEGMENT_START") {
1645 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001646 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001647 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001648 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001649 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001650 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001651 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001652 if (Tok == "DATA_SEGMENT_ALIGN") {
1653 expect("(");
1654 Expr E = readExpr();
1655 expect(",");
1656 readExpr();
1657 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001658 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001659 }
1660 if (Tok == "DATA_SEGMENT_END") {
1661 expect("(");
1662 expect(".");
1663 expect(")");
1664 return [](uint64_t Dot) { return Dot; };
1665 }
George Rimar276b4e62016-07-26 17:58:44 +00001666 // GNU linkers implements more complicated logic to handle
1667 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1668 // the next page boundary for simplicity.
1669 if (Tok == "DATA_SEGMENT_RELRO_END") {
1670 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001671 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001672 expect(",");
1673 readExpr();
1674 expect(")");
1675 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1676 }
George Rimar9e694502016-07-29 16:18:47 +00001677 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001678 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001679 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001680 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001681 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001682 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001683 return
1684 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001685 }
George Rimare32a3592016-08-10 07:59:34 +00001686 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001687 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001688
George Rimar9f2f7ad2016-09-02 16:01:42 +00001689 // Tok is a literal number.
1690 uint64_t V;
1691 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001692 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001693
1694 // Tok is a symbol name.
1695 if (Tok != "." && !isValidCIdentifier(Tok))
1696 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001697 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1698 [=]() { return isAbsolute(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001699}
1700
1701Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001702 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001703 Expr L = readExpr();
1704 expect(":");
1705 Expr R = readExpr();
1706 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1707}
1708
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001709Expr ScriptParser::readParenExpr() {
1710 expect("(");
1711 Expr E = readExpr();
1712 expect(")");
1713 return E;
1714}
1715
Eugene Leviantbbe38602016-07-19 09:25:43 +00001716std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1717 std::vector<StringRef> Phdrs;
1718 while (!Error && peek().startswith(":")) {
1719 StringRef Tok = next();
1720 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1721 if (Tok.empty()) {
1722 setError("section header name is empty");
1723 break;
1724 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001725 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001726 }
1727 return Phdrs;
1728}
1729
George Rimar95dd7182016-10-18 10:49:50 +00001730// Read a program header type name. The next token must be a
1731// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001732unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001733 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001734 uint64_t Val;
1735 if (readInteger(Tok, Val))
1736 return Val;
1737
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001738 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001739 .Case("PT_NULL", PT_NULL)
1740 .Case("PT_LOAD", PT_LOAD)
1741 .Case("PT_DYNAMIC", PT_DYNAMIC)
1742 .Case("PT_INTERP", PT_INTERP)
1743 .Case("PT_NOTE", PT_NOTE)
1744 .Case("PT_SHLIB", PT_SHLIB)
1745 .Case("PT_PHDR", PT_PHDR)
1746 .Case("PT_TLS", PT_TLS)
1747 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1748 .Case("PT_GNU_STACK", PT_GNU_STACK)
1749 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001750 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001751 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001752 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001753
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001754 if (Ret == (unsigned)-1) {
1755 setError("invalid program header type: " + Tok);
1756 return PT_NULL;
1757 }
1758 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001759}
1760
Rui Ueyama95769b42016-08-31 20:03:54 +00001761void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001762 // Identifiers start at 2 because 0 and 1 are reserved
1763 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1764 size_t VersionId = Config->VersionDefinitions.size() + 2;
1765 Config->VersionDefinitions.push_back({VerStr, VersionId});
1766
Rui Ueyama83043f22016-10-17 16:01:53 +00001767 if (consume("global:") || peek() != "local:")
George Rimar20b65982016-08-31 09:08:26 +00001768 readGlobal(VerStr);
Rui Ueyama83043f22016-10-17 16:01:53 +00001769 if (consume("local:"))
George Rimar20b65982016-08-31 09:08:26 +00001770 readLocal();
1771 expect("}");
1772
1773 // Each version may have a parent version. For example, "Ver2" defined as
1774 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1775 // version hierarchy is, probably against your instinct, purely for human; the
1776 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1777 if (!VerStr.empty() && peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001778 skip();
George Rimar20b65982016-08-31 09:08:26 +00001779 expect(";");
1780}
1781
1782void ScriptParser::readLocal() {
1783 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1784 expect("*");
1785 expect(";");
1786}
1787
1788void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001789 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001790 expect("{");
1791
1792 for (;;) {
1793 if (peek() == "}" || Error)
1794 break;
George Rimarcd574a52016-09-09 14:35:36 +00001795 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1796 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001797 expect(";");
1798 }
1799
1800 expect("}");
1801 expect(";");
1802}
1803
1804void ScriptParser::readGlobal(StringRef VerStr) {
1805 std::vector<SymbolVersion> *Globals;
1806 if (VerStr.empty())
1807 Globals = &Config->VersionScriptGlobals;
1808 else
1809 Globals = &Config->VersionDefinitions.back().Globals;
1810
1811 for (;;) {
Rui Ueyama83043f22016-10-17 16:01:53 +00001812 if (consume("extern"))
George Rimar20b65982016-08-31 09:08:26 +00001813 readExtern(Globals);
1814
1815 StringRef Cur = peek();
1816 if (Cur == "}" || Cur == "local:" || Error)
1817 return;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001818 skip();
George Rimarcd574a52016-09-09 14:35:36 +00001819 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001820 expect(";");
1821 }
1822}
1823
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001824static bool isUnderSysroot(StringRef Path) {
1825 if (Config->Sysroot == "")
1826 return false;
1827 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1828 if (sys::fs::equivalent(Config->Sysroot, Path))
1829 return true;
1830 return false;
1831}
1832
Rui Ueyama07320e42016-04-20 20:13:41 +00001833void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001834 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001835 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1836}
1837
1838void elf::readVersionScript(MemoryBufferRef MB) {
1839 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001840}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001841
Rui Ueyama07320e42016-04-20 20:13:41 +00001842template class elf::LinkerScript<ELF32LE>;
1843template class elf::LinkerScript<ELF32BE>;
1844template class elf::LinkerScript<ELF64LE>;
1845template class elf::LinkerScript<ELF64BE>;