blob: 7387c9c259057196c34ee1f68933960841bce5b6 [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"
George Rimar652852c2016-04-16 10:10:32 +000018#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000019#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000020#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000022#include "Symbols.h"
George Rimar3fb5a6d2016-11-29 16:05:27 +000023#include "SyntheticSections.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000024#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000025#include "Writer.h"
Rui Ueyama520d9162016-12-08 18:31:13 +000026#include "lld/Support/Memory.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
George Rimar6c55f0e2016-09-08 08:20:30 +000059template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000060 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000061 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
George Rimar463984d2016-11-15 08:07:14 +000062 0, 0, STB_GLOBAL, nullptr, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000063 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000064
65 // If we have no SECTIONS then we don't have '.' and don't call
66 // assignAddresses(). We calculate symbol value immediately in this case.
67 if (!ScriptConfig->HasSections)
68 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000069}
70
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000071template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
Eugene Leviantafaa9342016-11-16 09:49:39 +000072 // If we have SECTIONS block then output sections haven't been created yet.
73 const OutputSectionBase *Sec =
74 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
George Rimare1937bb2016-08-19 15:36:32 +000075 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
Eugene Leviantafaa9342016-11-16 09:49:39 +000076 Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000077 Cmd->Sym = Sym->body();
Eugene Leviantafaa9342016-11-16 09:49:39 +000078
79 // If we already know section then we can calculate symbol value immediately.
80 if (Sec)
81 cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
82 Cmd->Expression(0) - Sec->Addr;
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
Eugene Leviantdb741e72016-09-07 07:08:43 +000094template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000095 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000096 addRegular<ELFT>(Cmd);
97 else
98 addSynthetic<ELFT>(Cmd);
99}
Rui Ueyama16024212016-08-11 23:22:52 +0000100// If a symbol was in PROVIDE(), we need to define it only when
101// it is an undefined symbol.
102template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
103 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +0000104 return false;
Rui Ueyama16024212016-08-11 23:22:52 +0000105 if (!Cmd->Provide)
106 return true;
107 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
108 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +0000109}
110
George Rimar076fe152016-07-21 06:43:01 +0000111bool SymbolAssignment::classof(const BaseCommand *C) {
112 return C->Kind == AssignmentKind;
113}
114
115bool OutputSectionCommand::classof(const BaseCommand *C) {
116 return C->Kind == OutputSectionKind;
117}
118
George Rimareea31142016-07-21 14:26:59 +0000119bool InputSectionDescription::classof(const BaseCommand *C) {
120 return C->Kind == InputSectionKind;
121}
122
George Rimareefa7582016-08-04 09:29:31 +0000123bool AssertCommand::classof(const BaseCommand *C) {
124 return C->Kind == AssertKind;
125}
126
George Rimare38cbab2016-09-26 19:22:50 +0000127bool BytesDataCommand::classof(const BaseCommand *C) {
128 return C->Kind == BytesDataKind;
129}
130
Eugene Zelenko22886a22016-11-05 01:00:56 +0000131template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
132template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000133
Rui Ueyamae0be2902016-11-21 02:10:12 +0000134template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
135 if (S->getFile())
136 return sys::path::filename(S->getFile()->getName());
137 return "";
138}
139
Rui Ueyama07320e42016-04-20 20:13:41 +0000140template <class ELFT>
141bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000142 for (InputSectionDescription *ID : Opt.KeptSections)
143 if (ID->FilePat.match(basename(S)))
144 for (SectionPattern &P : ID->SectionPatterns)
145 if (P.SectionPat.match(S->Name))
146 return true;
George Rimareea31142016-07-21 14:26:59 +0000147 return false;
148}
149
George Rimar575208c2016-09-15 19:15:12 +0000150static bool comparePriority(InputSectionData *A, InputSectionData *B) {
151 return getPriority(A->Name) < getPriority(B->Name);
152}
153
Rafael Espindolac0028d32016-09-08 20:47:52 +0000154static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000155 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000156}
George Rimar350ece42016-08-03 08:35:59 +0000157
Rafael Espindolac0028d32016-09-08 20:47:52 +0000158static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000159 // ">" is not a mistake. Larger alignments are placed before smaller
160 // alignments in order to reduce the amount of padding necessary.
161 // This is compatible with GNU.
162 return A->Alignment > B->Alignment;
163}
George Rimar350ece42016-08-03 08:35:59 +0000164
Rafael Espindolac0028d32016-09-08 20:47:52 +0000165static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000166getComparator(SortSectionPolicy K) {
167 switch (K) {
168 case SortSectionPolicy::Alignment:
169 return compareAlignment;
170 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000171 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000172 case SortSectionPolicy::Priority:
173 return comparePriority;
174 default:
175 llvm_unreachable("unknown sort policy");
176 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000177}
George Rimar0702c4e2016-07-29 15:32:46 +0000178
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000179template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000180static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000181 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000182 if (Kind == ConstraintKind::NoConstraint)
183 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000184 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000185 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000186 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000187 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000188 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
189 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000190}
191
George Rimar07171f22016-09-21 15:56:44 +0000192static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000193 SortSectionPolicy K) {
194 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000195 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000196}
197
Rafael Espindolad3190792016-09-16 15:10:23 +0000198// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000199template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000200void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000201 // Collects all sections that satisfy constraints of I
202 // and attach them to I.
203 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000204 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000205
206 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000207 if (!S->Live || S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000208 continue;
209
Rui Ueyamae0be2902016-11-21 02:10:12 +0000210 StringRef Filename = basename(S);
211 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
212 continue;
213 if (!Pat.SectionPat.match(S->Name))
214 continue;
215 I->Sections.push_back(S);
216 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000217 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000218
George Rimar07171f22016-09-21 15:56:44 +0000219 // Sort sections as instructed by SORT-family commands and --sort-section
220 // option. Because SORT-family commands can be nested at most two depth
221 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
222 // line option is respected even if a SORT command is given, the exact
223 // behavior we have here is a bit complicated. Here are the rules.
224 //
225 // 1. If two SORT commands are given, --sort-section is ignored.
226 // 2. If one SORT command is given, and if it is not SORT_NONE,
227 // --sort-section is handled as an inner SORT command.
228 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
229 // 4. If no SORT command is given, sort according to --sort-section.
230 InputSectionData **Begin = I->Sections.data() + SizeBefore;
231 InputSectionData **End = I->Sections.data() + I->Sections.size();
232 if (Pat.SortOuter != SortSectionPolicy::None) {
233 if (Pat.SortInner == SortSectionPolicy::Default)
234 sortSections(Begin, End, Config->SortSection);
235 else
236 sortSections(Begin, End, Pat.SortInner);
237 sortSections(Begin, End, Pat.SortOuter);
238 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000239 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000240}
241
242template <class ELFT>
243void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
244 for (InputSectionBase<ELFT> *S : V) {
245 S->Live = false;
246 reportDiscarded(S);
247 }
248}
249
George Rimar06ae6832016-08-12 09:07:57 +0000250template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000251std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000252LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000253 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000254
George Rimar06ae6832016-08-12 09:07:57 +0000255 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000256 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
257 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000258 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000259 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000260 for (InputSectionData *S : Cmd->Sections)
261 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000262 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000263
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000264 return Ret;
265}
266
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000267template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000268static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
269 StringRef OutsecName) {
270 // When using linker script the merge rules are different.
271 // Unfortunately, linker scripts are name based. This means that expressions
272 // like *(.foo*) can refer to multiple input sections that would normally be
273 // placed in different output sections. We cannot put them in different
274 // output sections or we would produce wrong results for
275 // start = .; *(.foo.*) end = .; *(.bar)
276 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
277 // another. The problem is that there is no way to layout those output
278 // sections such that the .foo sections are the only thing between the
279 // start and end symbols.
280
281 // An extra annoyance is that we cannot simply disable merging of the contents
282 // of SHF_MERGE sections, but our implementation requires one output section
283 // per "kind" (string or not, which size/aligment).
284 // Fortunately, creating symbols in the middle of a merge section is not
285 // supported by bfd or gold, so we can just create multiple section in that
286 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000287 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000288 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000289
290 uintX_t Alignment = 0;
291 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000292 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000293
294 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
295}
296
297template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000298void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
299 InputSectionBase<ELFT> *Sec,
300 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000301 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000302 bool IsNew;
303 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
304 if (IsNew)
305 OutputSections->push_back(OutSec);
306 OutSec->addSection(Sec);
307}
308
309template <class ELFT>
310void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000311 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
312 auto Iter = Opt.Commands.begin() + I;
313 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000314
315 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000316 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
317 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000318 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000319 continue;
320 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000321
Eugene Leviant20d03192016-09-16 15:30:47 +0000322 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
323 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000324 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000325 // will not be called, so ASSERT should be evaluated now.
326 if (!Opt.HasSections)
327 Cmd->Expression(0);
328 continue;
329 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000330
Eugene Leviantceabe802016-08-11 07:56:43 +0000331 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000332 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
333
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000334 // The output section name `/DISCARD/' is special.
335 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000336 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000337 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000338 continue;
339 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000340
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000341 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
342 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
343 // sections satisfy a given constraint. If not, a directive is handled
344 // as if it wasn't present from the beginning.
345 //
346 // Because we'll iterate over Commands many more times, the easiest
347 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000348 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
349 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000350 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000351 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000352 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000353 continue;
354 }
355
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000356 // A directive may contain symbol definitions like this:
357 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000358 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
359 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
360 if (shouldDefine<ELFT>(OutCmd))
361 addSymbol<ELFT>(OutCmd);
362
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000363 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
364 // is given, input sections are aligned to that value, whether the
365 // given value is larger or smaller than the original section alignment.
366 if (Cmd->SubalignExpr) {
367 uint32_t Subalign = Cmd->SubalignExpr(0);
368 for (InputSectionBase<ELFT> *S : V)
369 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000370 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000371
372 // Add input sections to an output section.
373 for (InputSectionBase<ELFT> *S : V)
374 addSection(Factory, S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000375 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000376 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000377}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000378
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000379// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000380template <class ELFT>
George Rimar93c64022016-12-15 15:38:09 +0000381void LinkerScript<ELFT>::addOrphanSections(
382 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000383 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000384 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000385 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000386}
387
Eugene Leviantdb741e72016-09-07 07:08:43 +0000388// Sets value of a section-defined symbol. Two kinds of
389// symbols are processed: synthetic symbols, whose value
390// is an offset from beginning of section and regular
391// symbols whose value is absolute.
392template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000393static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000394 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000395 if (!Cmd->Sym)
396 return;
397
398 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000399 Body->Section = Cmd->Expression.Section();
400 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000401 return;
402 }
403 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000404 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000405}
406
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000407template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000408 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000409}
410
Rafael Espindolad3190792016-09-16 15:10:23 +0000411template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
412 if (!AlreadyOutputIS.insert(S).second)
413 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000414 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000415
Rafael Espindolad3190792016-09-16 15:10:23 +0000416 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
417 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000418 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000419 Pos += S->getSize();
420
421 // Update output section size after adding each section. This is so that
422 // SIZEOF works correctly in the case below:
423 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000424 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000425
Rafael Espindola7252ae52016-09-22 12:00:08 +0000426 if (IsTbss)
427 ThreadBssOffset = Pos - Dot;
428 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000429 Dot = Pos;
430}
431
432template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000433 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
434 return;
435 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000436 for (InputSection<ELFT> *I : OutSec->Sections)
437 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000438 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000439 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000440 }
441}
442
443template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000444void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000445 if (CurOutSec == Sec)
446 return;
447 if (AlreadyOutputOS.count(Sec))
448 return;
449
450 flush();
451 CurOutSec = Sec;
452
Rafael Espindola04a2e342016-11-09 01:42:41 +0000453 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000454 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000455
456 // If neither AT nor AT> is specified for an allocatable section, the linker
457 // will set the LMA such that the difference between VMA and LMA for the
458 // section is the same as the preceding output section in the same region
459 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
460 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000461}
462
463template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000464 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000465 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
466 if (AssignCmd->Name == ".") {
467 // Update to location counter means update to section size.
George Rimar14460e02016-12-15 07:27:28 +0000468 uintX_t Val = AssignCmd->Expression(Dot);
469 if (Val < Dot)
470 error("unable to move location counter backward for: " +
471 CurOutSec->Name);
472 Dot = Val;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000473 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000474 return;
475 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000476 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000477 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000478 }
George Rimare38cbab2016-09-26 19:22:50 +0000479
480 // Handle BYTE(), SHORT(), LONG(), or QUAD().
481 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000482 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000483 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000484 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000485 return;
486 }
487
Meador Ingeb2d99d62016-11-22 18:01:50 +0000488 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
489 AssertCmd->Expression(Dot);
490 return;
491 }
492
George Rimare38cbab2016-09-26 19:22:50 +0000493 // It handles single input section description command,
494 // calculates and assigns the offsets for each section and also
495 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000496 auto &ICmd = cast<InputSectionDescription>(Base);
497 for (InputSectionData *ID : ICmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000498 // We tentatively added all synthetic sections at the beginning and removed
499 // empty ones afterwards (because there is no way to know whether they were
500 // going be empty or not other than actually running linker scripts.)
501 // We need to ignore remains of empty sections.
502 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
503 if (Sec->empty())
504 continue;
505
Rafael Espindolad3190792016-09-16 15:10:23 +0000506 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
507 switchTo(IB->OutSec);
508 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
509 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000510 else
511 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000512 }
513}
514
George Rimar8f66df92016-08-12 20:38:20 +0000515template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000516static std::vector<OutputSectionBase *>
517findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
518 std::vector<OutputSectionBase *> Ret;
519 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000520 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000521 Ret.push_back(Sec);
522 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000523}
524
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000525// This function assigns offsets to input sections and an output section
526// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000527template <class ELFT>
528void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000529 if (Cmd->LMAExpr)
530 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000531 std::vector<OutputSectionBase *> Sections =
532 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000533 if (Sections.empty())
534 return;
535 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000536
Rafael Espindolad3190792016-09-16 15:10:23 +0000537 // Find the last section output location. We will output orphan sections
538 // there so that end symbols point to the correct location.
539 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
540 [](const std::unique_ptr<BaseCommand> &Cmd) {
541 return !isa<SymbolAssignment>(*Cmd);
542 })
543 .base();
544 for (auto I = Cmd->Commands.begin(); I != E; ++I)
545 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000546 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000547 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000548 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000549 std::for_each(E, Cmd->Commands.end(),
550 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000551}
552
Rafael Espindola07fe6122016-11-14 14:23:35 +0000553template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000554 // It is common practice to use very generic linker scripts. So for any
555 // given run some of the output sections in the script will be empty.
556 // We could create corresponding empty output sections, but that would
557 // clutter the output.
558 // We instead remove trivially empty sections. The bfd linker seems even
559 // more aggressive at removing them.
560 auto Pos = std::remove_if(
561 Opt.Commands.begin(), Opt.Commands.end(),
562 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000563 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
564 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
565 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000566 });
567 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000568}
569
Rafael Espindola6a537372016-11-14 14:33:49 +0000570static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
571 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
572 if (!isa<InputSectionDescription>(*I))
573 return false;
574 return true;
575}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000576
Rafael Espindola6a537372016-11-14 14:33:49 +0000577template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000578 // If the output section contains only symbol assignments, create a
579 // corresponding output section. The bfd linker seems to only create them if
580 // '.' is assigned to, but creating these section should not have any bad
581 // consequeces and gives us a section to put the symbol in.
582 uintX_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000583 uint32_t Type = SHT_NOBITS;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000584 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
585 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
586 if (!Cmd)
587 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000588 std::vector<OutputSectionBase *> Secs =
589 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000590 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000591 Flags = Secs[0]->Flags;
592 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000593 continue;
594 }
595
Rafael Espindola6a537372016-11-14 14:33:49 +0000596 if (isAllSectionDescription(*Cmd))
597 continue;
598
Rui Ueyama95642b92016-11-01 23:09:07 +0000599 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000600 OutputSections->push_back(OutSec);
601 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000602}
603
604template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
605 placeOrphanSections();
606
607 // If output section command doesn't specify any segments,
608 // and we haven't previously assigned any section to segment,
609 // then we simply assign section to the very first load segment.
610 // Below is an example of such linker script:
611 // PHDRS { seg PT_LOAD; }
612 // SECTIONS { .aaa : { *(.aaa) } }
613 std::vector<StringRef> DefPhdrs;
614 auto FirstPtLoad =
615 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
616 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
617 if (FirstPtLoad != Opt.PhdrsCommands.end())
618 DefPhdrs.push_back(FirstPtLoad->Name);
619
620 // Walk the commands and propagate the program headers to commands that don't
621 // explicitly specify them.
622 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
623 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
624 if (!Cmd)
625 continue;
626 if (Cmd->Phdrs.empty())
627 Cmd->Phdrs = DefPhdrs;
628 else
629 DefPhdrs = Cmd->Phdrs;
630 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000631
632 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000633}
634
Rafael Espindola15c57952016-09-22 18:05:49 +0000635// When placing orphan sections, we want to place them after symbol assignments
636// so that an orphan after
637// begin_foo = .;
638// foo : { *(foo) }
639// end_foo = .;
640// doesn't break the intended meaning of the begin/end symbols.
641// We don't want to go over sections since Writer<ELFT>::sortSections is the
642// one in charge of deciding the order of the sections.
643// We don't want to go over alignments, since doing so in
644// rx_sec : { *(rx_sec) }
645// . = ALIGN(0x1000);
646// /* The RW PT_LOAD starts here*/
647// rw_sec : { *(rw_sec) }
648// would mean that the RW PT_LOAD would become unaligned.
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000649static bool shouldSkip(const BaseCommand &Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000650 if (isa<OutputSectionCommand>(Cmd))
651 return false;
652 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
653 if (!Assign)
654 return true;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000655 return Assign->Name != ".";
Rafael Espindola15c57952016-09-22 18:05:49 +0000656}
657
Rafael Espindola337f9032016-11-14 14:13:32 +0000658// Orphan sections are sections present in the input files which are not
659// explicitly placed into the output file by the linker script. This just
660// places them in the order already decided in OutputSections.
George Rimar93c64022016-12-15 15:38:09 +0000661template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000662 // The OutputSections are already in the correct order.
663 // This loops creates or moves commands as needed so that they are in the
664 // correct order.
665 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000666
667 // As a horrible special case, skip the first . assignment if it is before any
668 // section. We do this because it is common to set a load address by starting
669 // the script with ". = 0xabcd" and the expectation is that every section is
670 // after that.
671 auto FirstSectionOrDotAssignment =
672 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
673 [](const std::unique_ptr<BaseCommand> &Cmd) {
674 if (isa<OutputSectionCommand>(*Cmd))
675 return true;
676 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
677 if (!Assign)
678 return false;
679 return Assign->Name == ".";
680 });
681 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
682 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
683 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
684 ++CmdIndex;
685 }
686
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000687 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000688 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000689
690 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000691 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000692 auto CmdIter = Opt.Commands.begin() + CmdIndex;
693 auto E = Opt.Commands.end();
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000694 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000695 ++CmdIter;
696 ++CmdIndex;
697 }
698
699 auto Pos =
700 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
701 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
702 return Cmd && Cmd->Name == Name;
703 });
704 if (Pos == E) {
705 Opt.Commands.insert(CmdIter,
706 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000707 ++CmdIndex;
708 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000709 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000710
711 // Continue from where we found it.
712 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000713 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000714}
715
716template <class ELFT>
717void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000718 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000719 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000720
George Rimar076fe152016-07-21 06:43:01 +0000721 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
722 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000723 if (Cmd->Name == ".") {
724 Dot = Cmd->Expression(Dot);
725 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000726 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000727 }
George Rimar652852c2016-04-16 10:10:32 +0000728 continue;
729 }
730
George Rimareefa7582016-08-04 09:29:31 +0000731 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
732 Cmd->Expression(Dot);
733 continue;
734 }
735
George Rimar076fe152016-07-21 06:43:01 +0000736 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000737 if (Cmd->AddrExpr)
738 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000739 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000740 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000741
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000742 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000743 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000744 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000745 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000746 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000747 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000748 }
749
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000750 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000751 auto FirstPTLoad =
752 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
753 return E.H.p_type == PT_LOAD;
754 });
Rafael Espindolad8b81d62016-11-17 14:18:08 +0000755 if (FirstPTLoad == Phdrs.end())
756 return;
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000757
Rafael Espindola1c570072016-11-21 19:59:33 +0000758 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
759 // now that we know we have space.
760 if (HeaderSize <= MinVA && !hasPhdrsCommands()) {
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000761 FirstPTLoad->First = Out<ELFT>::ElfHeader;
762 if (!FirstPTLoad->Last)
763 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Rafael Espindola1c570072016-11-21 19:59:33 +0000764 }
765
766 // ELF and Program headers need to be right before the first section in
767 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000768 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000769 Out<ELFT>::ElfHeader->Addr = MinVA;
770 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
George Rimar652852c2016-04-16 10:10:32 +0000771}
772
Rui Ueyama464daad2016-08-22 04:55:20 +0000773// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000774template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000775std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000776 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000777
Rui Ueyama464daad2016-08-22 04:55:20 +0000778 // Process PHDRS and FILEHDR keywords because they are not
779 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000780 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000781 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
782 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000783
784 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000785 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000786 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000787 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000788
789 if (Cmd.LMAExpr) {
790 Phdr.H.p_paddr = Cmd.LMAExpr(0);
791 Phdr.HasLMA = true;
792 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000793 }
794
Rui Ueyama464daad2016-08-22 04:55:20 +0000795 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000796 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000797 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000798 break;
799
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000800 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000801 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000802 Ret[Id].add(Sec);
803 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
804 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000805 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000806 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000807 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000808}
809
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000810template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
811 // Ignore .interp section in case we have PHDRS specification
812 // and PT_INTERP isn't listed.
813 return !Opt.PhdrsCommands.empty() &&
814 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
815 return Cmd.Type == PT_INTERP;
816 }) == Opt.PhdrsCommands.end();
817}
818
George Rimar93c64022016-12-15 15:38:09 +0000819template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000820 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
821 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
822 if (Cmd->Name == Name)
823 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000824 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000825}
826
George Rimare38cbab2016-09-26 19:22:50 +0000827template <class ELFT>
828static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
829 const endianness E = ELFT::TargetEndianness;
830
831 switch (Size) {
832 case 1:
833 *Buf = (uint8_t)Data;
834 break;
835 case 2:
836 write16<E>(Buf, Data);
837 break;
838 case 4:
839 write32<E>(Buf, Data);
840 break;
841 case 8:
842 write64<E>(Buf, Data);
843 break;
844 default:
845 llvm_unreachable("unsupported Size argument");
846 }
847}
848
849template <class ELFT>
850void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
851 int I = getSectionIndex(Name);
852 if (I == INT_MAX)
853 return;
854
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000855 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
856 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
857 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
Meador Inge95c7d8d2016-12-08 23:21:30 +0000858 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000859}
860
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000861template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000862 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
863 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000864 if (Cmd->LMAExpr && Cmd->Name == Name)
865 return true;
866 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000867}
868
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000869// Returns the index of the given section name in linker script
870// SECTIONS commands. Sections are laid out as the same order as they
871// were in the script. If a given name did not appear in the script,
872// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000873template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000874 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
875 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000876 if (Cmd->Name == Name)
877 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000878 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000879}
880
Eugene Leviantbbe38602016-07-19 09:25:43 +0000881template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
882 return !Opt.PhdrsCommands.empty();
883}
884
George Rimar9e694502016-07-29 16:18:47 +0000885template <class ELFT>
Eugene Levianted30ce72016-11-28 09:58:04 +0000886const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
887 StringRef Name) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000888 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000889
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000890 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000891 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000892 return Sec;
Eugene Levianted30ce72016-11-28 09:58:04 +0000893
894 error(Loc + ": undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000895 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000896}
897
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000898// This function is essentially the same as getOutputSection(Name)->Size,
899// but it won't print out an error message if a given section is not found.
900//
901// Linker script does not create an output section if its content is empty.
902// We want to allow SIZEOF(.foo) where .foo is a section which happened to
903// be empty. That is why this function is different from getOutputSection().
904template <class ELFT>
905uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
906 for (OutputSectionBase *Sec : *OutputSections)
907 if (Sec->getName() == Name)
908 return Sec->Size;
909 return 0;
910}
911
George Rimar884e7862016-09-08 08:19:13 +0000912template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000913 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000914}
915
George Rimar884e7862016-09-08 08:19:13 +0000916template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
917 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
918 return B->getVA<ELFT>();
919 error("symbol not found: " + S);
920 return 0;
921}
922
George Rimarf34f45f2016-09-23 13:17:23 +0000923template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
924 return Symtab<ELFT>::X->find(S) != nullptr;
925}
926
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000927template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
928 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
929 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
930 return DR && !DR->Section;
931}
932
Eugene Leviantafaa9342016-11-16 09:49:39 +0000933// Gets section symbol belongs to. Symbol "." doesn't belong to any
934// specific section but isn't absolute at the same time, so we try
935// to find suitable section for it as well.
936template <class ELFT>
937const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
938 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
939 if (!Sym) {
940 if (OutputSections->empty())
941 return nullptr;
942 return CurOutSec ? CurOutSec : (*OutputSections)[0];
943 }
944
945 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
946 return DR->Section ? DR->Section->OutSec : nullptr;
947 if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
948 return DS->Section;
949
950 return nullptr;
951}
952
Eugene Leviantbbe38602016-07-19 09:25:43 +0000953// Returns indices of ELF headers containing specific section, identified
954// by Name. Each index is a zero based number of ELF header listed within
955// PHDRS {} script block.
956template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000957std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000958 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
959 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000960 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000961 continue;
962
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000963 std::vector<size_t> Ret;
964 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000965 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000966 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000967 }
George Rimar31d842f2016-07-20 16:43:03 +0000968 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000969}
970
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000971template <class ELFT>
Eugene Leviant2a942c42016-12-05 16:38:32 +0000972size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000973 size_t I = 0;
974 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
975 if (Cmd.Name == PhdrName)
976 return I;
977 ++I;
978 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000979 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000980 return 0;
981}
982
Eugene Leviant03ff0162016-11-21 15:49:56 +0000983class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000984 typedef void (ScriptParser::*Handler)();
985
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000986public:
Rui Ueyama22375f22016-11-25 18:51:54 +0000987 ScriptParser(MemoryBufferRef MB)
988 : ScriptParserBase(MB),
989 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
George Rimarf23b2322016-02-19 10:45:45 +0000990
George Rimar20b65982016-08-31 09:08:26 +0000991 void readLinkerScript();
992 void readVersionScript();
Rafael Espindolad0ebd842016-12-08 17:54:26 +0000993 void readDynamicList();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000994
995private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000996 void addFile(StringRef Path);
997
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000998 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000999 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +00001000 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001001 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001002 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +00001003 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +00001004 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001005 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001006 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +00001007 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001008 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +00001009 void readVersion();
1010 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001011
Rui Ueyama113cdec2016-07-24 23:05:57 +00001012 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +00001013 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001014 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +00001015 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +00001016 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001017 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +00001018 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +00001019 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +00001020 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +00001021 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001022 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +00001023 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +00001024 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +00001025 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +00001026 void readSort();
George Rimareefa7582016-08-04 09:29:31 +00001027 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001028
1029 Expr readExpr();
1030 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001031 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001032 Expr readPrimary();
1033 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001034 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001035
George Rimar20b65982016-08-31 09:08:26 +00001036 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001037 std::vector<SymbolVersion> readVersionExtern();
1038 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001039 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001040 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001041
Rui Ueyama07320e42016-04-20 20:13:41 +00001042 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001043 bool IsUnderSysroot;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001044 std::vector<std::unique_ptr<MemoryBuffer>> OwningMBs;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001045};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001046
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001047void ScriptParser::readDynamicList() {
1048 expect("{");
1049 readAnonymousDeclaration();
1050 if (!atEOF())
1051 setError("EOF expected, but got " + next());
1052}
1053
George Rimar20b65982016-08-31 09:08:26 +00001054void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001055 readVersionScriptCommand();
1056 if (!atEOF())
1057 setError("EOF expected, but got " + next());
1058}
1059
1060void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001061 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001062 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001063 return;
1064 }
1065
Rui Ueyama95769b42016-08-31 20:03:54 +00001066 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001067 StringRef VerStr = next();
1068 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001069 setError("anonymous version definition is used in "
1070 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001071 return;
1072 }
1073 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001074 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001075 }
1076}
1077
Rui Ueyama95769b42016-08-31 20:03:54 +00001078void ScriptParser::readVersion() {
1079 expect("{");
1080 readVersionScriptCommand();
1081 expect("}");
1082}
1083
George Rimar20b65982016-08-31 09:08:26 +00001084void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001085 while (!atEOF()) {
1086 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001087 if (Tok == ";")
1088 continue;
1089
Eugene Leviant20d03192016-09-16 15:30:47 +00001090 if (Tok == "ASSERT") {
1091 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1092 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001093 readEntry();
1094 } else if (Tok == "EXTERN") {
1095 readExtern();
1096 } else if (Tok == "GROUP" || Tok == "INPUT") {
1097 readGroup();
1098 } else if (Tok == "INCLUDE") {
1099 readInclude();
1100 } else if (Tok == "OUTPUT") {
1101 readOutput();
1102 } else if (Tok == "OUTPUT_ARCH") {
1103 readOutputArch();
1104 } else if (Tok == "OUTPUT_FORMAT") {
1105 readOutputFormat();
1106 } else if (Tok == "PHDRS") {
1107 readPhdrs();
1108 } else if (Tok == "SEARCH_DIR") {
1109 readSearchDir();
1110 } else if (Tok == "SECTIONS") {
1111 readSections();
1112 } else if (Tok == "VERSION") {
1113 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001114 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001115 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001116 } else {
George Rimar57610422016-03-11 14:43:02 +00001117 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001118 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001119 }
1120}
1121
Rui Ueyama717677a2016-02-11 21:17:59 +00001122void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001123 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001124 SmallString<128> PathData;
1125 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001126 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001127 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001128 return;
1129 }
1130 }
1131
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001132 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001133 Driver->addFile(S);
1134 } else if (S.startswith("=")) {
1135 if (Config->Sysroot.empty())
1136 Driver->addFile(S.substr(1));
1137 else
1138 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1139 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001140 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001141 } else if (sys::fs::exists(S)) {
1142 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001143 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001144 if (Optional<std::string> Path = findFromSearchPaths(S))
1145 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001146 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001147 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001148 }
1149}
1150
Rui Ueyama717677a2016-02-11 21:17:59 +00001151void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001152 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001153 bool Orig = Config->AsNeeded;
1154 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001155 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001156 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001157 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001158}
1159
Rui Ueyama717677a2016-02-11 21:17:59 +00001160void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001161 // -e <symbol> takes predecence over ENTRY(<symbol>).
1162 expect("(");
1163 StringRef Tok = next();
1164 if (Config->Entry.empty())
1165 Config->Entry = Tok;
1166 expect(")");
1167}
1168
Rui Ueyama717677a2016-02-11 21:17:59 +00001169void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001170 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001171 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001172 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001173}
1174
Rui Ueyama717677a2016-02-11 21:17:59 +00001175void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001176 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001177 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001178 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001179 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001180 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001181 else
George Rimarcd574a52016-09-09 14:35:36 +00001182 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001183 }
1184}
1185
Rui Ueyama717677a2016-02-11 21:17:59 +00001186void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001187 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001188 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001189 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001190 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001191 return;
1192 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001193 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001194 tokenize(MB->getMemBufferRef());
1195 OwningMBs.push_back(std::move(MB));
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001196}
1197
Rui Ueyama717677a2016-02-11 21:17:59 +00001198void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001199 // -o <file> takes predecence over OUTPUT(<file>).
1200 expect("(");
1201 StringRef Tok = next();
1202 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001203 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001204 expect(")");
1205}
1206
Rui Ueyama717677a2016-02-11 21:17:59 +00001207void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001208 // Error checking only for now.
1209 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001210 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001211 expect(")");
1212}
1213
Rui Ueyama717677a2016-02-11 21:17:59 +00001214void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001215 // Error checking only for now.
1216 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001217 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001218 StringRef Tok = next();
1219 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001220 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001221 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001222 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001223 return;
1224 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001225 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001226 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001227 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001228 expect(")");
1229}
1230
Eugene Leviantbbe38602016-07-19 09:25:43 +00001231void ScriptParser::readPhdrs() {
1232 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001233 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001234 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001235 Opt.PhdrsCommands.push_back(
1236 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001237 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1238
1239 PhdrCmd.Type = readPhdrType();
1240 do {
1241 Tok = next();
1242 if (Tok == ";")
1243 break;
1244 if (Tok == "FILEHDR")
1245 PhdrCmd.HasFilehdr = true;
1246 else if (Tok == "PHDRS")
1247 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001248 else if (Tok == "AT")
1249 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001250 else if (Tok == "FLAGS") {
1251 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001252 // Passing 0 for the value of dot is a bit of a hack. It means that
1253 // we accept expressions like ".|1".
1254 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001255 expect(")");
1256 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001257 setError("unexpected header attribute: " + Tok);
1258 } while (!Error);
1259 }
1260}
1261
Rui Ueyama717677a2016-02-11 21:17:59 +00001262void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001263 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001264 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001265 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001266 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001267 expect(")");
1268}
1269
Rui Ueyama717677a2016-02-11 21:17:59 +00001270void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001271 Opt.HasSections = true;
George Rimar18a30962016-11-28 10:11:10 +00001272 // -no-rosegment is used to avoid placing read only non-executable sections in
1273 // their own segment. We do the same if SECTIONS command is present in linker
1274 // script. See comment for computeFlags().
1275 Config->SingleRoRx = true;
1276
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001277 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001278 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001279 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001280 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001281 if (!Cmd) {
1282 if (Tok == "ASSERT")
1283 Cmd = new AssertCommand(readAssert());
1284 else
1285 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001286 }
Rui Ueyama10416562016-08-04 02:03:27 +00001287 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001288 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001289}
1290
Rui Ueyama708019c2016-07-24 18:19:40 +00001291static int precedence(StringRef Op) {
1292 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001293 .Cases("*", "/", 5)
1294 .Cases("+", "-", 4)
1295 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001296 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001297 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001298 .Default(-1);
1299}
1300
Eugene Leviantdb688452016-11-03 10:54:58 +00001301StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001302 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001303 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001304 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001305 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001306}
1307
George Rimarbe394db2016-09-16 20:21:55 +00001308SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001309 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001310 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001311 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001312 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001313 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001314 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001315 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001316 return SortSectionPolicy::None;
1317 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001318}
1319
George Rimar395281c2016-09-16 17:42:10 +00001320// Method reads a list of sequence of excluded files and section globs given in
1321// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1322// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001323// The semantics of that is next:
1324// * Include .foo.1 from every file.
1325// * Include .foo.2 from every file but a.o
1326// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001327std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1328 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001329 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001330 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001331 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001332 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001333 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001334 }
1335
George Rimar601e9892016-09-21 08:53:21 +00001336 std::vector<StringRef> V;
1337 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1338 V.push_back(next());
1339
1340 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001341 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001342 else
1343 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001344 }
George Rimar07171f22016-09-21 15:56:44 +00001345 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001346}
1347
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001348// Reads contents of "SECTIONS" directive. That directive contains a
1349// list of glob patterns for input sections. The grammar is as follows.
1350//
1351// <patterns> ::= <section-list>
1352// | <sort> "(" <section-list> ")"
1353// | <sort> "(" <sort> "(" <section-list> ")" ")"
1354//
1355// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1356// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1357//
1358// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001359InputSectionDescription *
1360ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001361 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001362 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001363 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001364 SortSectionPolicy Outer = readSortKind();
1365 SortSectionPolicy Inner = SortSectionPolicy::Default;
1366 std::vector<SectionPattern> V;
1367 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001368 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001369 Inner = readSortKind();
1370 if (Inner != SortSectionPolicy::Default) {
1371 expect("(");
1372 V = readInputSectionsList();
1373 expect(")");
1374 } else {
1375 V = readInputSectionsList();
1376 }
George Rimar350ece42016-08-03 08:35:59 +00001377 expect(")");
1378 } else {
George Rimar07171f22016-09-21 15:56:44 +00001379 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001380 }
George Rimar0702c4e2016-07-29 15:32:46 +00001381
George Rimar07171f22016-09-21 15:56:44 +00001382 for (SectionPattern &Pat : V) {
1383 Pat.SortInner = Inner;
1384 Pat.SortOuter = Outer;
1385 }
1386
1387 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1388 }
Rui Ueyama10416562016-08-04 02:03:27 +00001389 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001390}
1391
George Rimara2496cb2016-08-30 09:46:59 +00001392InputSectionDescription *
1393ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001394 // Input section wildcard can be surrounded by KEEP.
1395 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001396 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001397 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001398 StringRef FilePattern = next();
1399 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001400 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001401 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001402 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001403 }
George Rimara2496cb2016-08-30 09:46:59 +00001404 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001405}
1406
George Rimar03fc0102016-07-28 07:18:23 +00001407void ScriptParser::readSort() {
1408 expect("(");
1409 expect("CONSTRUCTORS");
1410 expect(")");
1411}
1412
George Rimareefa7582016-08-04 09:29:31 +00001413Expr ScriptParser::readAssert() {
1414 expect("(");
1415 Expr E = readExpr();
1416 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001417 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001418 expect(")");
1419 return [=](uint64_t Dot) {
1420 uint64_t V = E(Dot);
1421 if (!V)
1422 error(Msg);
1423 return V;
1424 };
1425}
1426
Rui Ueyama25150e82016-09-06 17:46:43 +00001427// Reads a FILL(expr) command. We handle the FILL command as an
1428// alias for =fillexp section attribute, which is different from
1429// what GNU linkers do.
1430// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001431uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001432 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001433 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001434 expect(")");
1435 expect(";");
1436 return V;
1437}
1438
Rui Ueyama10416562016-08-04 02:03:27 +00001439OutputSectionCommand *
1440ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001441 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
Eugene Leviant2a942c42016-12-05 16:38:32 +00001442 Cmd->Location = getCurrentLocation();
George Rimar58e5c4d2016-07-25 08:29:46 +00001443
1444 // Read an address expression.
1445 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1446 if (peek() != ":")
1447 Cmd->AddrExpr = readExpr();
1448
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001449 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001450
Rui Ueyama83043f22016-10-17 16:01:53 +00001451 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001452 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001453 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001454 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001455 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001456 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001457
Davide Italiano246f6812016-07-22 03:36:24 +00001458 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001459 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001460 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001461 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001462 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001463 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001464
Rui Ueyama83043f22016-10-17 16:01:53 +00001465 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001466 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001467 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001468 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001469 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001470 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001471 } else if (Tok == "ASSERT") {
1472 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1473 expect(";");
1474 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001475 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001476 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001477 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001478 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001479 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001480 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001481 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001482 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001483 }
George Rimar076fe152016-07-21 06:43:01 +00001484 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001485
Rui Ueyama83043f22016-10-17 16:01:53 +00001486 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001487 Cmd->Filler = readOutputSectionFiller(next());
1488 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001489 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001490
Rui Ueyama10416562016-08-04 02:03:27 +00001491 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001492}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001493
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001494// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1495// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1496//
1497// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1498// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1499// as 32-bit big-endian values. We will do the same as ld.gold does
1500// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001501uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001502 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001503 if (!Tok.getAsInteger(0, V))
1504 return V;
1505 setError("invalid filler expression: " + Tok);
1506 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001507}
1508
Petr Hoseka35e39c2016-08-16 01:11:16 +00001509SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001510 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001511 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001512 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001513 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001514 expect(")");
1515 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001516 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001517}
1518
Rafael Espindolac96da112016-11-01 11:30:45 +00001519SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001520 SymbolAssignment *Cmd = nullptr;
1521 if (peek() == "=" || peek() == "+=") {
1522 Cmd = readAssignment(Tok);
1523 expect(";");
1524 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001525 Cmd = readProvideHidden(true, false);
1526 } else if (Tok == "HIDDEN") {
1527 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001528 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001529 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001530 }
1531 return Cmd;
1532}
1533
George Rimar30835ea2016-07-28 21:08:56 +00001534static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1535 if (S == ".")
1536 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001537 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001538}
1539
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001540static bool isAbsolute(StringRef S) {
1541 if (S == ".")
1542 return false;
1543 return ScriptBase->isAbsolute(S);
1544}
1545
George Rimar30835ea2016-07-28 21:08:56 +00001546SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1547 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001548 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001549 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001550 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001551 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1552 // Call readExpr1 to read the whole expression.
1553 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001554 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001555 } else {
1556 E = readExpr();
1557 }
George Rimar30835ea2016-07-28 21:08:56 +00001558 if (Op == "+=")
1559 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001560 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001561}
1562
1563// This is an operator-precedence parser to parse a linker
1564// script expression.
1565Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1566
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001567static Expr combine(StringRef Op, Expr L, Expr R) {
1568 if (Op == "*")
1569 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1570 if (Op == "/") {
1571 return [=](uint64_t Dot) -> uint64_t {
1572 uint64_t RHS = R(Dot);
1573 if (RHS == 0) {
1574 error("division by zero");
1575 return 0;
1576 }
1577 return L(Dot) / RHS;
1578 };
1579 }
1580 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001581 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001582 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1583 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001584 const OutputSectionBase *S = L.Section();
1585 return S ? S : R.Section();
1586 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001587 if (Op == "-")
1588 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001589 if (Op == "<<")
1590 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1591 if (Op == ">>")
1592 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001593 if (Op == "<")
1594 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1595 if (Op == ">")
1596 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1597 if (Op == ">=")
1598 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1599 if (Op == "<=")
1600 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1601 if (Op == "==")
1602 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1603 if (Op == "!=")
1604 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1605 if (Op == "&")
1606 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001607 if (Op == "|")
1608 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001609 llvm_unreachable("invalid operator");
1610}
1611
Rui Ueyama708019c2016-07-24 18:19:40 +00001612// This is a part of the operator-precedence parser. This function
1613// assumes that the remaining token stream starts with an operator.
1614Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1615 while (!atEOF() && !Error) {
1616 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001617 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001618 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001619 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001620 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001621 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001622 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001623 Expr Rhs = readPrimary();
1624
1625 // Evaluate the remaining part of the expression first if the
1626 // next operator has greater precedence than the previous one.
1627 // For example, if we have read "+" and "3", and if the next
1628 // operator is "*", then we'll evaluate 3 * ... part first.
1629 while (!atEOF()) {
1630 StringRef Op2 = peek();
1631 if (precedence(Op2) <= precedence(Op1))
1632 break;
1633 Rhs = readExpr1(Rhs, precedence(Op2));
1634 }
1635
1636 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001637 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001638 return Lhs;
1639}
1640
1641uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001642 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001643 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001644 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001645 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001646 error("unknown constant: " + S);
1647 return 0;
1648}
1649
Rui Ueyama626e0b02016-09-02 18:19:00 +00001650// Parses Tok as an integer. Returns true if successful.
1651// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1652// and decimal numbers. Decimal numbers may have "K" (kilo) or
1653// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001654static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001655 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001656 if (Tok.startswith("-")) {
1657 if (!readInteger(Tok.substr(1), Result))
1658 return false;
1659 Result = -Result;
1660 return true;
1661 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001662
1663 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001664 if (Tok.startswith_lower("0x"))
1665 return !Tok.substr(2).getAsInteger(16, Result);
1666 if (Tok.endswith_lower("H"))
1667 return !Tok.drop_back().getAsInteger(16, Result);
1668
Rui Ueyama46247b82016-11-18 06:49:07 +00001669 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001670 int Suffix = 1;
1671 if (Tok.endswith_lower("K")) {
1672 Suffix = 1024;
1673 Tok = Tok.drop_back();
1674 } else if (Tok.endswith_lower("M")) {
1675 Suffix = 1024 * 1024;
1676 Tok = Tok.drop_back();
1677 }
1678 if (Tok.getAsInteger(10, Result))
1679 return false;
1680 Result *= Suffix;
1681 return true;
1682}
1683
George Rimare38cbab2016-09-26 19:22:50 +00001684BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1685 int Size = StringSwitch<unsigned>(Tok)
1686 .Case("BYTE", 1)
1687 .Case("SHORT", 2)
1688 .Case("LONG", 4)
1689 .Case("QUAD", 8)
1690 .Default(-1);
1691 if (Size == -1)
1692 return nullptr;
1693
Meador Inge95c7d8d2016-12-08 23:21:30 +00001694 return new BytesDataCommand(readParenExpr(), Size);
George Rimare38cbab2016-09-26 19:22:50 +00001695}
1696
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001697StringRef ScriptParser::readParenLiteral() {
1698 expect("(");
1699 StringRef Tok = next();
1700 expect(")");
1701 return Tok;
1702}
1703
Rui Ueyama708019c2016-07-24 18:19:40 +00001704Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001705 if (peek() == "(")
1706 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001707
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001708 StringRef Tok = next();
Rui Ueyamab5f1c3e2016-12-01 04:36:49 +00001709 std::string Location = getCurrentLocation();
Rui Ueyama708019c2016-07-24 18:19:40 +00001710
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001711 if (Tok == "~") {
1712 Expr E = readPrimary();
1713 return [=](uint64_t Dot) { return ~E(Dot); };
1714 }
1715 if (Tok == "-") {
1716 Expr E = readPrimary();
1717 return [=](uint64_t Dot) { return -E(Dot); };
1718 }
1719
Rui Ueyama708019c2016-07-24 18:19:40 +00001720 // Built-in functions are parsed here.
1721 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001722 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001723 StringRef Name = readParenLiteral();
Eugene Levianted30ce72016-11-28 09:58:04 +00001724 return {[=](uint64_t Dot) {
1725 return ScriptBase->getOutputSection(Location, Name)->Addr;
1726 },
1727 [=] { return false; },
1728 [=] { return ScriptBase->getOutputSection(Location, Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001729 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001730 if (Tok == "LOADADDR") {
1731 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001732 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001733 return ScriptBase->getOutputSection(Location, Name)->getLMA();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001734 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001735 }
George Rimareefa7582016-08-04 09:29:31 +00001736 if (Tok == "ASSERT")
1737 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001738 if (Tok == "ALIGN") {
Rui Ueyama5d804dc2016-12-16 18:19:35 +00001739 expect("(");
1740 Expr E = readExpr();
1741 if (consume(",")) {
1742 Expr E2 = readExpr();
1743 expect(")");
1744 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1745 }
1746 expect(")");
Rui Ueyama708019c2016-07-24 18:19:40 +00001747 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1748 }
1749 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001750 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001751 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001752 }
George Rimarf34f45f2016-09-23 13:17:23 +00001753 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001754 StringRef Name = readParenLiteral();
1755 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001756 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001757 if (Tok == "SEGMENT_START") {
1758 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001759 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001760 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001761 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001762 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001763 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001764 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001765 if (Tok == "DATA_SEGMENT_ALIGN") {
1766 expect("(");
1767 Expr E = readExpr();
1768 expect(",");
1769 readExpr();
1770 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001771 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001772 }
1773 if (Tok == "DATA_SEGMENT_END") {
1774 expect("(");
1775 expect(".");
1776 expect(")");
1777 return [](uint64_t Dot) { return Dot; };
1778 }
George Rimar276b4e62016-07-26 17:58:44 +00001779 // GNU linkers implements more complicated logic to handle
1780 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1781 // the next page boundary for simplicity.
1782 if (Tok == "DATA_SEGMENT_RELRO_END") {
1783 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001784 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001785 expect(",");
1786 readExpr();
1787 expect(")");
1788 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1789 }
George Rimar9e694502016-07-29 16:18:47 +00001790 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001791 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001792 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001793 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001794 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001795 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001796 return [=](uint64_t Dot) {
Eugene Levianted30ce72016-11-28 09:58:04 +00001797 return ScriptBase->getOutputSection(Location, Name)->Addralign;
Eugene Leviantafaa9342016-11-16 09:49:39 +00001798 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001799 }
George Rimare32a3592016-08-10 07:59:34 +00001800 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001801 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001802
George Rimar9f2f7ad2016-09-02 16:01:42 +00001803 // Tok is a literal number.
1804 uint64_t V;
1805 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001806 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001807
1808 // Tok is a symbol name.
1809 if (Tok != "." && !isValidCIdentifier(Tok))
1810 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001811 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001812 [=] { return isAbsolute(Tok); },
1813 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001814}
1815
1816Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001817 Expr L = readExpr();
1818 expect(":");
1819 Expr R = readExpr();
1820 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1821}
1822
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001823Expr ScriptParser::readParenExpr() {
1824 expect("(");
1825 Expr E = readExpr();
1826 expect(")");
1827 return E;
1828}
1829
Eugene Leviantbbe38602016-07-19 09:25:43 +00001830std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1831 std::vector<StringRef> Phdrs;
1832 while (!Error && peek().startswith(":")) {
1833 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001834 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001835 }
1836 return Phdrs;
1837}
1838
George Rimar95dd7182016-10-18 10:49:50 +00001839// Read a program header type name. The next token must be a
1840// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001841unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001842 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001843 uint64_t Val;
1844 if (readInteger(Tok, Val))
1845 return Val;
1846
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001847 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001848 .Case("PT_NULL", PT_NULL)
1849 .Case("PT_LOAD", PT_LOAD)
1850 .Case("PT_DYNAMIC", PT_DYNAMIC)
1851 .Case("PT_INTERP", PT_INTERP)
1852 .Case("PT_NOTE", PT_NOTE)
1853 .Case("PT_SHLIB", PT_SHLIB)
1854 .Case("PT_PHDR", PT_PHDR)
1855 .Case("PT_TLS", PT_TLS)
1856 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1857 .Case("PT_GNU_STACK", PT_GNU_STACK)
1858 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001859 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001860 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimara2a32c22016-12-06 17:57:42 +00001861 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
George Rimar6c55f0e2016-09-08 08:20:30 +00001862 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001863
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001864 if (Ret == (unsigned)-1) {
1865 setError("invalid program header type: " + Tok);
1866 return PT_NULL;
1867 }
1868 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001869}
1870
Rui Ueyama12450b22016-11-18 06:30:09 +00001871// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1872void ScriptParser::readAnonymousDeclaration() {
1873 // Read global symbols first. "global:" is default, so if there's
1874 // no label, we assume global symbols.
1875 if (consume("global:") || peek() != "local:")
1876 Config->VersionScriptGlobals = readSymbols();
1877
1878 // Next, read local symbols.
1879 if (consume("local:")) {
1880 if (consume("*")) {
1881 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1882 expect(";");
1883 } else {
1884 setError("local symbol list for anonymous version is not supported");
1885 }
1886 }
1887 expect("}");
1888 expect(";");
1889}
1890
1891// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001892void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001893 // Identifiers start at 2 because 0 and 1 are reserved
1894 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001895 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001896 Config->VersionDefinitions.push_back({VerStr, VersionId});
1897
Rui Ueyama12450b22016-11-18 06:30:09 +00001898 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001899 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001900 Config->VersionDefinitions.back().Globals = readSymbols();
1901
1902 // Read local symbols.
1903 if (consume("local:")) {
1904 if (consume("*")) {
1905 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1906 expect(";");
1907 } else {
1908 for (SymbolVersion V : readSymbols())
1909 Config->VersionScriptLocals.push_back(V);
1910 }
1911 }
George Rimar20b65982016-08-31 09:08:26 +00001912 expect("}");
1913
Rui Ueyama12450b22016-11-18 06:30:09 +00001914 // Each version may have a parent version. For example, "Ver2"
1915 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1916 // as a parent. This version hierarchy is, probably against your
1917 // instinct, purely for hint; the runtime doesn't care about it
1918 // at all. In LLD, we simply ignore it.
1919 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001920 skip();
George Rimar20b65982016-08-31 09:08:26 +00001921 expect(";");
1922}
1923
Rui Ueyama12450b22016-11-18 06:30:09 +00001924// Reads a list of symbols for a versions cript.
1925std::vector<SymbolVersion> ScriptParser::readSymbols() {
1926 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001927 for (;;) {
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001928 if (consume("extern")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001929 for (SymbolVersion V : readVersionExtern())
1930 Ret.push_back(V);
Rafael Espindola1ef90d22016-12-09 16:44:05 +00001931 continue;
1932 }
George Rimare0fc2422016-11-16 17:59:10 +00001933
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001934 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001935 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001936 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001937 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001938 expect(";");
1939 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001940 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001941}
1942
Rui Ueyama12450b22016-11-18 06:30:09 +00001943// Reads an "extern C++" directive, e.g.,
1944// "extern "C++" { ns::*; "f(int, double)"; };"
1945std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
Rafael Espindola7e714152016-12-08 17:26:53 +00001946 StringRef Tok = next();
1947 bool IsCXX = Tok == "\"C++\"";
1948 if (!IsCXX && Tok != "\"C\"")
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001949 setError("Unknown language");
George Rimar20b65982016-08-31 09:08:26 +00001950 expect("{");
1951
Rui Ueyama12450b22016-11-18 06:30:09 +00001952 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001953 while (!Error && peek() != "}") {
1954 StringRef Tok = next();
1955 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rafael Espindola7e714152016-12-08 17:26:53 +00001956 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001957 expect(";");
1958 }
1959
1960 expect("}");
1961 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001962 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001963}
1964
Rui Ueyama07320e42016-04-20 20:13:41 +00001965void elf::readLinkerScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001966 ScriptParser(MB).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001967}
1968
1969void elf::readVersionScript(MemoryBufferRef MB) {
Rui Ueyama22375f22016-11-25 18:51:54 +00001970 ScriptParser(MB).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001971}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001972
Rafael Espindolad0ebd842016-12-08 17:54:26 +00001973void elf::readDynamicList(MemoryBufferRef MB) {
1974 ScriptParser(MB).readDynamicList();
1975}
1976
Rui Ueyama07320e42016-04-20 20:13:41 +00001977template class elf::LinkerScript<ELF32LE>;
1978template class elf::LinkerScript<ELF32BE>;
1979template class elf::LinkerScript<ELF64LE>;
1980template class elf::LinkerScript<ELF64BE>;