blob: d6d4c746a7e7d1f22e96782a1d055e5fc4181ffd [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 Ueyamaf7c5fbb2015-09-30 17:23:26 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama717677a2016-02-11 21:17:59 +000014#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000015#include "Config.h"
16#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000017#include "InputSection.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000018#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000019#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000020#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000021#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000022#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000023#include "Symbols.h"
George Rimar3fb5a6d2016-11-29 16:05:27 +000024#include "SyntheticSections.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000025#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000026#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000030#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000033#include "llvm/Support/Endian.h"
34#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000035#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/MathExtras.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000037#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <iterator>
43#include <limits>
44#include <memory>
45#include <string>
46#include <tuple>
47#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000048
49using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000050using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000051using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000052using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000053using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000054using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000055
George Rimar884e7862016-09-08 08:19:13 +000056LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000057ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000058
Meador Inge8f1f3c42017-01-09 18:36:57 +000059template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000060 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Meador Inge8f1f3c42017-01-09 18:36:57 +000061 Symbol *Sym = Symtab<ELFT>::X->addUndefined(
62 Cmd->Name, /*IsLocal=*/false, STB_GLOBAL, Visibility,
63 /*Type*/ 0,
64 /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
Eugene Leviant20d03192016-09-16 15:30:47 +000065
Meador Inge8f1f3c42017-01-09 18:36:57 +000066 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, /*IsLocal=*/false,
67 Visibility, STT_NOTYPE, 0, 0, nullptr,
68 nullptr);
69 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000070}
71
Meador Inge8f1f3c42017-01-09 18:36:57 +000072template <class ELFT> static SymbolBody *addSynthetic(SymbolAssignment *Cmd) {
73 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Eugene Leviantafaa9342016-11-16 09:49:39 +000074 const OutputSectionBase *Sec =
75 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
Meador Inge8f1f3c42017-01-09 18:36:57 +000076 Symbol *Sym = Symtab<ELFT>::X->addUndefined(
77 Cmd->Name, /*IsLocal=*/false, STB_GLOBAL, Visibility,
78 /*Type*/ 0,
79 /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
Eugene Leviantafaa9342016-11-16 09:49:39 +000080
Meador Inge8f1f3c42017-01-09 18:36:57 +000081 replaceBody<DefinedSynthetic>(Sym, Cmd->Name, 0, Sec);
82 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000083}
84
Rui Ueyama22375f22016-11-25 18:51:54 +000085static bool isUnderSysroot(StringRef Path) {
86 if (Config->Sysroot == "")
87 return false;
88 for (; !Path.empty(); Path = sys::path::parent_path(Path))
89 if (sys::fs::equivalent(Config->Sysroot, Path))
90 return true;
91 return false;
92}
93
Meador Inge8f1f3c42017-01-09 18:36:57 +000094template <class ELFT> static void assignSymbol(SymbolAssignment *Cmd) {
95 // If there are sections, then let the value be assigned later in
96 // `assignAddresses`.
97 if (ScriptConfig->HasSections)
98 return;
99
100 uint64_t Value = Cmd->Expression(0);
101 if (Cmd->Expression.IsAbsolute()) {
102 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Value;
103 } else {
104 const OutputSectionBase *Sec = Cmd->Expression.Section();
105 if (Sec)
106 cast<DefinedSynthetic>(Cmd->Sym)->Value = Value - Sec->Addr;
107 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000108}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000109
110template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000111 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000112 return;
113
114 // If a symbol was in PROVIDE(), we need to define it only when
115 // it is a referenced undefined symbol.
Rui Ueyama16024212016-08-11 23:22:52 +0000116 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000117 if (Cmd->Provide && (!B || B->isDefined()))
118 return;
119
120 // Otherwise, create a new symbol if one does not exist or an
121 // undefined one does exist.
122 if (Cmd->Expression.IsAbsolute())
123 Cmd->Sym = addRegular<ELFT>(Cmd);
124 else
125 Cmd->Sym = addSynthetic<ELFT>(Cmd);
126 assignSymbol<ELFT>(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000127}
128
George Rimar076fe152016-07-21 06:43:01 +0000129bool SymbolAssignment::classof(const BaseCommand *C) {
130 return C->Kind == AssignmentKind;
131}
132
133bool OutputSectionCommand::classof(const BaseCommand *C) {
134 return C->Kind == OutputSectionKind;
135}
136
George Rimareea31142016-07-21 14:26:59 +0000137bool InputSectionDescription::classof(const BaseCommand *C) {
138 return C->Kind == InputSectionKind;
139}
140
George Rimareefa7582016-08-04 09:29:31 +0000141bool AssertCommand::classof(const BaseCommand *C) {
142 return C->Kind == AssertKind;
143}
144
George Rimare38cbab2016-09-26 19:22:50 +0000145bool BytesDataCommand::classof(const BaseCommand *C) {
146 return C->Kind == BytesDataKind;
147}
148
Eugene Zelenko22886a22016-11-05 01:00:56 +0000149template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
150template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000151
Rui Ueyamae0be2902016-11-21 02:10:12 +0000152template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
153 if (S->getFile())
154 return sys::path::filename(S->getFile()->getName());
155 return "";
156}
157
Rui Ueyama07320e42016-04-20 20:13:41 +0000158template <class ELFT>
159bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000160 for (InputSectionDescription *ID : Opt.KeptSections)
161 if (ID->FilePat.match(basename(S)))
162 for (SectionPattern &P : ID->SectionPatterns)
163 if (P.SectionPat.match(S->Name))
164 return true;
George Rimareea31142016-07-21 14:26:59 +0000165 return false;
166}
167
George Rimar575208c2016-09-15 19:15:12 +0000168static bool comparePriority(InputSectionData *A, InputSectionData *B) {
169 return getPriority(A->Name) < getPriority(B->Name);
170}
171
Rafael Espindolac0028d32016-09-08 20:47:52 +0000172static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000173 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000174}
George Rimar350ece42016-08-03 08:35:59 +0000175
Rafael Espindolac0028d32016-09-08 20:47:52 +0000176static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000177 // ">" is not a mistake. Larger alignments are placed before smaller
178 // alignments in order to reduce the amount of padding necessary.
179 // This is compatible with GNU.
180 return A->Alignment > B->Alignment;
181}
George Rimar350ece42016-08-03 08:35:59 +0000182
Rafael Espindolac0028d32016-09-08 20:47:52 +0000183static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000184getComparator(SortSectionPolicy K) {
185 switch (K) {
186 case SortSectionPolicy::Alignment:
187 return compareAlignment;
188 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000189 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000190 case SortSectionPolicy::Priority:
191 return comparePriority;
192 default:
193 llvm_unreachable("unknown sort policy");
194 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000195}
George Rimar0702c4e2016-07-29 15:32:46 +0000196
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000197template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000198static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000199 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000200 if (Kind == ConstraintKind::NoConstraint)
201 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000202 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000203 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000204 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000205 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000206 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
207 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000208}
209
George Rimar07171f22016-09-21 15:56:44 +0000210static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000211 SortSectionPolicy K) {
212 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000213 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000214}
215
Rafael Espindolad3190792016-09-16 15:10:23 +0000216// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000217template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000218void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000219 // Collects all sections that satisfy constraints of I
220 // and attach them to I.
221 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000222 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000223
224 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000225 if (!S->Live || S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000226 continue;
227
Rui Ueyamae0be2902016-11-21 02:10:12 +0000228 StringRef Filename = basename(S);
229 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
230 continue;
231 if (!Pat.SectionPat.match(S->Name))
232 continue;
233 I->Sections.push_back(S);
234 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000235 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000236
George Rimar07171f22016-09-21 15:56:44 +0000237 // Sort sections as instructed by SORT-family commands and --sort-section
238 // option. Because SORT-family commands can be nested at most two depth
239 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
240 // line option is respected even if a SORT command is given, the exact
241 // behavior we have here is a bit complicated. Here are the rules.
242 //
243 // 1. If two SORT commands are given, --sort-section is ignored.
244 // 2. If one SORT command is given, and if it is not SORT_NONE,
245 // --sort-section is handled as an inner SORT command.
246 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
247 // 4. If no SORT command is given, sort according to --sort-section.
248 InputSectionData **Begin = I->Sections.data() + SizeBefore;
249 InputSectionData **End = I->Sections.data() + I->Sections.size();
250 if (Pat.SortOuter != SortSectionPolicy::None) {
251 if (Pat.SortInner == SortSectionPolicy::Default)
252 sortSections(Begin, End, Config->SortSection);
253 else
254 sortSections(Begin, End, Pat.SortInner);
255 sortSections(Begin, End, Pat.SortOuter);
256 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000257 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000258}
259
260template <class ELFT>
261void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
262 for (InputSectionBase<ELFT> *S : V) {
263 S->Live = false;
264 reportDiscarded(S);
265 }
266}
267
George Rimar06ae6832016-08-12 09:07:57 +0000268template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000269std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000270LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000271 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000272
George Rimar06ae6832016-08-12 09:07:57 +0000273 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000274 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
275 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000276 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000277 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000278 for (InputSectionData *S : Cmd->Sections)
279 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000280 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000281
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000282 return Ret;
283}
284
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000285template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000286void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
287 InputSectionBase<ELFT> *Sec,
288 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000289 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000290 bool IsNew;
Rafael Espindola33713982017-01-05 14:20:35 +0000291 std::tie(OutSec, IsNew) = Factory.create(Sec, Name);
Eugene Leviant20d03192016-09-16 15:30:47 +0000292 if (IsNew)
293 OutputSections->push_back(OutSec);
294 OutSec->addSection(Sec);
295}
296
297template <class ELFT>
298void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000299 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
300 auto Iter = Opt.Commands.begin() + I;
301 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000302
303 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000304 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
Meador Inge8f1f3c42017-01-09 18:36:57 +0000305 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000306 continue;
307 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000308
Eugene Leviant20d03192016-09-16 15:30:47 +0000309 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
310 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000311 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000312 // will not be called, so ASSERT should be evaluated now.
313 if (!Opt.HasSections)
314 Cmd->Expression(0);
315 continue;
316 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000317
Eugene Leviantceabe802016-08-11 07:56:43 +0000318 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000319 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
320
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000321 // The output section name `/DISCARD/' is special.
322 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000323 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000324 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000325 continue;
326 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000327
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000328 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
329 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
330 // sections satisfy a given constraint. If not, a directive is handled
331 // as if it wasn't present from the beginning.
332 //
333 // Because we'll iterate over Commands many more times, the easiest
334 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000335 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
336 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000337 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000338 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000339 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000340 continue;
341 }
342
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000343 // A directive may contain symbol definitions like this:
344 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000345 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
346 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
Meador Inge8f1f3c42017-01-09 18:36:57 +0000347 addSymbol<ELFT>(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000348
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000349 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
350 // is given, input sections are aligned to that value, whether the
351 // given value is larger or smaller than the original section alignment.
352 if (Cmd->SubalignExpr) {
353 uint32_t Subalign = Cmd->SubalignExpr(0);
354 for (InputSectionBase<ELFT> *S : V)
355 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000356 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000357
358 // Add input sections to an output section.
359 for (InputSectionBase<ELFT> *S : V)
360 addSection(Factory, S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000361 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000362 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000363}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000364
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000365// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000366template <class ELFT>
George Rimar93c64022016-12-15 15:38:09 +0000367void LinkerScript<ELFT>::addOrphanSections(
368 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000369 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000370 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000371 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000372}
373
Eugene Leviantdb741e72016-09-07 07:08:43 +0000374// Sets value of a section-defined symbol. Two kinds of
375// symbols are processed: synthetic symbols, whose value
376// is an offset from beginning of section and regular
377// symbols whose value is absolute.
378template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000379static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000380 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000381 if (!Cmd->Sym)
382 return;
383
Rui Ueyama4f2f50d2016-12-21 08:40:09 +0000384 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000385 Body->Section = Cmd->Expression.Section();
386 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000387 return;
388 }
389 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000390 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000391}
392
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000393template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000394 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000395}
396
Rafael Espindolad3190792016-09-16 15:10:23 +0000397template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
398 if (!AlreadyOutputIS.insert(S).second)
399 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000400 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000401
Rafael Espindolad3190792016-09-16 15:10:23 +0000402 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
403 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000404 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000405 Pos += S->getSize();
406
407 // Update output section size after adding each section. This is so that
408 // SIZEOF works correctly in the case below:
409 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000410 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000411
Rafael Espindola7252ae52016-09-22 12:00:08 +0000412 if (IsTbss)
413 ThreadBssOffset = Pos - Dot;
414 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000415 Dot = Pos;
416}
417
418template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000419 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
420 return;
421 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000422 for (InputSection<ELFT> *I : OutSec->Sections)
423 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000424 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000425 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000426 }
427}
428
429template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000430void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000431 if (CurOutSec == Sec)
432 return;
433 if (AlreadyOutputOS.count(Sec))
434 return;
435
436 flush();
437 CurOutSec = Sec;
438
Rafael Espindola04a2e342016-11-09 01:42:41 +0000439 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000440 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000441
442 // If neither AT nor AT> is specified for an allocatable section, the linker
443 // will set the LMA such that the difference between VMA and LMA for the
444 // section is the same as the preceding output section in the same region
445 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
446 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000447}
448
449template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000450 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000451 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
452 if (AssignCmd->Name == ".") {
453 // Update to location counter means update to section size.
George Rimar14460e02016-12-15 07:27:28 +0000454 uintX_t Val = AssignCmd->Expression(Dot);
455 if (Val < Dot)
456 error("unable to move location counter backward for: " +
457 CurOutSec->Name);
458 Dot = Val;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000459 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000460 return;
461 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000462 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000463 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000464 }
George Rimare38cbab2016-09-26 19:22:50 +0000465
466 // Handle BYTE(), SHORT(), LONG(), or QUAD().
467 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000468 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000469 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000470 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000471 return;
472 }
473
Meador Ingeb2d99d62016-11-22 18:01:50 +0000474 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
475 AssertCmd->Expression(Dot);
476 return;
477 }
478
George Rimare38cbab2016-09-26 19:22:50 +0000479 // It handles single input section description command,
480 // calculates and assigns the offsets for each section and also
481 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000482 auto &ICmd = cast<InputSectionDescription>(Base);
483 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000484 // We tentatively added all synthetic sections at the beginning and removed
485 // empty ones afterwards (because there is no way to know whether they were
486 // going be empty or not other than actually running linker scripts.)
487 // We need to ignore remains of empty sections.
488 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
489 if (Sec->empty())
490 continue;
491
Rafael Espindolad3190792016-09-16 15:10:23 +0000492 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
493 switchTo(IB->OutSec);
494 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
495 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000496 else
497 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000498 }
499}
500
George Rimar8f66df92016-08-12 20:38:20 +0000501template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000502static std::vector<OutputSectionBase *>
503findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
504 std::vector<OutputSectionBase *> Ret;
505 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000506 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000507 Ret.push_back(Sec);
508 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000509}
510
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000511// This function assigns offsets to input sections and an output section
512// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000513template <class ELFT>
514void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000515 if (Cmd->LMAExpr)
516 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000517 std::vector<OutputSectionBase *> Sections =
518 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000519 if (Sections.empty())
520 return;
521 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000522
Rafael Espindolad3190792016-09-16 15:10:23 +0000523 // Find the last section output location. We will output orphan sections
524 // there so that end symbols point to the correct location.
525 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
526 [](const std::unique_ptr<BaseCommand> &Cmd) {
527 return !isa<SymbolAssignment>(*Cmd);
528 })
529 .base();
530 for (auto I = Cmd->Commands.begin(); I != E; ++I)
531 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000532 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000533 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000534 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000535 std::for_each(E, Cmd->Commands.end(),
536 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000537}
538
Rafael Espindola07fe6122016-11-14 14:23:35 +0000539template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000540 // It is common practice to use very generic linker scripts. So for any
541 // given run some of the output sections in the script will be empty.
542 // We could create corresponding empty output sections, but that would
543 // clutter the output.
544 // We instead remove trivially empty sections. The bfd linker seems even
545 // more aggressive at removing them.
546 auto Pos = std::remove_if(
547 Opt.Commands.begin(), Opt.Commands.end(),
548 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000549 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
550 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
551 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000552 });
553 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000554}
555
Rafael Espindola6a537372016-11-14 14:33:49 +0000556static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
557 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
558 if (!isa<InputSectionDescription>(*I))
559 return false;
560 return true;
561}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000562
Rafael Espindola6a537372016-11-14 14:33:49 +0000563template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000564 // If the output section contains only symbol assignments, create a
565 // corresponding output section. The bfd linker seems to only create them if
566 // '.' is assigned to, but creating these section should not have any bad
567 // consequeces and gives us a section to put the symbol in.
568 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000569 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000570 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
571 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
572 if (!Cmd)
573 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000574 std::vector<OutputSectionBase *> Secs =
575 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000576 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000577 Flags = Secs[0]->Flags;
578 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000579 continue;
580 }
581
Rafael Espindola6a537372016-11-14 14:33:49 +0000582 if (isAllSectionDescription(*Cmd))
583 continue;
584
Rui Ueyama95642b92016-11-01 23:09:07 +0000585 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000586 OutputSections->push_back(OutSec);
587 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000588}
589
590template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
591 placeOrphanSections();
592
593 // If output section command doesn't specify any segments,
594 // and we haven't previously assigned any section to segment,
595 // then we simply assign section to the very first load segment.
596 // Below is an example of such linker script:
597 // PHDRS { seg PT_LOAD; }
598 // SECTIONS { .aaa : { *(.aaa) } }
599 std::vector<StringRef> DefPhdrs;
600 auto FirstPtLoad =
601 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
602 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
603 if (FirstPtLoad != Opt.PhdrsCommands.end())
604 DefPhdrs.push_back(FirstPtLoad->Name);
605
606 // Walk the commands and propagate the program headers to commands that don't
607 // explicitly specify them.
608 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
609 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
610 if (!Cmd)
611 continue;
612 if (Cmd->Phdrs.empty())
613 Cmd->Phdrs = DefPhdrs;
614 else
615 DefPhdrs = Cmd->Phdrs;
616 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000617
618 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000619}
620
Rafael Espindola15c57952016-09-22 18:05:49 +0000621// When placing orphan sections, we want to place them after symbol assignments
622// so that an orphan after
623// begin_foo = .;
624// foo : { *(foo) }
625// end_foo = .;
626// doesn't break the intended meaning of the begin/end symbols.
627// We don't want to go over sections since Writer<ELFT>::sortSections is the
628// one in charge of deciding the order of the sections.
629// We don't want to go over alignments, since doing so in
630// rx_sec : { *(rx_sec) }
631// . = ALIGN(0x1000);
632// /* The RW PT_LOAD starts here*/
633// rw_sec : { *(rw_sec) }
634// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000635static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000636 if (isa<OutputSectionCommand>(Cmd))
637 return false;
638 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
639 if (!Assign)
640 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000641 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000642}
643
Rafael Espindola337f9032016-11-14 14:13:32 +0000644// Orphan sections are sections present in the input files which are not
645// explicitly placed into the output file by the linker script. This just
646// places them in the order already decided in OutputSections.
George Rimar93c64022016-12-15 15:38:09 +0000647template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000648 // The OutputSections are already in the correct order.
649 // This loops creates or moves commands as needed so that they are in the
650 // correct order.
651 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000652
653 // As a horrible special case, skip the first . assignment if it is before any
654 // section. We do this because it is common to set a load address by starting
655 // the script with ". = 0xabcd" and the expectation is that every section is
656 // after that.
657 auto FirstSectionOrDotAssignment =
658 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
659 [](const std::unique_ptr<BaseCommand> &Cmd) {
660 if (isa<OutputSectionCommand>(*Cmd))
661 return true;
662 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
663 if (!Assign)
664 return false;
665 return Assign->Name == ".";
666 });
667 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
668 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
669 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
670 ++CmdIndex;
671 }
672
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000673 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000674 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000675
676 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000677 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000678 auto CmdIter = Opt.Commands.begin() + CmdIndex;
679 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000680 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000681 ++CmdIter;
682 ++CmdIndex;
683 }
684
685 auto Pos =
686 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
687 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
688 return Cmd && Cmd->Name == Name;
689 });
690 if (Pos == E) {
691 Opt.Commands.insert(CmdIter,
692 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000693 ++CmdIndex;
694 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000695 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000696
697 // Continue from where we found it.
698 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000699 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000700}
701
702template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000703void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000704 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000705 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000706
George Rimar076fe152016-07-21 06:43:01 +0000707 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
708 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000709 if (Cmd->Name == ".") {
710 Dot = Cmd->Expression(Dot);
711 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000712 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000713 }
George Rimar652852c2016-04-16 10:10:32 +0000714 continue;
715 }
716
George Rimareefa7582016-08-04 09:29:31 +0000717 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
718 Cmd->Expression(Dot);
719 continue;
720 }
721
George Rimar076fe152016-07-21 06:43:01 +0000722 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000723 if (Cmd->AddrExpr)
724 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000725 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000726 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000727
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000728 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000729 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000730 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000731 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000732 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000733 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000734 }
735
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000736 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola1c570072016-11-21 19:59:33 +0000737 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
738 // now that we know we have space.
Rafael Espindola5967c972016-12-19 21:21:07 +0000739 if (HeaderSize <= MinVA && !hasPhdrsCommands())
740 allocateHeaders<ELFT>(Phdrs, *OutputSections);
Rafael Espindola1c570072016-11-21 19:59:33 +0000741
742 // ELF and Program headers need to be right before the first section in
743 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000744 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000745 Out<ELFT>::ElfHeader->Addr = MinVA;
746 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
George Rimar652852c2016-04-16 10:10:32 +0000747}
748
Rui Ueyama464daad2016-08-22 04:55:20 +0000749// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000750template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
751 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000752
Rui Ueyama464daad2016-08-22 04:55:20 +0000753 // Process PHDRS and FILEHDR keywords because they are not
754 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000755 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000756 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000757 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000758
759 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000760 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000761 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000762 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000763
764 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000765 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000766 Phdr.HasLMA = true;
767 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000768 }
769
Rui Ueyama464daad2016-08-22 04:55:20 +0000770 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000771 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000772 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000773 break;
774
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000775 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000776 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000777 Ret[Id].add(Sec);
778 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000779 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000780 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000781 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000782 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000783}
784
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000785template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
786 // Ignore .interp section in case we have PHDRS specification
787 // and PT_INTERP isn't listed.
788 return !Opt.PhdrsCommands.empty() &&
789 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
790 return Cmd.Type == PT_INTERP;
791 }) == Opt.PhdrsCommands.end();
792}
793
George Rimar93c64022016-12-15 15:38:09 +0000794template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000795 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
796 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
797 if (Cmd->Name == Name)
798 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000799 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000800}
801
George Rimare38cbab2016-09-26 19:22:50 +0000802template <class ELFT>
803static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
804 const endianness E = ELFT::TargetEndianness;
805
806 switch (Size) {
807 case 1:
808 *Buf = (uint8_t)Data;
809 break;
810 case 2:
811 write16<E>(Buf, Data);
812 break;
813 case 4:
814 write32<E>(Buf, Data);
815 break;
816 case 8:
817 write64<E>(Buf, Data);
818 break;
819 default:
820 llvm_unreachable("unsupported Size argument");
821 }
822}
823
824template <class ELFT>
825void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
826 int I = getSectionIndex(Name);
827 if (I == INT_MAX)
828 return;
829
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000830 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
831 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
832 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000833 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000834}
835
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000836template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000837 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
838 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000839 if (Cmd->LMAExpr && Cmd->Name == Name)
840 return true;
841 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000842}
843
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000844// Returns the index of the given section name in linker script
845// SECTIONS commands. Sections are laid out as the same order as they
846// were in the script. If a given name did not appear in the script,
847// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000848template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000849 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
850 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000851 if (Cmd->Name == Name)
852 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000853 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000854}
855
Eugene Leviantbbe38602016-07-19 09:25:43 +0000856template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
857 return !Opt.PhdrsCommands.empty();
858}
859
George Rimar9e694502016-07-29 16:18:47 +0000860template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000861const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
862 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000863 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000864
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000865 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000866 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000867 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000868
869 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000870 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000871}
872
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000873// This function is essentially the same as getOutputSection(Name)->Size,
874// but it won't print out an error message if a given section is not found.
875//
876// Linker script does not create an output section if its content is empty.
877// We want to allow SIZEOF(.foo) where .foo is a section which happened to
878// be empty. That is why this function is different from getOutputSection().
879template <class ELFT>
880uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
881 for (OutputSectionBase *Sec : *OutputSections)
882 if (Sec->getName() == Name)
883 return Sec->Size;
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
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000891template <class ELFT>
892uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar884e7862016-09-08 08:19:13 +0000893 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
894 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000895 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000896 return 0;
897}
898
George Rimarf34f45f2016-09-23 13:17:23 +0000899template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
900 return Symtab<ELFT>::X->find(S) != nullptr;
901}
902
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000903template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
904 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
905 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
906 return DR && !DR->Section;
907}
908
Eugene Leviantafaa9342016-11-16 09:49:39 +0000909// Gets section symbol belongs to. Symbol "." doesn't belong to any
910// specific section but isn't absolute at the same time, so we try
911// to find suitable section for it as well.
912template <class ELFT>
913const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
914 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
915 if (!Sym) {
916 if (OutputSections->empty())
917 return nullptr;
918 return CurOutSec ? CurOutSec : (*OutputSections)[0];
919 }
920
921 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
922 return DR->Section ? DR->Section->OutSec : nullptr;
Rui Ueyama4f2f50d2016-12-21 08:40:09 +0000923 if (auto *DS = dyn_cast_or_null<DefinedSynthetic>(Sym))
Eugene Leviantafaa9342016-11-16 09:49:39 +0000924 return DS->Section;
925
926 return nullptr;
927}
928
Eugene Leviantbbe38602016-07-19 09:25:43 +0000929// Returns indices of ELF headers containing specific section, identified
930// by Name. Each index is a zero based number of ELF header listed within
931// PHDRS {} script block.
932template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000933std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000934 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
935 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000936 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000937 continue;
938
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000939 std::vector<size_t> Ret;
940 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000941 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000942 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000943 }
George Rimar31d842f2016-07-20 16:43:03 +0000944 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000945}
946
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000947template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +0000948size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000949 size_t I = 0;
950 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
951 if (Cmd.Name == PhdrName)
952 return I;
953 ++I;
954 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000955 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000956 return 0;
957}
958
Eugene Leviant03ff0162016-11-21 15:49:56 +0000959class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000960 typedef void (ScriptParser::*Handler)();
961
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000962public:
Rui Ueyama22375f22016-11-25 18:51:54 +0000963 ScriptParser(MemoryBufferRef MB)
964 : ScriptParserBase(MB),
965 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +0000966
George Rimar20b65982016-08-31 09:08:26 +0000967 void readLinkerScript();
968 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +0000969 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000970
971private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000972 void addFile(StringRef Path);
973
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000974 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000975 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000976 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000977 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000978 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000979 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000980 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000981 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000982 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000983 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000984 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000985 void readVersion();
986 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000987
Rui Ueyama113cdec2016-07-24 23:05:57 +0000988 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000989 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000990 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000991 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000992 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000993 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000994 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000995 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000996 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000997 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000998 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000999 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001000 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001001 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001002 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001003 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001004
1005 Expr readExpr();
1006 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001007 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001008 Expr readPrimary();
1009 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001010 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001011
George Rimar20b65982016-08-31 09:08:26 +00001012 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001013 std::vector<SymbolVersion> readVersionExtern();
1014 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001015 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001016 std::vector<SymbolVersion> readSymbols();
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001017 void readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001018
Rui Ueyama07320e42016-04-20 20:13:41 +00001019 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001020 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001021};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001022
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001023void ScriptParser::readDynamicList() {
1024 expect("{");
1025 readAnonymousDeclaration();
1026 if (!atEOF())
1027 setError("EOF expected, but got " + next());
1028}
1029
George Rimar20b65982016-08-31 09:08:26 +00001030void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001031 readVersionScriptCommand();
1032 if (!atEOF())
1033 setError("EOF expected, but got " + next());
1034}
1035
1036void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001037 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001038 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001039 return;
1040 }
1041
Rui Ueyama95769b42016-08-31 20:03:54 +00001042 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001043 StringRef VerStr = next();
1044 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001045 setError("anonymous version definition is used in "
1046 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001047 return;
1048 }
1049 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001050 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001051 }
1052}
1053
Rui Ueyama95769b42016-08-31 20:03:54 +00001054void ScriptParser::readVersion() {
1055 expect("{");
1056 readVersionScriptCommand();
1057 expect("}");
1058}
1059
George Rimar20b65982016-08-31 09:08:26 +00001060void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001061 while (!atEOF()) {
1062 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001063 if (Tok == ";")
1064 continue;
1065
Eugene Leviant20d03192016-09-16 15:30:47 +00001066 if (Tok == "ASSERT") {
1067 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1068 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001069 readEntry();
1070 } else if (Tok == "EXTERN") {
1071 readExtern();
1072 } else if (Tok == "GROUP" || Tok == "INPUT") {
1073 readGroup();
1074 } else if (Tok == "INCLUDE") {
1075 readInclude();
1076 } else if (Tok == "OUTPUT") {
1077 readOutput();
1078 } else if (Tok == "OUTPUT_ARCH") {
1079 readOutputArch();
1080 } else if (Tok == "OUTPUT_FORMAT") {
1081 readOutputFormat();
1082 } else if (Tok == "PHDRS") {
1083 readPhdrs();
1084 } else if (Tok == "SEARCH_DIR") {
1085 readSearchDir();
1086 } else if (Tok == "SECTIONS") {
1087 readSections();
1088 } else if (Tok == "VERSION") {
1089 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001090 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001091 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001092 } else {
George Rimar57610422016-03-11 14:43:02 +00001093 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001094 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001095 }
1096}
1097
Rui Ueyama717677a2016-02-11 21:17:59 +00001098void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001099 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001100 SmallString<128> PathData;
1101 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001102 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001103 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001104 return;
1105 }
1106 }
1107
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001108 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001109 Driver->addFile(S);
1110 } else if (S.startswith("=")) {
1111 if (Config->Sysroot.empty())
1112 Driver->addFile(S.substr(1));
1113 else
1114 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1115 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001116 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001117 } else if (sys::fs::exists(S)) {
1118 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001119 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001120 if (Optional<std::string> Path = findFromSearchPaths(S))
1121 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001122 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001123 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001124 }
1125}
1126
Rui Ueyama717677a2016-02-11 21:17:59 +00001127void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001128 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001129 bool Orig = Config->AsNeeded;
1130 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001131 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001132 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001133 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001134}
1135
Rui Ueyama717677a2016-02-11 21:17:59 +00001136void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001137 // -e <symbol> takes predecence over ENTRY(<symbol>).
1138 expect("(");
1139 StringRef Tok = next();
1140 if (Config->Entry.empty())
1141 Config->Entry = Tok;
1142 expect(")");
1143}
1144
Rui Ueyama717677a2016-02-11 21:17:59 +00001145void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001146 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001147 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001148 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001149}
1150
Rui Ueyama717677a2016-02-11 21:17:59 +00001151void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001152 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001153 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001154 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001155 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001156 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001157 else
George Rimarcd574a52016-09-09 14:35:36 +00001158 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001159 }
1160}
1161
Rui Ueyama717677a2016-02-11 21:17:59 +00001162void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001163 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001164
George Rimard4500652016-12-21 09:42:25 +00001165 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1166 // The file will be searched for in the current directory, and in any
1167 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001168 if (sys::fs::exists(Tok)) {
1169 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1170 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001171 return;
1172 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001173 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1174 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1175 tokenize(*MB);
1176 return;
1177 }
1178 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001179}
1180
Rui Ueyama717677a2016-02-11 21:17:59 +00001181void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001182 // -o <file> takes predecence over OUTPUT(<file>).
1183 expect("(");
1184 StringRef Tok = next();
1185 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001186 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001187 expect(")");
1188}
1189
Rui Ueyama717677a2016-02-11 21:17:59 +00001190void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001191 // Error checking only for now.
1192 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001193 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001194 expect(")");
1195}
1196
Rui Ueyama717677a2016-02-11 21:17:59 +00001197void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001198 // Error checking only for now.
1199 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001200 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001201 StringRef Tok = next();
1202 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001203 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001204 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001205 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001206 return;
1207 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001208 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001209 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001210 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001211 expect(")");
1212}
1213
Eugene Leviantbbe38602016-07-19 09:25:43 +00001214void ScriptParser::readPhdrs() {
1215 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001216 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001217 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001218 Opt.PhdrsCommands.push_back(
1219 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001220 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1221
1222 PhdrCmd.Type = readPhdrType();
1223 do {
1224 Tok = next();
1225 if (Tok == ";")
1226 break;
1227 if (Tok == "FILEHDR")
1228 PhdrCmd.HasFilehdr = true;
1229 else if (Tok == "PHDRS")
1230 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001231 else if (Tok == "AT")
1232 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001233 else if (Tok == "FLAGS") {
1234 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001235 // Passing 0 for the value of dot is a bit of a hack. It means that
1236 // we accept expressions like ".|1".
1237 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001238 expect(")");
1239 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001240 setError("unexpected header attribute: " + Tok);
1241 } while (!Error);
1242 }
1243}
1244
Rui Ueyama717677a2016-02-11 21:17:59 +00001245void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001246 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001247 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001248 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001249 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001250 expect(")");
1251}
1252
Rui Ueyama717677a2016-02-11 21:17:59 +00001253void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001254 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001255 // -no-rosegment is used to avoid placing read only non-executable sections in
1256 // their own segment. We do the same if SECTIONS command is present in linker
1257 // script. See comment for computeFlags().
1258 Config->SingleRoRx = true;
1259
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001260 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001261 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001262 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001263 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001264 if (!Cmd) {
1265 if (Tok == "ASSERT")
1266 Cmd = new AssertCommand(readAssert());
1267 else
1268 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001269 }
Rui Ueyama10416562016-08-04 02:03:27 +00001270 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001271 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001272}
1273
Rui Ueyama708019c2016-07-24 18:19:40 +00001274static int precedence(StringRef Op) {
1275 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001276 .Cases("*", "/", 5)
1277 .Cases("+", "-", 4)
1278 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001279 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001280 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001281 .Default(-1);
1282}
1283
Eugene Leviantdb688452016-11-03 10:54:58 +00001284StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001285 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001286 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001287 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001288 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001289}
1290
George Rimarbe394db2016-09-16 20:21:55 +00001291SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001292 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001293 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001294 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001295 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001296 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001297 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001298 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001299 return SortSectionPolicy::None;
1300 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001301}
1302
George Rimar395281c2016-09-16 17:42:10 +00001303// Method reads a list of sequence of excluded files and section globs given in
1304// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1305// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001306// The semantics of that is next:
1307// * Include .foo.1 from every file.
1308// * Include .foo.2 from every file but a.o
1309// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001310std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1311 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001312 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001313 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001314 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001315 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001316 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001317 }
1318
George Rimar601e9892016-09-21 08:53:21 +00001319 std::vector<StringRef> V;
1320 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1321 V.push_back(next());
1322
1323 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001324 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001325 else
1326 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001327 }
George Rimar07171f22016-09-21 15:56:44 +00001328 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001329}
1330
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001331// Reads contents of "SECTIONS" directive. That directive contains a
1332// list of glob patterns for input sections. The grammar is as follows.
1333//
1334// <patterns> ::= <section-list>
1335// | <sort> "(" <section-list> ")"
1336// | <sort> "(" <sort> "(" <section-list> ")" ")"
1337//
1338// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1339// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1340//
1341// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001342InputSectionDescription *
1343ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001344 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001345 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001346 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001347 SortSectionPolicy Outer = readSortKind();
1348 SortSectionPolicy Inner = SortSectionPolicy::Default;
1349 std::vector<SectionPattern> V;
1350 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001351 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001352 Inner = readSortKind();
1353 if (Inner != SortSectionPolicy::Default) {
1354 expect("(");
1355 V = readInputSectionsList();
1356 expect(")");
1357 } else {
1358 V = readInputSectionsList();
1359 }
George Rimar350ece42016-08-03 08:35:59 +00001360 expect(")");
1361 } else {
George Rimar07171f22016-09-21 15:56:44 +00001362 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001363 }
George Rimar0702c4e2016-07-29 15:32:46 +00001364
George Rimar07171f22016-09-21 15:56:44 +00001365 for (SectionPattern &Pat : V) {
1366 Pat.SortInner = Inner;
1367 Pat.SortOuter = Outer;
1368 }
1369
1370 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1371 }
Rui Ueyama10416562016-08-04 02:03:27 +00001372 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001373}
1374
George Rimara2496cb2016-08-30 09:46:59 +00001375InputSectionDescription *
1376ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001377 // Input section wildcard can be surrounded by KEEP.
1378 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001379 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001380 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001381 StringRef FilePattern = next();
1382 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001383 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001384 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001385 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001386 }
George Rimara2496cb2016-08-30 09:46:59 +00001387 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001388}
1389
George Rimar03fc0102016-07-28 07:18:23 +00001390void ScriptParser::readSort() {
1391 expect("(");
1392 expect("CONSTRUCTORS");
1393 expect(")");
1394}
1395
George Rimareefa7582016-08-04 09:29:31 +00001396Expr ScriptParser::readAssert() {
1397 expect("(");
1398 Expr E = readExpr();
1399 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001400 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001401 expect(")");
1402 return [=](uint64_t Dot) {
1403 uint64_t V = E(Dot);
1404 if (!V)
1405 error(Msg);
1406 return V;
1407 };
1408}
1409
Rui Ueyama25150e82016-09-06 17:46:43 +00001410// Reads a FILL(expr) command. We handle the FILL command as an
1411// alias for =fillexp section attribute, which is different from
1412// what GNU linkers do.
1413// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001414uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001415 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001416 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001417 expect(")");
1418 expect(";");
1419 return V;
1420}
1421
Rui Ueyama10416562016-08-04 02:03:27 +00001422OutputSectionCommand *
1423ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001424 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001425 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001426
1427 // Read an address expression.
1428 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1429 if (peek() != ":")
1430 Cmd->AddrExpr = readExpr();
1431
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001432 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001433
Rui Ueyama83043f22016-10-17 16:01:53 +00001434 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001435 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001436 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001437 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001438 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001439 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001440
Davide Italiano246f6812016-07-22 03:36:24 +00001441 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001442 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001443 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001444 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001445 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001446 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001447
Rui Ueyama83043f22016-10-17 16:01:53 +00001448 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001449 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001450 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001451 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001452 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001453 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001454 } else if (Tok == "ASSERT") {
1455 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1456 expect(";");
1457 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001458 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001459 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001460 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001461 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001462 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001463 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001464 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001465 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001466 }
George Rimar076fe152016-07-21 06:43:01 +00001467 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001468
Rui Ueyama83043f22016-10-17 16:01:53 +00001469 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001470 Cmd->Filler = readOutputSectionFiller(next());
1471 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001472 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001473
George Rimar7185a1a2017-01-17 15:32:12 +00001474 // Consume optional comma following output section command.
1475 consume(",");
1476
Rui Ueyama10416562016-08-04 02:03:27 +00001477 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001478}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001479
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001480// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1481// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1482//
1483// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1484// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1485// as 32-bit big-endian values. We will do the same as ld.gold does
1486// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001487uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001488 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001489 if (!Tok.getAsInteger(0, V))
1490 return V;
1491 setError("invalid filler expression: " + Tok);
1492 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001493}
1494
Petr Hoseka35e39c2016-08-16 01:11:16 +00001495SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001496 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001497 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001498 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001499 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001500 expect(")");
1501 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001502 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001503}
1504
Rafael Espindolac96da112016-11-01 11:30:45 +00001505SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001506 SymbolAssignment *Cmd = nullptr;
1507 if (peek() == "=" || peek() == "+=") {
1508 Cmd = readAssignment(Tok);
1509 expect(";");
1510 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001511 Cmd = readProvideHidden(true, false);
1512 } else if (Tok == "HIDDEN") {
1513 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001514 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001515 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001516 }
1517 return Cmd;
1518}
1519
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001520static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
George Rimar30835ea2016-07-28 21:08:56 +00001521 if (S == ".")
1522 return Dot;
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001523 return ScriptBase->getSymbolValue(Loc, S);
George Rimare32a3592016-08-10 07:59:34 +00001524}
1525
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001526static bool isAbsolute(StringRef S) {
1527 if (S == ".")
1528 return false;
1529 return ScriptBase->isAbsolute(S);
1530}
1531
George Rimar30835ea2016-07-28 21:08:56 +00001532SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1533 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001534 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001535 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001536 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001537 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1538 // Call readExpr1 to read the whole expression.
1539 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001540 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001541 } else {
1542 E = readExpr();
1543 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001544 if (Op == "+=") {
1545 std::string Loc = getCurrentLocation();
1546 E = [=](uint64_t Dot) {
1547 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1548 };
1549 }
Rafael Espindolaf6613932016-10-31 17:43:38 +00001550 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001551}
1552
1553// This is an operator-precedence parser to parse a linker
1554// script expression.
1555Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1556
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001557static Expr combine(StringRef Op, Expr L, Expr R) {
1558 if (Op == "*")
1559 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1560 if (Op == "/") {
1561 return [=](uint64_t Dot) -> uint64_t {
1562 uint64_t RHS = R(Dot);
1563 if (RHS == 0) {
1564 error("division by zero");
1565 return 0;
1566 }
1567 return L(Dot) / RHS;
1568 };
1569 }
1570 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001571 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001572 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1573 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001574 const OutputSectionBase *S = L.Section();
1575 return S ? S : R.Section();
1576 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001577 if (Op == "-")
1578 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001579 if (Op == "<<")
1580 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1581 if (Op == ">>")
1582 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001583 if (Op == "<")
1584 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1585 if (Op == ">")
1586 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1587 if (Op == ">=")
1588 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1589 if (Op == "<=")
1590 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1591 if (Op == "==")
1592 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1593 if (Op == "!=")
1594 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1595 if (Op == "&")
1596 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001597 if (Op == "|")
1598 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001599 llvm_unreachable("invalid operator");
1600}
1601
Rui Ueyama708019c2016-07-24 18:19:40 +00001602// This is a part of the operator-precedence parser. This function
1603// assumes that the remaining token stream starts with an operator.
1604Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1605 while (!atEOF() && !Error) {
1606 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001607 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001608 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001609 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001610 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001611 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001612 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001613 Expr Rhs = readPrimary();
1614
1615 // Evaluate the remaining part of the expression first if the
1616 // next operator has greater precedence than the previous one.
1617 // For example, if we have read "+" and "3", and if the next
1618 // operator is "*", then we'll evaluate 3 * ... part first.
1619 while (!atEOF()) {
1620 StringRef Op2 = peek();
1621 if (precedence(Op2) <= precedence(Op1))
1622 break;
1623 Rhs = readExpr1(Rhs, precedence(Op2));
1624 }
1625
1626 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001627 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001628 return Lhs;
1629}
1630
1631uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001632 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001633 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001634 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001635 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001636 error("unknown constant: " + S);
1637 return 0;
1638}
1639
Rui Ueyama626e0b02016-09-02 18:19:00 +00001640// Parses Tok as an integer. Returns true if successful.
1641// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1642// and decimal numbers. Decimal numbers may have "K" (kilo) or
1643// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001644static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001645 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001646 if (Tok.startswith("-")) {
1647 if (!readInteger(Tok.substr(1), Result))
1648 return false;
1649 Result = -Result;
1650 return true;
1651 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001652
1653 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001654 if (Tok.startswith_lower("0x"))
1655 return !Tok.substr(2).getAsInteger(16, Result);
1656 if (Tok.endswith_lower("H"))
1657 return !Tok.drop_back().getAsInteger(16, Result);
1658
Rui Ueyama46247b82016-11-18 06:49:07 +00001659 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001660 int Suffix = 1;
1661 if (Tok.endswith_lower("K")) {
1662 Suffix = 1024;
1663 Tok = Tok.drop_back();
1664 } else if (Tok.endswith_lower("M")) {
1665 Suffix = 1024 * 1024;
1666 Tok = Tok.drop_back();
1667 }
1668 if (Tok.getAsInteger(10, Result))
1669 return false;
1670 Result *= Suffix;
1671 return true;
1672}
1673
George Rimare38cbab2016-09-26 19:22:50 +00001674BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1675 int Size = StringSwitch<unsigned>(Tok)
1676 .Case("BYTE", 1)
1677 .Case("SHORT", 2)
1678 .Case("LONG", 4)
1679 .Case("QUAD", 8)
1680 .Default(-1);
1681 if (Size == -1)
1682 return nullptr;
1683
Meador Inge95c7d8d2016-12-08 23:21:30 +00001684 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001685}
1686
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001687StringRef ScriptParser::readParenLiteral() {
1688 expect("(");
1689 StringRef Tok = next();
1690 expect(")");
1691 return Tok;
1692}
1693
Rui Ueyama708019c2016-07-24 18:19:40 +00001694Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001695 if (peek() == "(")
1696 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001697
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001698 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001699 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001700
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001701 if (Tok == "~") {
1702 Expr E = readPrimary();
1703 return [=](uint64_t Dot) { return ~E(Dot); };
1704 }
1705 if (Tok == "-") {
1706 Expr E = readPrimary();
1707 return [=](uint64_t Dot) { return -E(Dot); };
1708 }
1709
Rui Ueyama708019c2016-07-24 18:19:40 +00001710 // Built-in functions are parsed here.
1711 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001712 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001713 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001714 return {[=](uint64_t Dot) {
1715 return ScriptBase->getOutputSection(Location, Name)->Addr;
1716 },
1717 [=] { return false; },
1718 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001719 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001720 if (Tok == "LOADADDR") {
1721 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001722 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001723 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001724 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001725 }
George Rimareefa7582016-08-04 09:29:31 +00001726 if (Tok == "ASSERT")
1727 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001728 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001729 expect("(");
1730 Expr E = readExpr();
1731 if (consume(",")) {
1732 Expr E2 = readExpr();
1733 expect(")");
1734 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1735 }
1736 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001737 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1738 }
1739 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001740 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001741 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001742 }
George Rimarf34f45f2016-09-23 13:17:23 +00001743 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001744 StringRef Name = readParenLiteral();
1745 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001746 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001747 if (Tok == "SEGMENT_START") {
1748 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001749 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001750 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001751 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001752 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001753 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001754 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001755 if (Tok == "DATA_SEGMENT_ALIGN") {
1756 expect("(");
1757 Expr E = readExpr();
1758 expect(",");
1759 readExpr();
1760 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001761 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001762 }
1763 if (Tok == "DATA_SEGMENT_END") {
1764 expect("(");
1765 expect(".");
1766 expect(")");
1767 return [](uint64_t Dot) { return Dot; };
1768 }
George Rimar276b4e62016-07-26 17:58:44 +00001769 // GNU linkers implements more complicated logic to handle
1770 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1771 // the next page boundary for simplicity.
1772 if (Tok == "DATA_SEGMENT_RELRO_END") {
1773 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001774 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001775 expect(",");
1776 readExpr();
1777 expect(")");
1778 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1779 }
George Rimar9e694502016-07-29 16:18:47 +00001780 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001781 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001782 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001783 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001784 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001785 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001786 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001787 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001788 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001789 }
George Rimare32a3592016-08-10 07:59:34 +00001790 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001791 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001792
George Rimar9f2f7ad2016-09-02 16:01:42 +00001793 // Tok is a literal number.
1794 uint64_t V;
1795 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001796 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001797
1798 // Tok is a symbol name.
1799 if (Tok != "." && !isValidCIdentifier(Tok))
1800 setError("malformed number: " + Tok);
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001801 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001802 [=] { return isAbsolute(Tok); },
1803 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001804}
1805
1806Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001807 Expr L = readExpr();
1808 expect(":");
1809 Expr R = readExpr();
1810 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1811}
1812
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001813Expr ScriptParser::readParenExpr() {
1814 expect("(");
1815 Expr E = readExpr();
1816 expect(")");
1817 return E;
1818}
1819
Eugene Leviantbbe38602016-07-19 09:25:43 +00001820std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1821 std::vector<StringRef> Phdrs;
1822 while (!Error && peek().startswith(":")) {
1823 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001824 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001825 }
1826 return Phdrs;
1827}
1828
George Rimar95dd7182016-10-18 10:49:50 +00001829// Read a program header type name. The next token must be a
1830// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001831unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001832 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001833 uint64_t Val;
1834 if (readInteger(Tok, Val))
1835 return Val;
1836
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001837 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001838 .Case("PT_NULL", PT_NULL)
1839 .Case("PT_LOAD", PT_LOAD)
1840 .Case("PT_DYNAMIC", PT_DYNAMIC)
1841 .Case("PT_INTERP", PT_INTERP)
1842 .Case("PT_NOTE", PT_NOTE)
1843 .Case("PT_SHLIB", PT_SHLIB)
1844 .Case("PT_PHDR", PT_PHDR)
1845 .Case("PT_TLS", PT_TLS)
1846 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1847 .Case("PT_GNU_STACK", PT_GNU_STACK)
1848 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001849 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001850 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001851 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001852 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001853
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001854 if (Ret == (unsigned)-1) {
1855 setError("invalid program header type: " + Tok);
1856 return PT_NULL;
1857 }
1858 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001859}
1860
Rui Ueyama12450b22016-11-18 06:30:09 +00001861// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1862void ScriptParser::readAnonymousDeclaration() {
1863 // Read global symbols first. "global:" is default, so if there's
1864 // no label, we assume global symbols.
1865 if (consume("global:") || peek() != "local:")
1866 Config->VersionScriptGlobals = readSymbols();
1867
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001868 readLocals();
Rui Ueyama12450b22016-11-18 06:30:09 +00001869 expect("}");
1870 expect(";");
1871}
1872
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001873void ScriptParser::readLocals() {
1874 if (!consume("local:"))
1875 return;
1876 std::vector<SymbolVersion> Locals = readSymbols();
1877 for (SymbolVersion V : Locals) {
1878 if (V.Name == "*") {
1879 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1880 continue;
1881 }
1882 Config->VersionScriptLocals.push_back(V);
1883 }
1884}
1885
Rui Ueyama12450b22016-11-18 06:30:09 +00001886// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001887void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001888 // Identifiers start at 2 because 0 and 1 are reserved
1889 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001890 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001891 Config->VersionDefinitions.push_back({VerStr, VersionId});
1892
Rui Ueyama12450b22016-11-18 06:30:09 +00001893 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001894 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001895 Config->VersionDefinitions.back().Globals = readSymbols();
1896
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001897 readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001898 expect("}");
1899
Rui Ueyama12450b22016-11-18 06:30:09 +00001900 // Each version may have a parent version. For example, "Ver2"
1901 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1902 // as a parent. This version hierarchy is, probably against your
1903 // instinct, purely for hint; the runtime doesn't care about it
1904 // at all. In LLD, we simply ignore it.
1905 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001906 skip();
George Rimar20b65982016-08-31 09:08:26 +00001907 expect(";");
1908}
1909
Rui Ueyama12450b22016-11-18 06:30:09 +00001910// Reads a list of symbols for a versions cript.
1911std::vector<SymbolVersion> ScriptParser::readSymbols() {
1912 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001913 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001914 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001915 for (SymbolVersion V : readVersionExtern())
1916 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001917 continue;
1918 }
George Rimare0fc2422016-11-16 17:59:10 +00001919
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001920 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001921 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001922 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001923 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001924 expect(";");
1925 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001926 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001927}
1928
Rui Ueyama12450b22016-11-18 06:30:09 +00001929// Reads an "extern C++" directive, e.g.,
1930// "extern "C++" { ns::*; "f(int, double)"; };"
1931std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001932 StringRef Tok = next();
1933 bool IsCXX = Tok == "\"C++\"";
1934 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001935 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00001936 expect("{");
1937
Rui Ueyama12450b22016-11-18 06:30:09 +00001938 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001939 while (!Error && peek() != "}") {
1940 StringRef Tok = next();
1941 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00001942 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001943 expect(";");
1944 }
1945
1946 expect("}");
1947 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001948 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001949}
1950
Rui Ueyama07320e42016-04-20 20:13:41 +00001951void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001952 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001953}
1954
1955void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001956 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001957}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001958
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001959void elf::readDynamicList(MemoryBufferRef MB) {
1960 ScriptParser(MB).readDynamicList();
1961}
1962
Rui Ueyama07320e42016-04-20 20:13:41 +00001963template class elf::LinkerScript<ELF32LE>;
1964template class elf::LinkerScript<ELF32BE>;
1965template class elf::LinkerScript<ELF64LE>;
1966template class elf::LinkerScript<ELF64BE>;