blob: 1f65c3703f94a48e2511aeb60bc389a6ca304db1 [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"
Eugene Zelenko22886a22016-11-05 01:00:56 +000032#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000033#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000034#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000035#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000037#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include "llvm/Support/Endian.h"
39#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000040#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000041#include "llvm/Support/MathExtras.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000042#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000043#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000044#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <iterator>
49#include <limits>
50#include <memory>
51#include <string>
52#include <tuple>
53#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000054
55using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000056using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000057using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000058using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000059using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000060using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000061
George Rimar884e7862016-09-08 08:19:13 +000062LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000063ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000064
George Rimar6c55f0e2016-09-08 08:20:30 +000065template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000066 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000067 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
George Rimar463984d2016-11-15 08:07:14 +000068 0, 0, STB_GLOBAL, nullptr, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000069 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000070
71 // If we have no SECTIONS then we don't have '.' and don't call
72 // assignAddresses(). We calculate symbol value immediately in this case.
73 if (!ScriptConfig->HasSections)
74 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000075}
76
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000077template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
George Rimare1937bb2016-08-19 15:36:32 +000078 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
79 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000080 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000081}
82
Eugene Leviantdb741e72016-09-07 07:08:43 +000083template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000084 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000085 addRegular<ELFT>(Cmd);
86 else
87 addSynthetic<ELFT>(Cmd);
88}
Rui Ueyama16024212016-08-11 23:22:52 +000089// If a symbol was in PROVIDE(), we need to define it only when
90// it is an undefined symbol.
91template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
92 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000093 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000094 if (!Cmd->Provide)
95 return true;
96 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
97 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000098}
99
George Rimar076fe152016-07-21 06:43:01 +0000100bool SymbolAssignment::classof(const BaseCommand *C) {
101 return C->Kind == AssignmentKind;
102}
103
104bool OutputSectionCommand::classof(const BaseCommand *C) {
105 return C->Kind == OutputSectionKind;
106}
107
George Rimareea31142016-07-21 14:26:59 +0000108bool InputSectionDescription::classof(const BaseCommand *C) {
109 return C->Kind == InputSectionKind;
110}
111
George Rimareefa7582016-08-04 09:29:31 +0000112bool AssertCommand::classof(const BaseCommand *C) {
113 return C->Kind == AssertKind;
114}
115
George Rimare38cbab2016-09-26 19:22:50 +0000116bool BytesDataCommand::classof(const BaseCommand *C) {
117 return C->Kind == BytesDataKind;
118}
119
Eugene Zelenko22886a22016-11-05 01:00:56 +0000120template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
121template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000122
Rui Ueyama07320e42016-04-20 20:13:41 +0000123template <class ELFT>
124bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000125 for (InputSectionDescription *ID : Opt.KeptSections) {
126 StringRef Filename = S->getFile()->getName();
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000127 if (!ID->FilePat.match(sys::path::filename(Filename)))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000128 continue;
Rui Ueyamab66260a2016-10-05 20:09:50 +0000129
130 for (SectionPattern &P : ID->SectionPatterns)
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000131 if (P.SectionPat.match(S->Name))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000132 return true;
133 }
George Rimareea31142016-07-21 14:26:59 +0000134 return false;
135}
136
George Rimar575208c2016-09-15 19:15:12 +0000137static bool comparePriority(InputSectionData *A, InputSectionData *B) {
138 return getPriority(A->Name) < getPriority(B->Name);
139}
140
Rafael Espindolac0028d32016-09-08 20:47:52 +0000141static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000142 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000143}
George Rimar350ece42016-08-03 08:35:59 +0000144
Rafael Espindolac0028d32016-09-08 20:47:52 +0000145static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000146 // ">" is not a mistake. Larger alignments are placed before smaller
147 // alignments in order to reduce the amount of padding necessary.
148 // This is compatible with GNU.
149 return A->Alignment > B->Alignment;
150}
George Rimar350ece42016-08-03 08:35:59 +0000151
Rafael Espindolac0028d32016-09-08 20:47:52 +0000152static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000153getComparator(SortSectionPolicy K) {
154 switch (K) {
155 case SortSectionPolicy::Alignment:
156 return compareAlignment;
157 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000158 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000159 case SortSectionPolicy::Priority:
160 return comparePriority;
161 default:
162 llvm_unreachable("unknown sort policy");
163 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000164}
George Rimar0702c4e2016-07-29 15:32:46 +0000165
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000166template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000167static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000168 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000169 if (Kind == ConstraintKind::NoConstraint)
170 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000171 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000172 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000173 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000174 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000175 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
176 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000177}
178
George Rimar07171f22016-09-21 15:56:44 +0000179static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000180 SortSectionPolicy K) {
181 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000182 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000183}
184
Rafael Espindolad3190792016-09-16 15:10:23 +0000185// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000186template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000187void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000188 // Collects all sections that satisfy constraints of I
189 // and attach them to I.
190 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000191 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000192
193 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000194 if (!S->Live || S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000195 continue;
196
197 StringRef Filename;
198 if (elf::ObjectFile<ELFT> *F = S->getFile())
199 Filename = sys::path::filename(F->getName());
200
Rui Ueyamae8a61022016-11-05 23:05:47 +0000201 if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) &&
202 Pat.SectionPat.match(S->Name))
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000203 I->Sections.push_back(S);
George Rimar395281c2016-09-16 17:42:10 +0000204 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000205
George Rimar07171f22016-09-21 15:56:44 +0000206 // Sort sections as instructed by SORT-family commands and --sort-section
207 // option. Because SORT-family commands can be nested at most two depth
208 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
209 // line option is respected even if a SORT command is given, the exact
210 // behavior we have here is a bit complicated. Here are the rules.
211 //
212 // 1. If two SORT commands are given, --sort-section is ignored.
213 // 2. If one SORT command is given, and if it is not SORT_NONE,
214 // --sort-section is handled as an inner SORT command.
215 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
216 // 4. If no SORT command is given, sort according to --sort-section.
217 InputSectionData **Begin = I->Sections.data() + SizeBefore;
218 InputSectionData **End = I->Sections.data() + I->Sections.size();
219 if (Pat.SortOuter != SortSectionPolicy::None) {
220 if (Pat.SortInner == SortSectionPolicy::Default)
221 sortSections(Begin, End, Config->SortSection);
222 else
223 sortSections(Begin, End, Pat.SortInner);
224 sortSections(Begin, End, Pat.SortOuter);
225 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000226 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000227
228 // We do not add duplicate input sections, so mark them with a dummy output
229 // section for now.
230 for (InputSectionData *S : I->Sections) {
231 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000232 S2->OutSec = (OutputSectionBase *)-1;
Rafael Espindolad3190792016-09-16 15:10:23 +0000233 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000234}
235
236template <class ELFT>
237void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
238 for (InputSectionBase<ELFT> *S : V) {
239 S->Live = false;
240 reportDiscarded(S);
241 }
242}
243
George Rimar06ae6832016-08-12 09:07:57 +0000244template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000245std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000246LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000247 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000248
George Rimar06ae6832016-08-12 09:07:57 +0000249 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000250 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
251 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000252 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000253 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000254 for (InputSectionData *S : Cmd->Sections)
255 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000256 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000257
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000258 // After we created final list we should now set OutSec pointer to null,
George Rimara4c7e742016-10-20 08:36:42 +0000259 // instead of -1. Otherwise we may get a crash when writing relocs, in
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000260 // case section is discarded by linker script
261 for (InputSectionBase<ELFT> *S : Ret)
262 S->OutSec = nullptr;
263
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000264 return Ret;
265}
266
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000267template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000268static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
269 StringRef OutsecName) {
270 // When using linker script the merge rules are different.
271 // Unfortunately, linker scripts are name based. This means that expressions
272 // like *(.foo*) can refer to multiple input sections that would normally be
273 // placed in different output sections. We cannot put them in different
274 // output sections or we would produce wrong results for
275 // start = .; *(.foo.*) end = .; *(.bar)
276 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
277 // another. The problem is that there is no way to layout those output
278 // sections such that the .foo sections are the only thing between the
279 // start and end symbols.
280
281 // An extra annoyance is that we cannot simply disable merging of the contents
282 // of SHF_MERGE sections, but our implementation requires one output section
283 // per "kind" (string or not, which size/aligment).
284 // Fortunately, creating symbols in the middle of a merge section is not
285 // supported by bfd or gold, so we can just create multiple section in that
286 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000287 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000288 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000289
290 uintX_t Alignment = 0;
291 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000292 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000293
294 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
295}
296
297template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000298void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
299 InputSectionBase<ELFT> *Sec,
300 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000301 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000302 bool IsNew;
303 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
304 if (IsNew)
305 OutputSections->push_back(OutSec);
306 OutSec->addSection(Sec);
307}
308
309template <class ELFT>
310void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000311 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
312 auto Iter = Opt.Commands.begin() + I;
313 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000314 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
315 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000316 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000317 continue;
318 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000319 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
320 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000321 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000322 // will not be called, so ASSERT should be evaluated now.
323 if (!Opt.HasSections)
324 Cmd->Expression(0);
325 continue;
326 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000327
Eugene Leviantceabe802016-08-11 07:56:43 +0000328 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000329 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
330
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000331 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000332 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000333 continue;
334 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000335
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000336 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
337 for (InputSectionBase<ELFT> *S : V)
338 S->OutSec = nullptr;
339 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000340 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000341 continue;
342 }
343
344 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
345 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
346 if (shouldDefine<ELFT>(OutCmd))
347 addSymbol<ELFT>(OutCmd);
348
Eugene Leviant97403d12016-09-01 09:55:57 +0000349 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000350 continue;
351
George Rimardb24d9c2016-08-19 15:18:23 +0000352 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000353 addSection(Factory, Sec, Cmd->Name);
354 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000355 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000356 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000357 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000358 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000359}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000360
Eugene Leviant20d03192016-09-16 15:30:47 +0000361template <class ELFT>
362void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
363 processCommands(Factory);
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000364
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000365 // Add orphan sections.
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000366 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000367 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000368 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000369}
370
Eugene Leviantdb741e72016-09-07 07:08:43 +0000371// Sets value of a section-defined symbol. Two kinds of
372// symbols are processed: synthetic symbols, whose value
373// is an offset from beginning of section and regular
374// symbols whose value is absolute.
375template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000376static void assignSectionSymbol(SymbolAssignment *Cmd, OutputSectionBase *Sec,
Rafael Espindola498ed712016-10-31 14:44:41 +0000377 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000378 if (!Cmd->Sym)
379 return;
380
381 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
382 Body->Section = Sec;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000383 Body->Value = Cmd->Expression(Value) - Sec->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000384 return;
385 }
386 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000387 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000388}
389
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000390template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000391 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000392}
393
Rafael Espindolad3190792016-09-16 15:10:23 +0000394template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
395 if (!AlreadyOutputIS.insert(S).second)
396 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000397 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000398
Rafael Espindolad3190792016-09-16 15:10:23 +0000399 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
400 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000401 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000402 Pos += S->getSize();
403
404 // Update output section size after adding each section. This is so that
405 // SIZEOF works correctly in the case below:
406 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000407 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000408
Rafael Espindola7252ae52016-09-22 12:00:08 +0000409 if (IsTbss)
410 ThreadBssOffset = Pos - Dot;
411 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000412 Dot = Pos;
413}
414
415template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000416 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
417 return;
418 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000419 for (InputSection<ELFT> *I : OutSec->Sections)
420 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000421 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000422 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000423 }
424}
425
426template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000427void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000428 if (CurOutSec == Sec)
429 return;
430 if (AlreadyOutputOS.count(Sec))
431 return;
432
433 flush();
434 CurOutSec = Sec;
435
Rafael Espindola04a2e342016-11-09 01:42:41 +0000436 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000437 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000438
439 // If neither AT nor AT> is specified for an allocatable section, the linker
440 // will set the LMA such that the difference between VMA and LMA for the
441 // section is the same as the preceding output section in the same region
442 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
443 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000444}
445
446template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000447 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000448 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
449 if (AssignCmd->Name == ".") {
450 // Update to location counter means update to section size.
451 Dot = AssignCmd->Expression(Dot);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000452 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000453 return;
454 }
Rafael Espindola498ed712016-10-31 14:44:41 +0000455 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000456 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000457 }
George Rimare38cbab2016-09-26 19:22:50 +0000458
459 // Handle BYTE(), SHORT(), LONG(), or QUAD().
460 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000461 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000462 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000463 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000464 return;
465 }
466
467 // It handles single input section description command,
468 // calculates and assigns the offsets for each section and also
469 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000470 auto &ICmd = cast<InputSectionDescription>(Base);
471 for (InputSectionData *ID : ICmd.Sections) {
472 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
473 switchTo(IB->OutSec);
474 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
475 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000476 else
477 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000478 }
479}
480
George Rimar8f66df92016-08-12 20:38:20 +0000481template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000482static std::vector<OutputSectionBase *>
483findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
484 std::vector<OutputSectionBase *> Ret;
485 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000486 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000487 Ret.push_back(Sec);
488 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000489}
490
Rafael Espindolad3190792016-09-16 15:10:23 +0000491template <class ELFT>
492void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000493 if (Cmd->LMAExpr)
494 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000495 std::vector<OutputSectionBase *> Sections =
496 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000497 if (Sections.empty())
498 return;
499 switchTo(Sections[0]);
Rafael Espindolad3190792016-09-16 15:10:23 +0000500 // Find the last section output location. We will output orphan sections
501 // there so that end symbols point to the correct location.
502 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
503 [](const std::unique_ptr<BaseCommand> &Cmd) {
504 return !isa<SymbolAssignment>(*Cmd);
505 })
506 .base();
507 for (auto I = Cmd->Commands.begin(); I != E; ++I)
508 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000509 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000510 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000511 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000512 std::for_each(E, Cmd->Commands.end(),
513 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000514}
515
Rafael Espindola07fe6122016-11-14 14:23:35 +0000516template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000517 // It is common practice to use very generic linker scripts. So for any
518 // given run some of the output sections in the script will be empty.
519 // We could create corresponding empty output sections, but that would
520 // clutter the output.
521 // We instead remove trivially empty sections. The bfd linker seems even
522 // more aggressive at removing them.
523 auto Pos = std::remove_if(
524 Opt.Commands.begin(), Opt.Commands.end(),
525 [&](const std::unique_ptr<BaseCommand> &Base) {
526 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
527 if (!Cmd)
528 return false;
Rafael Espindola6a537372016-11-14 14:33:49 +0000529 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000530 });
531 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000532}
533
Rafael Espindola6a537372016-11-14 14:33:49 +0000534static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
535 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
536 if (!isa<InputSectionDescription>(*I))
537 return false;
538 return true;
539}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000540
Rafael Espindola6a537372016-11-14 14:33:49 +0000541template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000542 // If the output section contains only symbol assignments, create a
543 // corresponding output section. The bfd linker seems to only create them if
544 // '.' is assigned to, but creating these section should not have any bad
545 // consequeces and gives us a section to put the symbol in.
546 uintX_t Flags = SHF_ALLOC;
547 uint32_t Type = 0;
548 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
549 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
550 if (!Cmd)
551 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000552 std::vector<OutputSectionBase *> Secs =
553 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000554 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000555 Flags = Secs[0]->Flags;
556 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000557 continue;
558 }
559
Rafael Espindola6a537372016-11-14 14:33:49 +0000560 if (isAllSectionDescription(*Cmd))
561 continue;
562
Rui Ueyama95642b92016-11-01 23:09:07 +0000563 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000564 OutputSections->push_back(OutSec);
565 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000566}
567
568template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
569 placeOrphanSections();
570
571 // If output section command doesn't specify any segments,
572 // and we haven't previously assigned any section to segment,
573 // then we simply assign section to the very first load segment.
574 // Below is an example of such linker script:
575 // PHDRS { seg PT_LOAD; }
576 // SECTIONS { .aaa : { *(.aaa) } }
577 std::vector<StringRef> DefPhdrs;
578 auto FirstPtLoad =
579 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
580 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
581 if (FirstPtLoad != Opt.PhdrsCommands.end())
582 DefPhdrs.push_back(FirstPtLoad->Name);
583
584 // Walk the commands and propagate the program headers to commands that don't
585 // explicitly specify them.
586 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
587 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
588 if (!Cmd)
589 continue;
590 if (Cmd->Phdrs.empty())
591 Cmd->Phdrs = DefPhdrs;
592 else
593 DefPhdrs = Cmd->Phdrs;
594 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000595
596 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000597}
598
Rafael Espindola15c57952016-09-22 18:05:49 +0000599// When placing orphan sections, we want to place them after symbol assignments
600// so that an orphan after
601// begin_foo = .;
602// foo : { *(foo) }
603// end_foo = .;
604// doesn't break the intended meaning of the begin/end symbols.
605// We don't want to go over sections since Writer<ELFT>::sortSections is the
606// one in charge of deciding the order of the sections.
607// We don't want to go over alignments, since doing so in
608// rx_sec : { *(rx_sec) }
609// . = ALIGN(0x1000);
610// /* The RW PT_LOAD starts here*/
611// rw_sec : { *(rw_sec) }
612// would mean that the RW PT_LOAD would become unaligned.
613static bool shouldSkip(const BaseCommand &Cmd) {
614 if (isa<OutputSectionCommand>(Cmd))
615 return false;
616 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
617 if (!Assign)
618 return true;
619 return Assign->Name != ".";
620}
621
Rafael Espindola337f9032016-11-14 14:13:32 +0000622// Orphan sections are sections present in the input files which are not
623// explicitly placed into the output file by the linker script. This just
624// places them in the order already decided in OutputSections.
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000625template <class ELFT>
Rafael Espindola337f9032016-11-14 14:13:32 +0000626void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000627 // The OutputSections are already in the correct order.
628 // This loops creates or moves commands as needed so that they are in the
629 // correct order.
630 int CmdIndex = 0;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000631 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000632 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000633
634 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000635 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000636 auto CmdIter = Opt.Commands.begin() + CmdIndex;
637 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000638 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000639 ++CmdIter;
640 ++CmdIndex;
641 }
642
643 auto Pos =
644 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
645 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
646 return Cmd && Cmd->Name == Name;
647 });
648 if (Pos == E) {
649 Opt.Commands.insert(CmdIter,
650 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000651 ++CmdIndex;
652 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000653 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000654
655 // Continue from where we found it.
656 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000657 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000658}
659
660template <class ELFT>
661void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000662 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000663 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000664
George Rimar076fe152016-07-21 06:43:01 +0000665 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
666 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000667 if (Cmd->Name == ".") {
668 Dot = Cmd->Expression(Dot);
669 } else if (Cmd->Sym) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000670 assignSectionSymbol<ELFT>(
671 Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0], Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000672 }
George Rimar652852c2016-04-16 10:10:32 +0000673 continue;
674 }
675
George Rimareefa7582016-08-04 09:29:31 +0000676 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
677 Cmd->Expression(Dot);
678 continue;
679 }
680
George Rimar076fe152016-07-21 06:43:01 +0000681 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000682
Rafael Espindolad3190792016-09-16 15:10:23 +0000683 if (Cmd->AddrExpr)
684 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000685
Rafael Espindolad3190792016-09-16 15:10:23 +0000686 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000687 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000688
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000689 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000690 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000691 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000692 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000693 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000694 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000695 }
696
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000697 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000698 auto FirstPTLoad =
699 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
700 return E.H.p_type == PT_LOAD;
701 });
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000702
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000703 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
George Rimar59d9b4b2016-11-14 10:04:45 +0000704 // If linker script specifies program headers and first PT_LOAD doesn't
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000705 // have both PHDRS and FILEHDR attributes then do nothing
706 if (!Opt.PhdrsCommands.empty()) {
707 size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
708 if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
709 !Opt.PhdrsCommands[SegNum].HasFilehdr)
710 return;
711 }
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000712 // ELF and Program headers need to be right before the first section in
713 // memory. Set their addresses accordingly.
714 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000715 Out<ELFT>::ElfHeader->Addr = MinVA;
716 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000717 FirstPTLoad->First = Out<ELFT>::ElfHeader;
718 if (!FirstPTLoad->Last)
719 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000720 } else if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000721 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000722 // This happens if (all conditions met):
723 // - Linker script is used
724 // - First section in ELF image is not RO
725 // - Not enough space for program headers.
726 // The code below removes empty PT_LOAD segment and updates
727 // program headers size.
728 Phdrs.erase(FirstPTLoad);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000729 Out<ELFT>::ProgramHeaders->Size =
730 sizeof(typename ELFT::Phdr) * Phdrs.size();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000731 }
George Rimar652852c2016-04-16 10:10:32 +0000732}
733
Rui Ueyama464daad2016-08-22 04:55:20 +0000734// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000735template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000736std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000737 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000738
Rui Ueyama464daad2016-08-22 04:55:20 +0000739 // Process PHDRS and FILEHDR keywords because they are not
740 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000741 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000742 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
743 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000744
745 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000746 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000747 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000748 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000749
750 if (Cmd.LMAExpr) {
751 Phdr.H.p_paddr = Cmd.LMAExpr(0);
752 Phdr.HasLMA = true;
753 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000754 }
755
Rui Ueyama464daad2016-08-22 04:55:20 +0000756 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000757 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000758 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000759 break;
760
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000761 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000762 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000763 Ret[Id].add(Sec);
764 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
765 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000766 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000767 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000768 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000769}
770
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000771template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
772 // Ignore .interp section in case we have PHDRS specification
773 // and PT_INTERP isn't listed.
774 return !Opt.PhdrsCommands.empty() &&
775 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
776 return Cmd.Type == PT_INTERP;
777 }) == Opt.PhdrsCommands.end();
778}
779
Eugene Leviantbbe38602016-07-19 09:25:43 +0000780template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000781ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000782 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
783 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
784 if (Cmd->Name == Name)
785 return Cmd->Filler;
786 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000787}
788
George Rimare38cbab2016-09-26 19:22:50 +0000789template <class ELFT>
790static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
791 const endianness E = ELFT::TargetEndianness;
792
793 switch (Size) {
794 case 1:
795 *Buf = (uint8_t)Data;
796 break;
797 case 2:
798 write16<E>(Buf, Data);
799 break;
800 case 4:
801 write32<E>(Buf, Data);
802 break;
803 case 8:
804 write64<E>(Buf, Data);
805 break;
806 default:
807 llvm_unreachable("unsupported Size argument");
808 }
809}
810
811template <class ELFT>
812void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
813 int I = getSectionIndex(Name);
814 if (I == INT_MAX)
815 return;
816
817 OutputSectionCommand *Cmd =
818 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
819 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
820 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
821 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
822}
823
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000824template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000825 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
826 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000827 if (Cmd->LMAExpr && Cmd->Name == Name)
828 return true;
829 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000830}
831
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000832// Returns the index of the given section name in linker script
833// SECTIONS commands. Sections are laid out as the same order as they
834// were in the script. If a given name did not appear in the script,
835// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000836template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000837 int I = 0;
838 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
839 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
840 if (Cmd->Name == Name)
841 return I;
842 ++I;
843 }
844 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000845}
846
Eugene Leviantbbe38602016-07-19 09:25:43 +0000847template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
848 return !Opt.PhdrsCommands.empty();
849}
850
George Rimar9e694502016-07-29 16:18:47 +0000851template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000852uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000853 for (OutputSectionBase *Sec : *OutputSections)
George Rimar96659df2016-08-30 09:54:01 +0000854 if (Sec->getName() == Name)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000855 return Sec->Addr;
George Rimar96659df2016-08-30 09:54:01 +0000856 error("undefined section " + Name);
857 return 0;
858}
859
860template <class ELFT>
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000861uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000862 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000863 if (Sec->getName() == Name)
864 return Sec->getLMA();
865 error("undefined section " + Name);
866 return 0;
867}
868
869template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000870uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000871 for (OutputSectionBase *Sec : *OutputSections)
George Rimar9e694502016-07-29 16:18:47 +0000872 if (Sec->getName() == Name)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000873 return Sec->Size;
George Rimar9e694502016-07-29 16:18:47 +0000874 error("undefined section " + Name);
875 return 0;
876}
877
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000878template <class ELFT>
879uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000880 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000881 if (Sec->getName() == Name)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000882 return Sec->Addralign;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000883 error("undefined section " + Name);
884 return 0;
885}
886
George Rimar884e7862016-09-08 08:19:13 +0000887template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000888 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000889}
890
George Rimar884e7862016-09-08 08:19:13 +0000891template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
892 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
893 return B->getVA<ELFT>();
894 error("symbol not found: " + S);
895 return 0;
896}
897
George Rimarf34f45f2016-09-23 13:17:23 +0000898template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
899 return Symtab<ELFT>::X->find(S) != nullptr;
900}
901
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000902template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
903 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
904 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
905 return DR && !DR->Section;
906}
907
Eugene Leviantbbe38602016-07-19 09:25:43 +0000908// Returns indices of ELF headers containing specific section, identified
909// by Name. Each index is a zero based number of ELF header listed within
910// PHDRS {} script block.
911template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000912std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000913 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
914 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000915 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000916 continue;
917
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000918 std::vector<size_t> Ret;
919 for (StringRef PhdrName : Cmd->Phdrs)
920 Ret.push_back(getPhdrIndex(PhdrName));
921 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000922 }
George Rimar31d842f2016-07-20 16:43:03 +0000923 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000924}
925
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000926template <class ELFT>
927size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
928 size_t I = 0;
929 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
930 if (Cmd.Name == PhdrName)
931 return I;
932 ++I;
933 }
934 error("section header '" + PhdrName + "' is not listed in PHDRS");
935 return 0;
936}
937
Rui Ueyama07320e42016-04-20 20:13:41 +0000938class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000939 typedef void (ScriptParser::*Handler)();
940
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000941public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000942 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000943
George Rimar20b65982016-08-31 09:08:26 +0000944 void readLinkerScript();
945 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000946
947private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000948 void addFile(StringRef Path);
949
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000950 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000951 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000952 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000953 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000954 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000955 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000956 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000957 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000958 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000959 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000960 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000961 void readVersion();
962 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000963
Rui Ueyama113cdec2016-07-24 23:05:57 +0000964 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000965 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000966 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000967 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000968 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000969 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000970 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000971 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000972 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000973 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000974 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000975 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000976 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000977 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000978 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000979 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000980
981 Expr readExpr();
982 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000983 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000984 Expr readPrimary();
985 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000986 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000987
George Rimar20b65982016-08-31 09:08:26 +0000988 // For parsing version script.
Rui Ueyama2a00b842016-11-15 17:51:07 +0000989 void readVersionExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000990 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000991 void readGlobal(StringRef VerStr);
George Rimarbb6c01e2016-11-12 07:04:15 +0000992 void readLocal(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000993
Rui Ueyama07320e42016-04-20 20:13:41 +0000994 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000995 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000996};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000997
George Rimar20b65982016-08-31 09:08:26 +0000998void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000999 readVersionScriptCommand();
1000 if (!atEOF())
1001 setError("EOF expected, but got " + next());
1002}
1003
1004void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001005 if (consume("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +00001006 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +00001007 return;
1008 }
1009
Rui Ueyama95769b42016-08-31 20:03:54 +00001010 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001011 StringRef VerStr = next();
1012 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001013 setError("anonymous version definition is used in "
1014 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001015 return;
1016 }
1017 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001018 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001019 }
1020}
1021
Rui Ueyama95769b42016-08-31 20:03:54 +00001022void ScriptParser::readVersion() {
1023 expect("{");
1024 readVersionScriptCommand();
1025 expect("}");
1026}
1027
George Rimar20b65982016-08-31 09:08:26 +00001028void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001029 while (!atEOF()) {
1030 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001031 if (Tok == ";")
1032 continue;
1033
Eugene Leviant20d03192016-09-16 15:30:47 +00001034 if (Tok == "ASSERT") {
1035 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1036 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001037 readEntry();
1038 } else if (Tok == "EXTERN") {
1039 readExtern();
1040 } else if (Tok == "GROUP" || Tok == "INPUT") {
1041 readGroup();
1042 } else if (Tok == "INCLUDE") {
1043 readInclude();
1044 } else if (Tok == "OUTPUT") {
1045 readOutput();
1046 } else if (Tok == "OUTPUT_ARCH") {
1047 readOutputArch();
1048 } else if (Tok == "OUTPUT_FORMAT") {
1049 readOutputFormat();
1050 } else if (Tok == "PHDRS") {
1051 readPhdrs();
1052 } else if (Tok == "SEARCH_DIR") {
1053 readSearchDir();
1054 } else if (Tok == "SECTIONS") {
1055 readSections();
1056 } else if (Tok == "VERSION") {
1057 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001058 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001059 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001060 } else {
George Rimar57610422016-03-11 14:43:02 +00001061 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001062 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001063 }
1064}
1065
Rui Ueyama717677a2016-02-11 21:17:59 +00001066void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001067 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001068 SmallString<128> PathData;
1069 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001070 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001071 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001072 return;
1073 }
1074 }
1075
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001076 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001077 Driver->addFile(S);
1078 } else if (S.startswith("=")) {
1079 if (Config->Sysroot.empty())
1080 Driver->addFile(S.substr(1));
1081 else
1082 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1083 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001084 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001085 } else if (sys::fs::exists(S)) {
1086 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001087 } else {
1088 std::string Path = findFromSearchPaths(S);
1089 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001090 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001091 else
1092 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001093 }
1094}
1095
Rui Ueyama717677a2016-02-11 21:17:59 +00001096void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001097 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001098 bool Orig = Config->AsNeeded;
1099 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001100 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001101 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001102 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001103}
1104
Rui Ueyama717677a2016-02-11 21:17:59 +00001105void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001106 // -e <symbol> takes predecence over ENTRY(<symbol>).
1107 expect("(");
1108 StringRef Tok = next();
1109 if (Config->Entry.empty())
1110 Config->Entry = Tok;
1111 expect(")");
1112}
1113
Rui Ueyama717677a2016-02-11 21:17:59 +00001114void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001115 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001116 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001117 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001118}
1119
Rui Ueyama717677a2016-02-11 21:17:59 +00001120void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001121 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001122 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001123 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001124 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001125 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001126 else
George Rimarcd574a52016-09-09 14:35:36 +00001127 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001128 }
1129}
1130
Rui Ueyama717677a2016-02-11 21:17:59 +00001131void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001132 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001133 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001134 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001135 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001136 return;
1137 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001138 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001139 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1140 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001141 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001142}
1143
Rui Ueyama717677a2016-02-11 21:17:59 +00001144void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001145 // -o <file> takes predecence over OUTPUT(<file>).
1146 expect("(");
1147 StringRef Tok = next();
1148 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001149 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001150 expect(")");
1151}
1152
Rui Ueyama717677a2016-02-11 21:17:59 +00001153void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001154 // Error checking only for now.
1155 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001156 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001157 expect(")");
1158}
1159
Rui Ueyama717677a2016-02-11 21:17:59 +00001160void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001161 // Error checking only for now.
1162 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001163 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001164 StringRef Tok = next();
1165 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001166 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001167 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001168 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001169 return;
1170 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001171 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001172 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001173 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001174 expect(")");
1175}
1176
Eugene Leviantbbe38602016-07-19 09:25:43 +00001177void ScriptParser::readPhdrs() {
1178 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001179 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001180 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001181 Opt.PhdrsCommands.push_back(
1182 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001183 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1184
1185 PhdrCmd.Type = readPhdrType();
1186 do {
1187 Tok = next();
1188 if (Tok == ";")
1189 break;
1190 if (Tok == "FILEHDR")
1191 PhdrCmd.HasFilehdr = true;
1192 else if (Tok == "PHDRS")
1193 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001194 else if (Tok == "AT")
1195 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001196 else if (Tok == "FLAGS") {
1197 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001198 // Passing 0 for the value of dot is a bit of a hack. It means that
1199 // we accept expressions like ".|1".
1200 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001201 expect(")");
1202 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001203 setError("unexpected header attribute: " + Tok);
1204 } while (!Error);
1205 }
1206}
1207
Rui Ueyama717677a2016-02-11 21:17:59 +00001208void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001209 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001210 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001211 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001212 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001213 expect(")");
1214}
1215
Rui Ueyama717677a2016-02-11 21:17:59 +00001216void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001217 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001218 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001219 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001220 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001221 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001222 if (!Cmd) {
1223 if (Tok == "ASSERT")
1224 Cmd = new AssertCommand(readAssert());
1225 else
1226 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001227 }
Rui Ueyama10416562016-08-04 02:03:27 +00001228 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001229 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001230}
1231
Rui Ueyama708019c2016-07-24 18:19:40 +00001232static int precedence(StringRef Op) {
1233 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001234 .Cases("*", "/", 5)
1235 .Cases("+", "-", 4)
1236 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001237 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001238 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001239 .Default(-1);
1240}
1241
Eugene Leviantdb688452016-11-03 10:54:58 +00001242StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001243 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001244 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001245 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001246 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001247}
1248
George Rimarbe394db2016-09-16 20:21:55 +00001249SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001250 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001251 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001252 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001253 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001254 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001255 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001256 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001257 return SortSectionPolicy::None;
1258 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001259}
1260
George Rimar395281c2016-09-16 17:42:10 +00001261// Method reads a list of sequence of excluded files and section globs given in
1262// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1263// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001264// The semantics of that is next:
1265// * Include .foo.1 from every file.
1266// * Include .foo.2 from every file but a.o
1267// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001268std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1269 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001270 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001271 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001272 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001273 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001274 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001275 }
1276
George Rimar601e9892016-09-21 08:53:21 +00001277 std::vector<StringRef> V;
1278 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1279 V.push_back(next());
1280
1281 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001282 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001283 else
1284 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001285 }
George Rimar07171f22016-09-21 15:56:44 +00001286 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001287}
1288
George Rimar07171f22016-09-21 15:56:44 +00001289// Section pattern grammar can have complex expressions, for example:
1290// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1291// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1292// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1293// This methods handles wrapping sequences of excluded files and section globs
1294// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001295InputSectionDescription *
1296ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001297 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001298 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001299 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001300 SortSectionPolicy Outer = readSortKind();
1301 SortSectionPolicy Inner = SortSectionPolicy::Default;
1302 std::vector<SectionPattern> V;
1303 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001304 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001305 Inner = readSortKind();
1306 if (Inner != SortSectionPolicy::Default) {
1307 expect("(");
1308 V = readInputSectionsList();
1309 expect(")");
1310 } else {
1311 V = readInputSectionsList();
1312 }
George Rimar350ece42016-08-03 08:35:59 +00001313 expect(")");
1314 } else {
George Rimar07171f22016-09-21 15:56:44 +00001315 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001316 }
George Rimar0702c4e2016-07-29 15:32:46 +00001317
George Rimar07171f22016-09-21 15:56:44 +00001318 for (SectionPattern &Pat : V) {
1319 Pat.SortInner = Inner;
1320 Pat.SortOuter = Outer;
1321 }
1322
1323 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1324 }
Rui Ueyama10416562016-08-04 02:03:27 +00001325 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001326}
1327
George Rimara2496cb2016-08-30 09:46:59 +00001328InputSectionDescription *
1329ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001330 // Input section wildcard can be surrounded by KEEP.
1331 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001332 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001333 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001334 StringRef FilePattern = next();
1335 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001336 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001337 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001338 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001339 }
George Rimara2496cb2016-08-30 09:46:59 +00001340 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001341}
1342
George Rimar03fc0102016-07-28 07:18:23 +00001343void ScriptParser::readSort() {
1344 expect("(");
1345 expect("CONSTRUCTORS");
1346 expect(")");
1347}
1348
George Rimareefa7582016-08-04 09:29:31 +00001349Expr ScriptParser::readAssert() {
1350 expect("(");
1351 Expr E = readExpr();
1352 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001353 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001354 expect(")");
1355 return [=](uint64_t Dot) {
1356 uint64_t V = E(Dot);
1357 if (!V)
1358 error(Msg);
1359 return V;
1360 };
1361}
1362
Rui Ueyama25150e82016-09-06 17:46:43 +00001363// Reads a FILL(expr) command. We handle the FILL command as an
1364// alias for =fillexp section attribute, which is different from
1365// what GNU linkers do.
1366// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001367std::vector<uint8_t> ScriptParser::readFill() {
1368 expect("(");
1369 std::vector<uint8_t> V = readOutputSectionFiller(next());
1370 expect(")");
1371 expect(";");
1372 return V;
1373}
1374
Rui Ueyama10416562016-08-04 02:03:27 +00001375OutputSectionCommand *
1376ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001377 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001378
1379 // Read an address expression.
1380 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1381 if (peek() != ":")
1382 Cmd->AddrExpr = readExpr();
1383
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001384 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001385
Rui Ueyama83043f22016-10-17 16:01:53 +00001386 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001387 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001388 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001389 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001390 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001391 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001392
Davide Italiano246f6812016-07-22 03:36:24 +00001393 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001394 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001395 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001396 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001397 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001398 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001399
Rui Ueyama83043f22016-10-17 16:01:53 +00001400 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001401 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001402 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001403 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001404 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1405 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001406 else if (Tok == "FILL")
1407 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001408 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001409 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001410 else if (peek() == "(")
1411 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001412 else
1413 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001414 }
George Rimar076fe152016-07-21 06:43:01 +00001415 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001416
Rui Ueyama83043f22016-10-17 16:01:53 +00001417 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001418 Cmd->Filler = readOutputSectionFiller(next());
1419 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001420 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001421
Rui Ueyama10416562016-08-04 02:03:27 +00001422 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001423}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001424
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001425// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1426// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1427//
1428// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1429// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1430// as 32-bit big-endian values. We will do the same as ld.gold does
1431// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001432std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001433 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001434 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001435 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001436 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001437 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001438 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001439}
1440
Petr Hoseka35e39c2016-08-16 01:11:16 +00001441SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001442 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001443 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001444 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001445 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001446 expect(")");
1447 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001448 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001449}
1450
Rafael Espindolac96da112016-11-01 11:30:45 +00001451SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001452 SymbolAssignment *Cmd = nullptr;
1453 if (peek() == "=" || peek() == "+=") {
1454 Cmd = readAssignment(Tok);
1455 expect(";");
1456 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001457 Cmd = readProvideHidden(true, false);
1458 } else if (Tok == "HIDDEN") {
1459 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001460 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001461 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001462 }
1463 return Cmd;
1464}
1465
George Rimar30835ea2016-07-28 21:08:56 +00001466static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1467 if (S == ".")
1468 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001469 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001470}
1471
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001472static bool isAbsolute(StringRef S) {
1473 if (S == ".")
1474 return false;
1475 return ScriptBase->isAbsolute(S);
1476}
1477
George Rimar30835ea2016-07-28 21:08:56 +00001478SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1479 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001480 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001481 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001482 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001483 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1484 // Call readExpr1 to read the whole expression.
1485 E = readExpr1(readParenExpr(), 0);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001486 E.IsAbsolute = []() { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001487 } else {
1488 E = readExpr();
1489 }
George Rimar30835ea2016-07-28 21:08:56 +00001490 if (Op == "+=")
1491 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001492 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001493}
1494
1495// This is an operator-precedence parser to parse a linker
1496// script expression.
1497Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1498
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001499static Expr combine(StringRef Op, Expr L, Expr R) {
1500 if (Op == "*")
1501 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1502 if (Op == "/") {
1503 return [=](uint64_t Dot) -> uint64_t {
1504 uint64_t RHS = R(Dot);
1505 if (RHS == 0) {
1506 error("division by zero");
1507 return 0;
1508 }
1509 return L(Dot) / RHS;
1510 };
1511 }
1512 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001513 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1514 [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001515 if (Op == "-")
1516 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001517 if (Op == "<<")
1518 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1519 if (Op == ">>")
1520 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001521 if (Op == "<")
1522 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1523 if (Op == ">")
1524 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1525 if (Op == ">=")
1526 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1527 if (Op == "<=")
1528 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1529 if (Op == "==")
1530 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1531 if (Op == "!=")
1532 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1533 if (Op == "&")
1534 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001535 if (Op == "|")
1536 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001537 llvm_unreachable("invalid operator");
1538}
1539
Rui Ueyama708019c2016-07-24 18:19:40 +00001540// This is a part of the operator-precedence parser. This function
1541// assumes that the remaining token stream starts with an operator.
1542Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1543 while (!atEOF() && !Error) {
1544 // Read an operator and an expression.
1545 StringRef Op1 = peek();
1546 if (Op1 == "?")
1547 return readTernary(Lhs);
1548 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001549 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001550 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001551 Expr Rhs = readPrimary();
1552
1553 // Evaluate the remaining part of the expression first if the
1554 // next operator has greater precedence than the previous one.
1555 // For example, if we have read "+" and "3", and if the next
1556 // operator is "*", then we'll evaluate 3 * ... part first.
1557 while (!atEOF()) {
1558 StringRef Op2 = peek();
1559 if (precedence(Op2) <= precedence(Op1))
1560 break;
1561 Rhs = readExpr1(Rhs, precedence(Op2));
1562 }
1563
1564 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001565 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001566 return Lhs;
1567}
1568
1569uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001570 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001571 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001572 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001573 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001574 error("unknown constant: " + S);
1575 return 0;
1576}
1577
Rui Ueyama626e0b02016-09-02 18:19:00 +00001578// Parses Tok as an integer. Returns true if successful.
1579// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1580// and decimal numbers. Decimal numbers may have "K" (kilo) or
1581// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001582static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001583 if (Tok.startswith("-")) {
1584 if (!readInteger(Tok.substr(1), Result))
1585 return false;
1586 Result = -Result;
1587 return true;
1588 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001589 if (Tok.startswith_lower("0x"))
1590 return !Tok.substr(2).getAsInteger(16, Result);
1591 if (Tok.endswith_lower("H"))
1592 return !Tok.drop_back().getAsInteger(16, Result);
1593
1594 int Suffix = 1;
1595 if (Tok.endswith_lower("K")) {
1596 Suffix = 1024;
1597 Tok = Tok.drop_back();
1598 } else if (Tok.endswith_lower("M")) {
1599 Suffix = 1024 * 1024;
1600 Tok = Tok.drop_back();
1601 }
1602 if (Tok.getAsInteger(10, Result))
1603 return false;
1604 Result *= Suffix;
1605 return true;
1606}
1607
George Rimare38cbab2016-09-26 19:22:50 +00001608BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1609 int Size = StringSwitch<unsigned>(Tok)
1610 .Case("BYTE", 1)
1611 .Case("SHORT", 2)
1612 .Case("LONG", 4)
1613 .Case("QUAD", 8)
1614 .Default(-1);
1615 if (Size == -1)
1616 return nullptr;
1617
1618 expect("(");
1619 uint64_t Val = 0;
1620 StringRef S = next();
1621 if (!readInteger(S, Val))
1622 setError("unexpected value: " + S);
1623 expect(")");
1624 return new BytesDataCommand(Val, Size);
1625}
1626
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001627StringRef ScriptParser::readParenLiteral() {
1628 expect("(");
1629 StringRef Tok = next();
1630 expect(")");
1631 return Tok;
1632}
1633
Rui Ueyama708019c2016-07-24 18:19:40 +00001634Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001635 if (peek() == "(")
1636 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001637
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001638 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001639
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001640 if (Tok == "~") {
1641 Expr E = readPrimary();
1642 return [=](uint64_t Dot) { return ~E(Dot); };
1643 }
1644 if (Tok == "-") {
1645 Expr E = readPrimary();
1646 return [=](uint64_t Dot) { return -E(Dot); };
1647 }
1648
Rui Ueyama708019c2016-07-24 18:19:40 +00001649 // Built-in functions are parsed here.
1650 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001651 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001652 StringRef Name = readParenLiteral();
George Rimar884e7862016-09-08 08:19:13 +00001653 return
1654 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001655 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001656 if (Tok == "LOADADDR") {
1657 StringRef Name = readParenLiteral();
1658 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1659 }
George Rimareefa7582016-08-04 09:29:31 +00001660 if (Tok == "ASSERT")
1661 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001662 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001663 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001664 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1665 }
1666 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001667 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001668 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001669 }
George Rimarf34f45f2016-09-23 13:17:23 +00001670 if (Tok == "DEFINED") {
1671 expect("(");
1672 StringRef Tok = next();
1673 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001674 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001675 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001676 if (Tok == "SEGMENT_START") {
1677 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001678 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001679 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001680 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001681 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001682 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001683 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001684 if (Tok == "DATA_SEGMENT_ALIGN") {
1685 expect("(");
1686 Expr E = readExpr();
1687 expect(",");
1688 readExpr();
1689 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001690 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001691 }
1692 if (Tok == "DATA_SEGMENT_END") {
1693 expect("(");
1694 expect(".");
1695 expect(")");
1696 return [](uint64_t Dot) { return Dot; };
1697 }
George Rimar276b4e62016-07-26 17:58:44 +00001698 // GNU linkers implements more complicated logic to handle
1699 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1700 // the next page boundary for simplicity.
1701 if (Tok == "DATA_SEGMENT_RELRO_END") {
1702 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001703 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001704 expect(",");
1705 readExpr();
1706 expect(")");
1707 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1708 }
George Rimar9e694502016-07-29 16:18:47 +00001709 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001710 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001711 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001712 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001713 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001714 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001715 return
1716 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001717 }
George Rimare32a3592016-08-10 07:59:34 +00001718 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001719 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001720
George Rimar9f2f7ad2016-09-02 16:01:42 +00001721 // Tok is a literal number.
1722 uint64_t V;
1723 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001724 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001725
1726 // Tok is a symbol name.
1727 if (Tok != "." && !isValidCIdentifier(Tok))
1728 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001729 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1730 [=]() { return isAbsolute(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001731}
1732
1733Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001734 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001735 Expr L = readExpr();
1736 expect(":");
1737 Expr R = readExpr();
1738 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1739}
1740
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001741Expr ScriptParser::readParenExpr() {
1742 expect("(");
1743 Expr E = readExpr();
1744 expect(")");
1745 return E;
1746}
1747
Eugene Leviantbbe38602016-07-19 09:25:43 +00001748std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1749 std::vector<StringRef> Phdrs;
1750 while (!Error && peek().startswith(":")) {
1751 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001752 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001753 }
1754 return Phdrs;
1755}
1756
George Rimar95dd7182016-10-18 10:49:50 +00001757// Read a program header type name. The next token must be a
1758// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001759unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001760 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001761 uint64_t Val;
1762 if (readInteger(Tok, Val))
1763 return Val;
1764
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001765 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001766 .Case("PT_NULL", PT_NULL)
1767 .Case("PT_LOAD", PT_LOAD)
1768 .Case("PT_DYNAMIC", PT_DYNAMIC)
1769 .Case("PT_INTERP", PT_INTERP)
1770 .Case("PT_NOTE", PT_NOTE)
1771 .Case("PT_SHLIB", PT_SHLIB)
1772 .Case("PT_PHDR", PT_PHDR)
1773 .Case("PT_TLS", PT_TLS)
1774 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1775 .Case("PT_GNU_STACK", PT_GNU_STACK)
1776 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001777 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001778 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001779 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001780
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001781 if (Ret == (unsigned)-1) {
1782 setError("invalid program header type: " + Tok);
1783 return PT_NULL;
1784 }
1785 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001786}
1787
Rui Ueyama95769b42016-08-31 20:03:54 +00001788void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001789 // Identifiers start at 2 because 0 and 1 are reserved
1790 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1791 size_t VersionId = Config->VersionDefinitions.size() + 2;
1792 Config->VersionDefinitions.push_back({VerStr, VersionId});
1793
Rui Ueyama83043f22016-10-17 16:01:53 +00001794 if (consume("global:") || peek() != "local:")
George Rimar20b65982016-08-31 09:08:26 +00001795 readGlobal(VerStr);
Rui Ueyama83043f22016-10-17 16:01:53 +00001796 if (consume("local:"))
George Rimarbb6c01e2016-11-12 07:04:15 +00001797 readLocal(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001798 expect("}");
1799
1800 // Each version may have a parent version. For example, "Ver2" defined as
1801 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1802 // version hierarchy is, probably against your instinct, purely for human; the
1803 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1804 if (!VerStr.empty() && peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001805 skip();
George Rimar20b65982016-08-31 09:08:26 +00001806 expect(";");
1807}
1808
George Rimarbb6c01e2016-11-12 07:04:15 +00001809void ScriptParser::readLocal(StringRef VerStr) {
1810 if (consume("*")) {
1811 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1812 expect(";");
1813 return;
1814 }
1815
1816 if (VerStr.empty())
1817 setError("locals list for anonymous version is not supported");
1818
1819 std::vector<SymbolVersion> &Locals = Config->VersionDefinitions.back().Locals;
1820 while (!Error && peek() != "}") {
1821 StringRef Tok = next();
1822 Locals.push_back({unquote(Tok), false, hasWildcard(Tok)});
1823 expect(";");
1824 }
George Rimar20b65982016-08-31 09:08:26 +00001825}
1826
Rui Ueyama2a00b842016-11-15 17:51:07 +00001827void ScriptParser::readVersionExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001828 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001829 expect("{");
1830
1831 for (;;) {
1832 if (peek() == "}" || Error)
1833 break;
George Rimarcd574a52016-09-09 14:35:36 +00001834 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1835 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001836 expect(";");
1837 }
1838
1839 expect("}");
1840 expect(";");
1841}
1842
1843void ScriptParser::readGlobal(StringRef VerStr) {
1844 std::vector<SymbolVersion> *Globals;
1845 if (VerStr.empty())
1846 Globals = &Config->VersionScriptGlobals;
1847 else
1848 Globals = &Config->VersionDefinitions.back().Globals;
1849
1850 for (;;) {
Rui Ueyama83043f22016-10-17 16:01:53 +00001851 if (consume("extern"))
Rui Ueyama2a00b842016-11-15 17:51:07 +00001852 readVersionExtern(Globals);
George Rimar20b65982016-08-31 09:08:26 +00001853
1854 StringRef Cur = peek();
1855 if (Cur == "}" || Cur == "local:" || Error)
1856 return;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001857 skip();
George Rimarcd574a52016-09-09 14:35:36 +00001858 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001859 expect(";");
1860 }
1861}
1862
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001863static bool isUnderSysroot(StringRef Path) {
1864 if (Config->Sysroot == "")
1865 return false;
1866 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1867 if (sys::fs::equivalent(Config->Sysroot, Path))
1868 return true;
1869 return false;
1870}
1871
Rui Ueyama07320e42016-04-20 20:13:41 +00001872void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001873 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001874 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1875}
1876
1877void elf::readVersionScript(MemoryBufferRef MB) {
1878 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001879}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001880
Rui Ueyama07320e42016-04-20 20:13:41 +00001881template class elf::LinkerScript<ELF32LE>;
1882template class elf::LinkerScript<ELF32BE>;
1883template class elf::LinkerScript<ELF64LE>;
1884template class elf::LinkerScript<ELF64BE>;