blob: 03573577dcfbb0322a1372d056784c77331c49a5 [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
Meador Ingeb8897442017-01-24 02:34:00 +0000412 // If there is a memory region associated with this input section, then
413 // place the section in that region and update the region index.
414 if (CurMemRegion) {
415 CurMemRegion->Offset += CurOutSec->Size;
416 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
417 if (CurSize > CurMemRegion->Length) {
418 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
419 error("section '" + CurOutSec->Name + "' will not fit in region '" +
420 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
421 " bytes");
422 }
423 }
424
Rafael Espindola7252ae52016-09-22 12:00:08 +0000425 if (IsTbss)
426 ThreadBssOffset = Pos - Dot;
427 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000428 Dot = Pos;
429}
430
431template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000432 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
433 return;
434 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000435 for (InputSection<ELFT> *I : OutSec->Sections)
436 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000437 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000438 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000439 }
440}
441
442template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000443void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000444 if (CurOutSec == Sec)
445 return;
446 if (AlreadyOutputOS.count(Sec))
447 return;
448
449 flush();
450 CurOutSec = Sec;
451
Rafael Espindola04a2e342016-11-09 01:42:41 +0000452 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000453 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000454
455 // If neither AT nor AT> is specified for an allocatable section, the linker
456 // will set the LMA such that the difference between VMA and LMA for the
457 // section is the same as the preceding output section in the same region
458 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
459 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000460}
461
462template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000463 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000464 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
465 if (AssignCmd->Name == ".") {
466 // Update to location counter means update to section size.
George Rimar14460e02016-12-15 07:27:28 +0000467 uintX_t Val = AssignCmd->Expression(Dot);
468 if (Val < Dot)
469 error("unable to move location counter backward for: " +
470 CurOutSec->Name);
471 Dot = Val;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000472 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000473 return;
474 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000475 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000476 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000477 }
George Rimare38cbab2016-09-26 19:22:50 +0000478
479 // Handle BYTE(), SHORT(), LONG(), or QUAD().
480 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000481 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000482 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000483 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000484 return;
485 }
486
Meador Ingeb2d99d62016-11-22 18:01:50 +0000487 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
488 AssertCmd->Expression(Dot);
489 return;
490 }
491
George Rimare38cbab2016-09-26 19:22:50 +0000492 // It handles single input section description command,
493 // calculates and assigns the offsets for each section and also
494 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000495 auto &ICmd = cast<InputSectionDescription>(Base);
496 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000497 // We tentatively added all synthetic sections at the beginning and removed
498 // empty ones afterwards (because there is no way to know whether they were
499 // going be empty or not other than actually running linker scripts.)
500 // We need to ignore remains of empty sections.
501 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
502 if (Sec->empty())
503 continue;
504
Rafael Espindolad3190792016-09-16 15:10:23 +0000505 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
506 switchTo(IB->OutSec);
507 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
508 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000509 else
510 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000511 }
512}
513
George Rimar8f66df92016-08-12 20:38:20 +0000514template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000515static std::vector<OutputSectionBase *>
516findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
517 std::vector<OutputSectionBase *> Ret;
518 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000519 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000520 Ret.push_back(Sec);
521 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000522}
523
Meador Ingeb8897442017-01-24 02:34:00 +0000524// This function searches for a memory region to place the given output
525// section in. If found, a pointer to the appropriate memory region is
526// returned. Otherwise, a nullptr is returned.
527template <class ELFT>
528MemoryRegion *LinkerScript<ELFT>::findMemoryRegion(OutputSectionCommand *Cmd,
529 OutputSectionBase *Sec) {
530 // If a memory region name was specified in the output section command,
531 // then try to find that region first.
532 if (!Cmd->MemoryRegionName.empty()) {
533 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
534 if (It != Opt.MemoryRegions.end())
535 return &It->second;
536 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
537 return nullptr;
538 }
539
540 // The memory region name is empty, thus a suitable region must be
541 // searched for in the region map. If the region map is empty, just
542 // return. Note that this check doesn't happen at the very beginning
543 // so that uses of undeclared regions can be caught.
544 if (!Opt.MemoryRegions.size())
545 return nullptr;
546
547 // See if a region can be found by matching section flags.
548 for (auto &MRI : Opt.MemoryRegions) {
549 MemoryRegion &MR = MRI.second;
Rui Ueyama8a8a9532017-01-26 02:58:59 +0000550 if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
Meador Ingeb8897442017-01-24 02:34:00 +0000551 return &MR;
552 }
553
554 // Otherwise, no suitable region was found.
555 if (Sec->Flags & SHF_ALLOC)
556 error("no memory region specified for section '" + Sec->Name + "'");
557 return nullptr;
558}
559
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000560// This function assigns offsets to input sections and an output section
561// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000562template <class ELFT>
563void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000564 if (Cmd->LMAExpr)
565 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000566 std::vector<OutputSectionBase *> Sections =
567 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000568 if (Sections.empty())
569 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000570
571 OutputSectionBase *Sec = Sections[0];
572 // Try and find an appropriate memory region to assign offsets in.
573 CurMemRegion = findMemoryRegion(Cmd, Sec);
574 if (CurMemRegion)
575 Dot = CurMemRegion->Offset;
576 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000577
Rafael Espindolad3190792016-09-16 15:10:23 +0000578 // Find the last section output location. We will output orphan sections
579 // there so that end symbols point to the correct location.
580 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
581 [](const std::unique_ptr<BaseCommand> &Cmd) {
582 return !isa<SymbolAssignment>(*Cmd);
583 })
584 .base();
585 for (auto I = Cmd->Commands.begin(); I != E; ++I)
586 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000587 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000588 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000589 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000590 std::for_each(E, Cmd->Commands.end(),
591 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000592}
593
Rafael Espindola07fe6122016-11-14 14:23:35 +0000594template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000595 // It is common practice to use very generic linker scripts. So for any
596 // given run some of the output sections in the script will be empty.
597 // We could create corresponding empty output sections, but that would
598 // clutter the output.
599 // We instead remove trivially empty sections. The bfd linker seems even
600 // more aggressive at removing them.
601 auto Pos = std::remove_if(
602 Opt.Commands.begin(), Opt.Commands.end(),
603 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000604 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
605 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
606 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000607 });
608 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000609}
610
Rafael Espindola6a537372016-11-14 14:33:49 +0000611static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
612 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
613 if (!isa<InputSectionDescription>(*I))
614 return false;
615 return true;
616}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000617
Rafael Espindola6a537372016-11-14 14:33:49 +0000618template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000619 // If the output section contains only symbol assignments, create a
620 // corresponding output section. The bfd linker seems to only create them if
621 // '.' is assigned to, but creating these section should not have any bad
622 // consequeces and gives us a section to put the symbol in.
623 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000624 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000625 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
626 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
627 if (!Cmd)
628 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000629 std::vector<OutputSectionBase *> Secs =
630 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000631 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000632 Flags = Secs[0]->Flags;
633 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000634 continue;
635 }
636
Rafael Espindola6a537372016-11-14 14:33:49 +0000637 if (isAllSectionDescription(*Cmd))
638 continue;
639
Rui Ueyama95642b92016-11-01 23:09:07 +0000640 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000641 OutputSections->push_back(OutSec);
642 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000643}
644
645template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
646 placeOrphanSections();
647
648 // If output section command doesn't specify any segments,
649 // and we haven't previously assigned any section to segment,
650 // then we simply assign section to the very first load segment.
651 // Below is an example of such linker script:
652 // PHDRS { seg PT_LOAD; }
653 // SECTIONS { .aaa : { *(.aaa) } }
654 std::vector<StringRef> DefPhdrs;
655 auto FirstPtLoad =
656 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
657 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
658 if (FirstPtLoad != Opt.PhdrsCommands.end())
659 DefPhdrs.push_back(FirstPtLoad->Name);
660
661 // Walk the commands and propagate the program headers to commands that don't
662 // explicitly specify them.
663 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
664 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
665 if (!Cmd)
666 continue;
667 if (Cmd->Phdrs.empty())
668 Cmd->Phdrs = DefPhdrs;
669 else
670 DefPhdrs = Cmd->Phdrs;
671 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000672
673 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000674}
675
Rafael Espindola15c57952016-09-22 18:05:49 +0000676// When placing orphan sections, we want to place them after symbol assignments
677// so that an orphan after
678// begin_foo = .;
679// foo : { *(foo) }
680// end_foo = .;
681// doesn't break the intended meaning of the begin/end symbols.
682// We don't want to go over sections since Writer<ELFT>::sortSections is the
683// one in charge of deciding the order of the sections.
684// We don't want to go over alignments, since doing so in
685// rx_sec : { *(rx_sec) }
686// . = ALIGN(0x1000);
687// /* The RW PT_LOAD starts here*/
688// rw_sec : { *(rw_sec) }
689// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000690static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000691 if (isa<OutputSectionCommand>(Cmd))
692 return false;
693 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
694 if (!Assign)
695 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000696 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000697}
698
Rafael Espindola337f9032016-11-14 14:13:32 +0000699// Orphan sections are sections present in the input files which are not
700// explicitly placed into the output file by the linker script. This just
701// places them in the order already decided in OutputSections.
George Rimar93c64022016-12-15 15:38:09 +0000702template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000703 // The OutputSections are already in the correct order.
704 // This loops creates or moves commands as needed so that they are in the
705 // correct order.
706 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000707
708 // As a horrible special case, skip the first . assignment if it is before any
709 // section. We do this because it is common to set a load address by starting
710 // the script with ". = 0xabcd" and the expectation is that every section is
711 // after that.
712 auto FirstSectionOrDotAssignment =
713 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
714 [](const std::unique_ptr<BaseCommand> &Cmd) {
715 if (isa<OutputSectionCommand>(*Cmd))
716 return true;
717 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
718 if (!Assign)
719 return false;
720 return Assign->Name == ".";
721 });
722 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
723 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
724 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
725 ++CmdIndex;
726 }
727
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000728 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000729 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000730
731 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000732 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000733 auto CmdIter = Opt.Commands.begin() + CmdIndex;
734 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000735 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000736 ++CmdIter;
737 ++CmdIndex;
738 }
739
740 auto Pos =
741 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
742 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
743 return Cmd && Cmd->Name == Name;
744 });
745 if (Pos == E) {
746 Opt.Commands.insert(CmdIter,
747 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000748 ++CmdIndex;
749 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000750 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000751
752 // Continue from where we found it.
753 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000754 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000755}
756
757template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000758void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000759 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000760 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000761
George Rimar076fe152016-07-21 06:43:01 +0000762 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
763 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000764 if (Cmd->Name == ".") {
765 Dot = Cmd->Expression(Dot);
766 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000767 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000768 }
George Rimar652852c2016-04-16 10:10:32 +0000769 continue;
770 }
771
George Rimareefa7582016-08-04 09:29:31 +0000772 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
773 Cmd->Expression(Dot);
774 continue;
775 }
776
George Rimar076fe152016-07-21 06:43:01 +0000777 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000778 if (Cmd->AddrExpr)
779 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000780 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000781 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000782
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000783 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000784 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000785 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000786 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000787 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000788 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000789 }
790
Rafael Espindola8c495e22017-01-20 20:41:18 +0000791 allocateHeaders<ELFT>(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000792}
793
Rui Ueyama464daad2016-08-22 04:55:20 +0000794// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000795template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
796 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000797
Rui Ueyama464daad2016-08-22 04:55:20 +0000798 // Process PHDRS and FILEHDR keywords because they are not
799 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000800 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000801 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000802 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000803
804 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000805 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000806 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000807 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000808
809 if (Cmd.LMAExpr) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000810 Phdr.p_paddr = Cmd.LMAExpr(0);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000811 Phdr.HasLMA = true;
812 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000813 }
814
Rui Ueyama464daad2016-08-22 04:55:20 +0000815 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000816 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000817 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000818 break;
819
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000820 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000821 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000822 Ret[Id].add(Sec);
823 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000824 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000825 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000826 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000827 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000828}
829
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000830template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
831 // Ignore .interp section in case we have PHDRS specification
832 // and PT_INTERP isn't listed.
833 return !Opt.PhdrsCommands.empty() &&
834 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
835 return Cmd.Type == PT_INTERP;
836 }) == Opt.PhdrsCommands.end();
837}
838
George Rimar93c64022016-12-15 15:38:09 +0000839template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000840 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
841 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
842 if (Cmd->Name == Name)
843 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000844 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000845}
846
George Rimare38cbab2016-09-26 19:22:50 +0000847template <class ELFT>
848static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
849 const endianness E = ELFT::TargetEndianness;
850
851 switch (Size) {
852 case 1:
853 *Buf = (uint8_t)Data;
854 break;
855 case 2:
856 write16<E>(Buf, Data);
857 break;
858 case 4:
859 write32<E>(Buf, Data);
860 break;
861 case 8:
862 write64<E>(Buf, Data);
863 break;
864 default:
865 llvm_unreachable("unsupported Size argument");
866 }
867}
868
869template <class ELFT>
870void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
871 int I = getSectionIndex(Name);
872 if (I == INT_MAX)
873 return;
874
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000875 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
876 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
877 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000878 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000879}
880
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000881template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000882 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
883 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000884 if (Cmd->LMAExpr && Cmd->Name == Name)
885 return true;
886 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000887}
888
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000889// Returns the index of the given section name in linker script
890// SECTIONS commands. Sections are laid out as the same order as they
891// were in the script. If a given name did not appear in the script,
892// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000893template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000894 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
895 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000896 if (Cmd->Name == Name)
897 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000898 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000899}
900
Eugene Leviantbbe38602016-07-19 09:25:43 +0000901template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
902 return !Opt.PhdrsCommands.empty();
903}
904
George Rimar9e694502016-07-29 16:18:47 +0000905template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000906const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
907 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000908 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000909
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000910 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000911 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000912 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000913
914 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000915 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000916}
917
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000918// This function is essentially the same as getOutputSection(Name)->Size,
919// but it won't print out an error message if a given section is not found.
920//
921// Linker script does not create an output section if its content is empty.
922// We want to allow SIZEOF(.foo) where .foo is a section which happened to
923// be empty. That is why this function is different from getOutputSection().
924template <class ELFT>
925uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
926 for (OutputSectionBase *Sec : *OutputSections)
927 if (Sec->getName() == Name)
928 return Sec->Size;
929 return 0;
930}
931
George Rimar884e7862016-09-08 08:19:13 +0000932template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000933 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000934}
935
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000936template <class ELFT>
937uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar884e7862016-09-08 08:19:13 +0000938 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
939 return B->getVA<ELFT>();
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000940 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000941 return 0;
942}
943
George Rimarf34f45f2016-09-23 13:17:23 +0000944template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
945 return Symtab<ELFT>::X->find(S) != nullptr;
946}
947
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000948template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
949 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
950 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
951 return DR && !DR->Section;
952}
953
Eugene Leviantafaa9342016-11-16 09:49:39 +0000954// Gets section symbol belongs to. Symbol "." doesn't belong to any
955// specific section but isn't absolute at the same time, so we try
956// to find suitable section for it as well.
957template <class ELFT>
958const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
959 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
960 if (!Sym) {
961 if (OutputSections->empty())
962 return nullptr;
963 return CurOutSec ? CurOutSec : (*OutputSections)[0];
964 }
965
George Rimar60aed442017-01-20 09:45:36 +0000966 return SymbolTableSection<ELFT>::getOutputSection(Sym);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000967}
968
Eugene Leviantbbe38602016-07-19 09:25:43 +0000969// Returns indices of ELF headers containing specific section, identified
970// by Name. Each index is a zero based number of ELF header listed within
971// PHDRS {} script block.
972template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000973std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000974 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
975 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000976 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000977 continue;
978
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000979 std::vector<size_t> Ret;
980 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000981 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000982 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000983 }
George Rimar31d842f2016-07-20 16:43:03 +0000984 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000985}
986
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000987template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +0000988size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000989 size_t I = 0;
990 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
991 if (Cmd.Name == PhdrName)
992 return I;
993 ++I;
994 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000995 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000996 return 0;
997}
998
Eugene Leviant03ff0162016-11-21 15:49:56 +0000999class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +00001000 typedef void (ScriptParser::*Handler)();
1001
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001002public:
Rui Ueyama22375f22016-11-25 18:51:54 +00001003 ScriptParser(MemoryBufferRef MB)
1004 : ScriptParserBase(MB),
1005 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +00001006
George Rimar20b65982016-08-31 09:08:26 +00001007 void readLinkerScript();
1008 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001009 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001010
1011private:
Rui Ueyama52a15092015-10-11 03:28:42 +00001012 void addFile(StringRef Path);
1013
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001014 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +00001015 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001016 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001017 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001018 void readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001019 void readMemory();
Rui Ueyamaee592822015-10-07 00:25:09 +00001020 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001021 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001022 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001023 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001024 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001025 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001026 void readVersion();
1027 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001028
Rui Ueyama113cdec2016-07-24 23:05:57 +00001029 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001030 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001031 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001032 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001033 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001034 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001035 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001036 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001037 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001038 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001039 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001040 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001041 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001042 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001043 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001044 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001045
Rui Ueyama24e626c2017-01-26 02:58:19 +00001046 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1047 std::pair<uint32_t, uint32_t> readMemoryAttributes();
1048
Rui Ueyama708019c2016-07-24 18:19:40 +00001049 Expr readExpr();
1050 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001051 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001052 Expr readPrimary();
1053 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001054 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001055
George Rimar20b65982016-08-31 09:08:26 +00001056 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001057 std::vector<SymbolVersion> readVersionExtern();
1058 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001059 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001060 std::vector<SymbolVersion> readSymbols();
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001061 void readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001062
Rui Ueyama07320e42016-04-20 20:13:41 +00001063 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001064 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001065};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001066
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001067void ScriptParser::readDynamicList() {
1068 expect("{");
1069 readAnonymousDeclaration();
1070 if (!atEOF())
1071 setError("EOF expected, but got " + next());
1072}
1073
George Rimar20b65982016-08-31 09:08:26 +00001074void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001075 readVersionScriptCommand();
1076 if (!atEOF())
1077 setError("EOF expected, but got " + next());
1078}
1079
1080void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001081 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001082 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001083 return;
1084 }
1085
Rui Ueyama95769b42016-08-31 20:03:54 +00001086 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001087 StringRef VerStr = next();
1088 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001089 setError("anonymous version definition is used in "
1090 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001091 return;
1092 }
1093 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001094 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001095 }
1096}
1097
Rui Ueyama95769b42016-08-31 20:03:54 +00001098void ScriptParser::readVersion() {
1099 expect("{");
1100 readVersionScriptCommand();
1101 expect("}");
1102}
1103
George Rimar20b65982016-08-31 09:08:26 +00001104void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001105 while (!atEOF()) {
1106 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001107 if (Tok == ";")
1108 continue;
1109
Eugene Leviant20d03192016-09-16 15:30:47 +00001110 if (Tok == "ASSERT") {
1111 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1112 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001113 readEntry();
1114 } else if (Tok == "EXTERN") {
1115 readExtern();
1116 } else if (Tok == "GROUP" || Tok == "INPUT") {
1117 readGroup();
1118 } else if (Tok == "INCLUDE") {
1119 readInclude();
Meador Ingeb8897442017-01-24 02:34:00 +00001120 } else if (Tok == "MEMORY") {
1121 readMemory();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001122 } else if (Tok == "OUTPUT") {
1123 readOutput();
1124 } else if (Tok == "OUTPUT_ARCH") {
1125 readOutputArch();
1126 } else if (Tok == "OUTPUT_FORMAT") {
1127 readOutputFormat();
1128 } else if (Tok == "PHDRS") {
1129 readPhdrs();
1130 } else if (Tok == "SEARCH_DIR") {
1131 readSearchDir();
1132 } else if (Tok == "SECTIONS") {
1133 readSections();
1134 } else if (Tok == "VERSION") {
1135 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001136 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001137 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001138 } else {
George Rimar57610422016-03-11 14:43:02 +00001139 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001140 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001141 }
1142}
1143
Rui Ueyama717677a2016-02-11 21:17:59 +00001144void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001145 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001146 SmallString<128> PathData;
1147 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001148 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001149 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001150 return;
1151 }
1152 }
1153
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001154 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001155 Driver->addFile(S);
1156 } else if (S.startswith("=")) {
1157 if (Config->Sysroot.empty())
1158 Driver->addFile(S.substr(1));
1159 else
1160 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1161 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001162 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001163 } else if (sys::fs::exists(S)) {
1164 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001165 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001166 if (Optional<std::string> Path = findFromSearchPaths(S))
1167 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001168 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001169 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001170 }
1171}
1172
Rui Ueyama717677a2016-02-11 21:17:59 +00001173void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001174 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001175 bool Orig = Config->AsNeeded;
1176 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001177 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001178 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001179 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001180}
1181
Rui Ueyama717677a2016-02-11 21:17:59 +00001182void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001183 // -e <symbol> takes predecence over ENTRY(<symbol>).
1184 expect("(");
1185 StringRef Tok = next();
1186 if (Config->Entry.empty())
1187 Config->Entry = Tok;
1188 expect(")");
1189}
1190
Rui Ueyama717677a2016-02-11 21:17:59 +00001191void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001192 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001193 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001194 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001195}
1196
Rui Ueyama717677a2016-02-11 21:17:59 +00001197void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001198 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001199 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001200 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001201 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001202 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001203 else
George Rimarcd574a52016-09-09 14:35:36 +00001204 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001205 }
1206}
1207
Rui Ueyama717677a2016-02-11 21:17:59 +00001208void ScriptParser::readInclude() {
George Rimard4500652016-12-21 09:42:25 +00001209 StringRef Tok = unquote(next());
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001210
George Rimard4500652016-12-21 09:42:25 +00001211 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1212 // The file will be searched for in the current directory, and in any
1213 // directory specified with the -L option.
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001214 if (sys::fs::exists(Tok)) {
1215 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1216 tokenize(*MB);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001217 return;
1218 }
Rui Ueyamaec1c75e2017-01-09 01:42:02 +00001219 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1220 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1221 tokenize(*MB);
1222 return;
1223 }
1224 setError("cannot open " + Tok);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001225}
1226
Rui Ueyama717677a2016-02-11 21:17:59 +00001227void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001228 // -o <file> takes predecence over OUTPUT(<file>).
1229 expect("(");
1230 StringRef Tok = next();
1231 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001232 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001233 expect(")");
1234}
1235
Rui Ueyama717677a2016-02-11 21:17:59 +00001236void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001237 // Error checking only for now.
1238 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001239 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001240 expect(")");
1241}
1242
Rui Ueyama717677a2016-02-11 21:17:59 +00001243void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001244 // Error checking only for now.
1245 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001246 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001247 StringRef Tok = next();
1248 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001249 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001250 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001251 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001252 return;
1253 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001254 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001255 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001256 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001257 expect(")");
1258}
1259
Eugene Leviantbbe38602016-07-19 09:25:43 +00001260void ScriptParser::readPhdrs() {
1261 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001262 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001263 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001264 Opt.PhdrsCommands.push_back(
1265 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001266 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1267
1268 PhdrCmd.Type = readPhdrType();
1269 do {
1270 Tok = next();
1271 if (Tok == ";")
1272 break;
1273 if (Tok == "FILEHDR")
1274 PhdrCmd.HasFilehdr = true;
1275 else if (Tok == "PHDRS")
1276 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001277 else if (Tok == "AT")
1278 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001279 else if (Tok == "FLAGS") {
1280 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001281 // Passing 0 for the value of dot is a bit of a hack. It means that
1282 // we accept expressions like ".|1".
1283 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001284 expect(")");
1285 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001286 setError("unexpected header attribute: " + Tok);
1287 } while (!Error);
1288 }
1289}
1290
Rui Ueyama717677a2016-02-11 21:17:59 +00001291void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001292 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001293 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001294 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001295 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001296 expect(")");
1297}
1298
Rui Ueyama717677a2016-02-11 21:17:59 +00001299void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001300 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001301 // -no-rosegment is used to avoid placing read only non-executable sections in
1302 // their own segment. We do the same if SECTIONS command is present in linker
1303 // script. See comment for computeFlags().
1304 Config->SingleRoRx = true;
1305
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001306 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001307 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001308 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001309 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001310 if (!Cmd) {
1311 if (Tok == "ASSERT")
1312 Cmd = new AssertCommand(readAssert());
1313 else
1314 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001315 }
Rui Ueyama10416562016-08-04 02:03:27 +00001316 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001317 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001318}
1319
Rui Ueyama708019c2016-07-24 18:19:40 +00001320static int precedence(StringRef Op) {
1321 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001322 .Cases("*", "/", 5)
1323 .Cases("+", "-", 4)
1324 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001325 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001326 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001327 .Default(-1);
1328}
1329
Eugene Leviantdb688452016-11-03 10:54:58 +00001330StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001331 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001332 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001333 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001334 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001335}
1336
George Rimarbe394db2016-09-16 20:21:55 +00001337SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001338 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001339 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001340 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001341 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001342 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001343 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001344 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001345 return SortSectionPolicy::None;
1346 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001347}
1348
George Rimar395281c2016-09-16 17:42:10 +00001349// Method reads a list of sequence of excluded files and section globs given in
1350// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1351// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001352// The semantics of that is next:
1353// * Include .foo.1 from every file.
1354// * Include .foo.2 from every file but a.o
1355// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001356std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1357 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001358 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001359 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001360 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001361 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001362 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001363 }
1364
George Rimar601e9892016-09-21 08:53:21 +00001365 std::vector<StringRef> V;
1366 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1367 V.push_back(next());
1368
1369 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001370 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001371 else
1372 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001373 }
George Rimar07171f22016-09-21 15:56:44 +00001374 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001375}
1376
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001377// Reads contents of "SECTIONS" directive. That directive contains a
1378// list of glob patterns for input sections. The grammar is as follows.
1379//
1380// <patterns> ::= <section-list>
1381// | <sort> "(" <section-list> ")"
1382// | <sort> "(" <sort> "(" <section-list> ")" ")"
1383//
1384// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1385// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1386//
1387// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001388InputSectionDescription *
1389ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001390 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001391 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001392 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001393 SortSectionPolicy Outer = readSortKind();
1394 SortSectionPolicy Inner = SortSectionPolicy::Default;
1395 std::vector<SectionPattern> V;
1396 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001397 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001398 Inner = readSortKind();
1399 if (Inner != SortSectionPolicy::Default) {
1400 expect("(");
1401 V = readInputSectionsList();
1402 expect(")");
1403 } else {
1404 V = readInputSectionsList();
1405 }
George Rimar350ece42016-08-03 08:35:59 +00001406 expect(")");
1407 } else {
George Rimar07171f22016-09-21 15:56:44 +00001408 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001409 }
George Rimar0702c4e2016-07-29 15:32:46 +00001410
George Rimar07171f22016-09-21 15:56:44 +00001411 for (SectionPattern &Pat : V) {
1412 Pat.SortInner = Inner;
1413 Pat.SortOuter = Outer;
1414 }
1415
1416 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1417 }
Rui Ueyama10416562016-08-04 02:03:27 +00001418 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001419}
1420
George Rimara2496cb2016-08-30 09:46:59 +00001421InputSectionDescription *
1422ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001423 // Input section wildcard can be surrounded by KEEP.
1424 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001425 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001426 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001427 StringRef FilePattern = next();
1428 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001429 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001430 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001431 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001432 }
George Rimara2496cb2016-08-30 09:46:59 +00001433 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001434}
1435
George Rimar03fc0102016-07-28 07:18:23 +00001436void ScriptParser::readSort() {
1437 expect("(");
1438 expect("CONSTRUCTORS");
1439 expect(")");
1440}
1441
George Rimareefa7582016-08-04 09:29:31 +00001442Expr ScriptParser::readAssert() {
1443 expect("(");
1444 Expr E = readExpr();
1445 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001446 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001447 expect(")");
1448 return [=](uint64_t Dot) {
1449 uint64_t V = E(Dot);
1450 if (!V)
1451 error(Msg);
1452 return V;
1453 };
1454}
1455
Rui Ueyama25150e82016-09-06 17:46:43 +00001456// Reads a FILL(expr) command. We handle the FILL command as an
1457// alias for =fillexp section attribute, which is different from
1458// what GNU linkers do.
1459// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001460uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001461 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001462 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001463 expect(")");
1464 expect(";");
1465 return V;
1466}
1467
Rui Ueyama10416562016-08-04 02:03:27 +00001468OutputSectionCommand *
1469ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001470 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001471 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001472
1473 // Read an address expression.
1474 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1475 if (peek() != ":")
1476 Cmd->AddrExpr = readExpr();
1477
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001478 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001479
Rui Ueyama83043f22016-10-17 16:01:53 +00001480 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001481 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001482 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001483 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001484 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001485 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001486
Davide Italiano246f6812016-07-22 03:36:24 +00001487 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001488 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001489 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001490 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001491 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001492 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001493
Rui Ueyama83043f22016-10-17 16:01:53 +00001494 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001495 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001496 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001497 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001498 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001499 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001500 } else if (Tok == "ASSERT") {
1501 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1502 expect(";");
George Rimar8e2eca22017-01-23 09:36:19 +00001503 } else if (Tok == "CONSTRUCTORS") {
1504 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1505 // by name. This is for very old file formats such as ECOFF/XCOFF.
1506 // For ELF, we should ignore.
Meador Ingeb2d99d62016-11-22 18:01:50 +00001507 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001508 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001509 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001510 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001511 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001512 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001513 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001514 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001515 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001516 }
Meador Ingeb8897442017-01-24 02:34:00 +00001517
1518 if (consume(">"))
1519 Cmd->MemoryRegionName = next();
1520
George Rimar076fe152016-07-21 06:43:01 +00001521 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001522
Rui Ueyama83043f22016-10-17 16:01:53 +00001523 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001524 Cmd->Filler = readOutputSectionFiller(next());
1525 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001526 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001527
George Rimar7185a1a2017-01-17 15:32:12 +00001528 // Consume optional comma following output section command.
1529 consume(",");
1530
Rui Ueyama10416562016-08-04 02:03:27 +00001531 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001532}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001533
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001534// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1535// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1536//
1537// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1538// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1539// as 32-bit big-endian values. We will do the same as ld.gold does
1540// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001541uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001542 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001543 if (!Tok.getAsInteger(0, V))
1544 return V;
1545 setError("invalid filler expression: " + Tok);
1546 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001547}
1548
Petr Hoseka35e39c2016-08-16 01:11:16 +00001549SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001550 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001551 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001552 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001553 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001554 expect(")");
1555 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001556 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001557}
1558
Rafael Espindolac96da112016-11-01 11:30:45 +00001559SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001560 SymbolAssignment *Cmd = nullptr;
1561 if (peek() == "=" || peek() == "+=") {
1562 Cmd = readAssignment(Tok);
1563 expect(";");
1564 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001565 Cmd = readProvideHidden(true, false);
1566 } else if (Tok == "HIDDEN") {
1567 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001568 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001569 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001570 }
1571 return Cmd;
1572}
1573
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001574static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
George Rimar30835ea2016-07-28 21:08:56 +00001575 if (S == ".")
1576 return Dot;
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001577 return ScriptBase->getSymbolValue(Loc, S);
George Rimare32a3592016-08-10 07:59:34 +00001578}
1579
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001580static bool isAbsolute(StringRef S) {
1581 if (S == ".")
1582 return false;
1583 return ScriptBase->isAbsolute(S);
1584}
1585
George Rimar30835ea2016-07-28 21:08:56 +00001586SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1587 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001588 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001589 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001590 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001591 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1592 // Call readExpr1 to read the whole expression.
1593 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001594 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001595 } else {
1596 E = readExpr();
1597 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001598 if (Op == "+=") {
1599 std::string Loc = getCurrentLocation();
1600 E = [=](uint64_t Dot) {
1601 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1602 };
1603 }
Rafael Espindolaf6613932016-10-31 17:43:38 +00001604 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001605}
1606
1607// This is an operator-precedence parser to parse a linker
1608// script expression.
1609Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1610
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001611static Expr combine(StringRef Op, Expr L, Expr R) {
1612 if (Op == "*")
1613 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1614 if (Op == "/") {
1615 return [=](uint64_t Dot) -> uint64_t {
1616 uint64_t RHS = R(Dot);
1617 if (RHS == 0) {
1618 error("division by zero");
1619 return 0;
1620 }
1621 return L(Dot) / RHS;
1622 };
1623 }
1624 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001625 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001626 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1627 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001628 const OutputSectionBase *S = L.Section();
1629 return S ? S : R.Section();
1630 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001631 if (Op == "-")
1632 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001633 if (Op == "<<")
1634 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1635 if (Op == ">>")
1636 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001637 if (Op == "<")
1638 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1639 if (Op == ">")
1640 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1641 if (Op == ">=")
1642 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1643 if (Op == "<=")
1644 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1645 if (Op == "==")
1646 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1647 if (Op == "!=")
1648 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1649 if (Op == "&")
1650 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001651 if (Op == "|")
1652 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001653 llvm_unreachable("invalid operator");
1654}
1655
Rui Ueyama708019c2016-07-24 18:19:40 +00001656// This is a part of the operator-precedence parser. This function
1657// assumes that the remaining token stream starts with an operator.
1658Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1659 while (!atEOF() && !Error) {
1660 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001661 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001662 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001663 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001664 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001665 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001666 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001667 Expr Rhs = readPrimary();
1668
1669 // Evaluate the remaining part of the expression first if the
1670 // next operator has greater precedence than the previous one.
1671 // For example, if we have read "+" and "3", and if the next
1672 // operator is "*", then we'll evaluate 3 * ... part first.
1673 while (!atEOF()) {
1674 StringRef Op2 = peek();
1675 if (precedence(Op2) <= precedence(Op1))
1676 break;
1677 Rhs = readExpr1(Rhs, precedence(Op2));
1678 }
1679
1680 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001681 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001682 return Lhs;
1683}
1684
1685uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001686 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001687 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001688 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001689 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001690 error("unknown constant: " + S);
1691 return 0;
1692}
1693
Rui Ueyama626e0b02016-09-02 18:19:00 +00001694// Parses Tok as an integer. Returns true if successful.
1695// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1696// and decimal numbers. Decimal numbers may have "K" (kilo) or
1697// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001698static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001699 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001700 if (Tok.startswith("-")) {
1701 if (!readInteger(Tok.substr(1), Result))
1702 return false;
1703 Result = -Result;
1704 return true;
1705 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001706
1707 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001708 if (Tok.startswith_lower("0x"))
1709 return !Tok.substr(2).getAsInteger(16, Result);
1710 if (Tok.endswith_lower("H"))
1711 return !Tok.drop_back().getAsInteger(16, Result);
1712
Rui Ueyama46247b82016-11-18 06:49:07 +00001713 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001714 int Suffix = 1;
1715 if (Tok.endswith_lower("K")) {
1716 Suffix = 1024;
1717 Tok = Tok.drop_back();
1718 } else if (Tok.endswith_lower("M")) {
1719 Suffix = 1024 * 1024;
1720 Tok = Tok.drop_back();
1721 }
1722 if (Tok.getAsInteger(10, Result))
1723 return false;
1724 Result *= Suffix;
1725 return true;
1726}
1727
George Rimare38cbab2016-09-26 19:22:50 +00001728BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1729 int Size = StringSwitch<unsigned>(Tok)
1730 .Case("BYTE", 1)
1731 .Case("SHORT", 2)
1732 .Case("LONG", 4)
1733 .Case("QUAD", 8)
1734 .Default(-1);
1735 if (Size == -1)
1736 return nullptr;
1737
Meador Inge95c7d8d2016-12-08 23:21:30 +00001738 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001739}
1740
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001741StringRef ScriptParser::readParenLiteral() {
1742 expect("(");
1743 StringRef Tok = next();
1744 expect(")");
1745 return Tok;
1746}
1747
Rui Ueyama708019c2016-07-24 18:19:40 +00001748Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001749 if (peek() == "(")
1750 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001751
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001752 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001753 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001754
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001755 if (Tok == "~") {
1756 Expr E = readPrimary();
1757 return [=](uint64_t Dot) { return ~E(Dot); };
1758 }
1759 if (Tok == "-") {
1760 Expr E = readPrimary();
1761 return [=](uint64_t Dot) { return -E(Dot); };
1762 }
1763
Rui Ueyama708019c2016-07-24 18:19:40 +00001764 // Built-in functions are parsed here.
1765 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001766 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001767 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001768 return {[=](uint64_t Dot) {
1769 return ScriptBase->getOutputSection(Location, Name)->Addr;
1770 },
1771 [=] { return false; },
1772 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001773 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001774 if (Tok == "LOADADDR") {
1775 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001776 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001777 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001778 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001779 }
George Rimareefa7582016-08-04 09:29:31 +00001780 if (Tok == "ASSERT")
1781 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001782 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001783 expect("(");
1784 Expr E = readExpr();
1785 if (consume(",")) {
1786 Expr E2 = readExpr();
1787 expect(")");
1788 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1789 }
1790 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001791 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1792 }
1793 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001794 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001795 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001796 }
George Rimarf34f45f2016-09-23 13:17:23 +00001797 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001798 StringRef Name = readParenLiteral();
1799 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001800 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001801 if (Tok == "SEGMENT_START") {
1802 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001803 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001804 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001805 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001806 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001807 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001808 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001809 if (Tok == "DATA_SEGMENT_ALIGN") {
1810 expect("(");
1811 Expr E = readExpr();
1812 expect(",");
1813 readExpr();
1814 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001815 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001816 }
1817 if (Tok == "DATA_SEGMENT_END") {
1818 expect("(");
1819 expect(".");
1820 expect(")");
1821 return [](uint64_t Dot) { return Dot; };
1822 }
George Rimar276b4e62016-07-26 17:58:44 +00001823 // GNU linkers implements more complicated logic to handle
1824 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1825 // the next page boundary for simplicity.
1826 if (Tok == "DATA_SEGMENT_RELRO_END") {
1827 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001828 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001829 expect(",");
1830 readExpr();
1831 expect(")");
1832 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1833 }
George Rimar9e694502016-07-29 16:18:47 +00001834 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001835 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001836 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001837 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001838 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001839 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001840 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001841 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001842 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001843 }
George Rimare32a3592016-08-10 07:59:34 +00001844 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001845 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001846
George Rimar9f2f7ad2016-09-02 16:01:42 +00001847 // Tok is a literal number.
1848 uint64_t V;
1849 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001850 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001851
1852 // Tok is a symbol name.
1853 if (Tok != "." && !isValidCIdentifier(Tok))
1854 setError("malformed number: " + Tok);
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001855 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001856 [=] { return isAbsolute(Tok); },
1857 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001858}
1859
1860Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001861 Expr L = readExpr();
1862 expect(":");
1863 Expr R = readExpr();
1864 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1865}
1866
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001867Expr ScriptParser::readParenExpr() {
1868 expect("(");
1869 Expr E = readExpr();
1870 expect(")");
1871 return E;
1872}
1873
Eugene Leviantbbe38602016-07-19 09:25:43 +00001874std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1875 std::vector<StringRef> Phdrs;
1876 while (!Error && peek().startswith(":")) {
1877 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001878 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001879 }
1880 return Phdrs;
1881}
1882
George Rimar95dd7182016-10-18 10:49:50 +00001883// Read a program header type name. The next token must be a
1884// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001885unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001886 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001887 uint64_t Val;
1888 if (readInteger(Tok, Val))
1889 return Val;
1890
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001891 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001892 .Case("PT_NULL", PT_NULL)
1893 .Case("PT_LOAD", PT_LOAD)
1894 .Case("PT_DYNAMIC", PT_DYNAMIC)
1895 .Case("PT_INTERP", PT_INTERP)
1896 .Case("PT_NOTE", PT_NOTE)
1897 .Case("PT_SHLIB", PT_SHLIB)
1898 .Case("PT_PHDR", PT_PHDR)
1899 .Case("PT_TLS", PT_TLS)
1900 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1901 .Case("PT_GNU_STACK", PT_GNU_STACK)
1902 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001903 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001904 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001905 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001906 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001907
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001908 if (Ret == (unsigned)-1) {
1909 setError("invalid program header type: " + Tok);
1910 return PT_NULL;
1911 }
1912 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001913}
1914
Rui Ueyama12450b22016-11-18 06:30:09 +00001915// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1916void ScriptParser::readAnonymousDeclaration() {
1917 // Read global symbols first. "global:" is default, so if there's
1918 // no label, we assume global symbols.
1919 if (consume("global:") || peek() != "local:")
1920 Config->VersionScriptGlobals = readSymbols();
1921
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001922 readLocals();
Rui Ueyama12450b22016-11-18 06:30:09 +00001923 expect("}");
1924 expect(";");
1925}
1926
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001927void ScriptParser::readLocals() {
1928 if (!consume("local:"))
1929 return;
1930 std::vector<SymbolVersion> Locals = readSymbols();
1931 for (SymbolVersion V : Locals) {
1932 if (V.Name == "*") {
1933 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1934 continue;
1935 }
1936 Config->VersionScriptLocals.push_back(V);
1937 }
1938}
1939
Rui Ueyama12450b22016-11-18 06:30:09 +00001940// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001941void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001942 // Identifiers start at 2 because 0 and 1 are reserved
1943 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001944 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001945 Config->VersionDefinitions.push_back({VerStr, VersionId});
1946
Rui Ueyama12450b22016-11-18 06:30:09 +00001947 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001948 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001949 Config->VersionDefinitions.back().Globals = readSymbols();
1950
Rafael Espindolae999ddb2017-01-10 16:37:24 +00001951 readLocals();
George Rimar20b65982016-08-31 09:08:26 +00001952 expect("}");
1953
Rui Ueyama12450b22016-11-18 06:30:09 +00001954 // Each version may have a parent version. For example, "Ver2"
1955 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1956 // as a parent. This version hierarchy is, probably against your
1957 // instinct, purely for hint; the runtime doesn't care about it
1958 // at all. In LLD, we simply ignore it.
1959 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001960 skip();
George Rimar20b65982016-08-31 09:08:26 +00001961 expect(";");
1962}
1963
Rui Ueyama12450b22016-11-18 06:30:09 +00001964// Reads a list of symbols for a versions cript.
1965std::vector<SymbolVersion> ScriptParser::readSymbols() {
1966 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001967 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001968 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001969 for (SymbolVersion V : readVersionExtern())
1970 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001971 continue;
1972 }
George Rimare0fc2422016-11-16 17:59:10 +00001973
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001974 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001975 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001976 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001977 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001978 expect(";");
1979 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001980 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001981}
1982
Rui Ueyama12450b22016-11-18 06:30:09 +00001983// Reads an "extern C++" directive, e.g.,
1984// "extern "C++" { ns::*; "f(int, double)"; };"
1985std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001986 StringRef Tok = next();
1987 bool IsCXX = Tok == "\"C++\"";
1988 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001989 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00001990 expect("{");
1991
Rui Ueyama12450b22016-11-18 06:30:09 +00001992 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001993 while (!Error && peek() != "}") {
1994 StringRef Tok = next();
1995 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00001996 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001997 expect(";");
1998 }
1999
2000 expect("}");
2001 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00002002 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00002003}
2004
Rui Ueyama24e626c2017-01-26 02:58:19 +00002005uint64_t ScriptParser::readMemoryAssignment(
2006 StringRef S1, StringRef S2, StringRef S3) {
2007 if (!(consume(S1) || consume(S2) || consume(S3))) {
2008 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2009 return 0;
2010 }
2011 expect("=");
2012
2013 // TODO: Fully support constant expressions.
2014 uint64_t Val;
2015 if (!readInteger(next(), Val))
2016 setError("nonconstant expression for "+ S1);
2017 return Val;
2018}
2019
2020// Parse the MEMORY command as specified in:
2021// https://sourceware.org/binutils/docs/ld/MEMORY.html
2022//
2023// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
Meador Ingeb8897442017-01-24 02:34:00 +00002024void ScriptParser::readMemory() {
2025 expect("{");
2026 while (!Error && !consume("}")) {
2027 StringRef Name = next();
Rui Ueyama24e626c2017-01-26 02:58:19 +00002028
Meador Ingeb8897442017-01-24 02:34:00 +00002029 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002030 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002031 if (consume("(")) {
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002032 std::tie(Flags, NegFlags) = readMemoryAttributes();
Meador Ingeb8897442017-01-24 02:34:00 +00002033 expect(")");
2034 }
2035 expect(":");
2036
Rui Ueyama24e626c2017-01-26 02:58:19 +00002037 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
Meador Ingeb8897442017-01-24 02:34:00 +00002038 expect(",");
Rui Ueyama24e626c2017-01-26 02:58:19 +00002039 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
Meador Ingeb8897442017-01-24 02:34:00 +00002040
Meador Ingeb8897442017-01-24 02:34:00 +00002041 // Add the memory region to the region map (if it doesn't already exist).
2042 auto It = Opt.MemoryRegions.find(Name);
2043 if (It != Opt.MemoryRegions.end())
2044 setError("region '" + Name + "' already defined");
2045 else
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002046 Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002047 }
2048}
2049
2050// This function parses the attributes used to match against section
2051// flags when placing output sections in a memory region. These flags
2052// are only used when an explicit memory region name is not used.
2053std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2054 uint32_t Flags = 0;
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002055 uint32_t NegFlags = 0;
Meador Ingeb8897442017-01-24 02:34:00 +00002056 bool Invert = false;
Rui Ueyama481ac992017-01-26 02:58:39 +00002057
2058 for (char C : next().lower()) {
Meador Ingeb8897442017-01-24 02:34:00 +00002059 uint32_t Flag = 0;
2060 if (C == '!')
2061 Invert = !Invert;
Rui Ueyama481ac992017-01-26 02:58:39 +00002062 else if (C == 'w')
Meador Ingeb8897442017-01-24 02:34:00 +00002063 Flag = SHF_WRITE;
Rui Ueyama481ac992017-01-26 02:58:39 +00002064 else if (C == 'x')
Meador Ingeb8897442017-01-24 02:34:00 +00002065 Flag = SHF_EXECINSTR;
Rui Ueyama481ac992017-01-26 02:58:39 +00002066 else if (C == 'a')
Meador Ingeb8897442017-01-24 02:34:00 +00002067 Flag = SHF_ALLOC;
Rui Ueyama481ac992017-01-26 02:58:39 +00002068 else if (C != 'r')
Meador Ingeb8897442017-01-24 02:34:00 +00002069 setError("invalid memory region attribute");
Rui Ueyama481ac992017-01-26 02:58:39 +00002070
Meador Ingeb8897442017-01-24 02:34:00 +00002071 if (Invert)
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002072 NegFlags |= Flag;
Meador Ingeb8897442017-01-24 02:34:00 +00002073 else
2074 Flags |= Flag;
2075 }
Rui Ueyama8a8a9532017-01-26 02:58:59 +00002076 return {Flags, NegFlags};
Meador Ingeb8897442017-01-24 02:34:00 +00002077}
2078
Rui Ueyama07320e42016-04-20 20:13:41 +00002079void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002080 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00002081}
2082
2083void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00002084 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00002085}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00002086
Rafael Espindolad0ebd842016-12-08 17:54:26 +00002087void elf::readDynamicList(MemoryBufferRef MB) {
2088 ScriptParser(MB).readDynamicList();
2089}
2090
Rui Ueyama07320e42016-04-20 20:13:41 +00002091template class elf::LinkerScript<ELF32LE>;
2092template class elf::LinkerScript<ELF32BE>;
2093template class elf::LinkerScript<ELF64LE>;
2094template class elf::LinkerScript<ELF64BE>;