blob: c3d19760b8e5f0fbb223c39df991c33798c66f4a [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama717677a2016-02-11 21:17:59 +000014#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000015#include "Config.h"
16#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000017#include "InputSection.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000018#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000019#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000020#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000021#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000022#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000023#include "Symbols.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000024#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000025#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000026#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000027#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000028#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000029#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000030#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000031#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000032#include "llvm/Support/Endian.h"
33#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000034#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000035#include "llvm/Support/MathExtras.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000036#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000037#include <algorithm>
38#include <cassert>
39#include <cstddef>
40#include <cstdint>
41#include <iterator>
42#include <limits>
43#include <memory>
44#include <string>
45#include <tuple>
46#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000047
48using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000049using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000050using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000051using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000052using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000053using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000054
George Rimar884e7862016-09-08 08:19:13 +000055LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000056ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000057
George Rimar6c55f0e2016-09-08 08:20:30 +000058template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000059 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000060 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
George Rimar463984d2016-11-15 08:07:14 +000061 0, 0, STB_GLOBAL, nullptr, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000062 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000063
64 // If we have no SECTIONS then we don't have '.' and don't call
65 // assignAddresses(). We calculate symbol value immediately in this case.
66 if (!ScriptConfig->HasSections)
67 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000068}
69
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000070template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
Eugene Leviantafaa9342016-11-16 09:49:39 +000071 // If we have SECTIONS block then output sections haven't been created yet.
72 const OutputSectionBase *Sec =
73 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
George Rimare1937bb2016-08-19 15:36:32 +000074 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
Eugene Leviantafaa9342016-11-16 09:49:39 +000075 Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000076 Cmd->Sym = Sym->body();
Eugene Leviantafaa9342016-11-16 09:49:39 +000077
78 // If we already know section then we can calculate symbol value immediately.
79 if (Sec)
80 cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
81 Cmd->Expression(0) - Sec->Addr;
Eugene Leviantceabe802016-08-11 07:56:43 +000082}
83
Eugene Leviantdb741e72016-09-07 07:08:43 +000084template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000085 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000086 addRegular<ELFT>(Cmd);
87 else
88 addSynthetic<ELFT>(Cmd);
89}
Rui Ueyama16024212016-08-11 23:22:52 +000090// If a symbol was in PROVIDE(), we need to define it only when
91// it is an undefined symbol.
92template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
93 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000094 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000095 if (!Cmd->Provide)
96 return true;
97 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
98 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000099}
100
George Rimar076fe152016-07-21 06:43:01 +0000101bool SymbolAssignment::classof(const BaseCommand *C) {
102 return C->Kind == AssignmentKind;
103}
104
105bool OutputSectionCommand::classof(const BaseCommand *C) {
106 return C->Kind == OutputSectionKind;
107}
108
George Rimareea31142016-07-21 14:26:59 +0000109bool InputSectionDescription::classof(const BaseCommand *C) {
110 return C->Kind == InputSectionKind;
111}
112
George Rimareefa7582016-08-04 09:29:31 +0000113bool AssertCommand::classof(const BaseCommand *C) {
114 return C->Kind == AssertKind;
115}
116
George Rimare38cbab2016-09-26 19:22:50 +0000117bool BytesDataCommand::classof(const BaseCommand *C) {
118 return C->Kind == BytesDataKind;
119}
120
Eugene Zelenko22886a22016-11-05 01:00:56 +0000121template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
122template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000123
Rui Ueyamae0be2902016-11-21 02:10:12 +0000124template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
125 if (S->getFile())
126 return sys::path::filename(S->getFile()->getName());
127 return "";
128}
129
Rui Ueyama07320e42016-04-20 20:13:41 +0000130template <class ELFT>
131bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000132 for (InputSectionDescription *ID : Opt.KeptSections)
133 if (ID->FilePat.match(basename(S)))
134 for (SectionPattern &P : ID->SectionPatterns)
135 if (P.SectionPat.match(S->Name))
136 return true;
George Rimareea31142016-07-21 14:26:59 +0000137 return false;
138}
139
George Rimar575208c2016-09-15 19:15:12 +0000140static bool comparePriority(InputSectionData *A, InputSectionData *B) {
141 return getPriority(A->Name) < getPriority(B->Name);
142}
143
Rafael Espindolac0028d32016-09-08 20:47:52 +0000144static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000145 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000146}
George Rimar350ece42016-08-03 08:35:59 +0000147
Rafael Espindolac0028d32016-09-08 20:47:52 +0000148static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000149 // ">" is not a mistake. Larger alignments are placed before smaller
150 // alignments in order to reduce the amount of padding necessary.
151 // This is compatible with GNU.
152 return A->Alignment > B->Alignment;
153}
George Rimar350ece42016-08-03 08:35:59 +0000154
Rafael Espindolac0028d32016-09-08 20:47:52 +0000155static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000156getComparator(SortSectionPolicy K) {
157 switch (K) {
158 case SortSectionPolicy::Alignment:
159 return compareAlignment;
160 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000161 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000162 case SortSectionPolicy::Priority:
163 return comparePriority;
164 default:
165 llvm_unreachable("unknown sort policy");
166 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000167}
George Rimar0702c4e2016-07-29 15:32:46 +0000168
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000169template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000170static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000171 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000172 if (Kind == ConstraintKind::NoConstraint)
173 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000174 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000175 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000176 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000177 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000178 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
179 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000180}
181
George Rimar07171f22016-09-21 15:56:44 +0000182static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000183 SortSectionPolicy K) {
184 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000185 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000186}
187
Rafael Espindolad3190792016-09-16 15:10:23 +0000188// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000189template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000190void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000191 // Collects all sections that satisfy constraints of I
192 // and attach them to I.
193 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000194 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000195
196 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000197 if (!S->Live || S->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000198 continue;
199
Rui Ueyamae0be2902016-11-21 02:10:12 +0000200 StringRef Filename = basename(S);
201 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
202 continue;
203 if (!Pat.SectionPat.match(S->Name))
204 continue;
205 I->Sections.push_back(S);
206 S->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000207 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000208
George Rimar07171f22016-09-21 15:56:44 +0000209 // Sort sections as instructed by SORT-family commands and --sort-section
210 // option. Because SORT-family commands can be nested at most two depth
211 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
212 // line option is respected even if a SORT command is given, the exact
213 // behavior we have here is a bit complicated. Here are the rules.
214 //
215 // 1. If two SORT commands are given, --sort-section is ignored.
216 // 2. If one SORT command is given, and if it is not SORT_NONE,
217 // --sort-section is handled as an inner SORT command.
218 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
219 // 4. If no SORT command is given, sort according to --sort-section.
220 InputSectionData **Begin = I->Sections.data() + SizeBefore;
221 InputSectionData **End = I->Sections.data() + I->Sections.size();
222 if (Pat.SortOuter != SortSectionPolicy::None) {
223 if (Pat.SortInner == SortSectionPolicy::Default)
224 sortSections(Begin, End, Config->SortSection);
225 else
226 sortSections(Begin, End, Pat.SortInner);
227 sortSections(Begin, End, Pat.SortOuter);
228 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000229 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000230}
231
232template <class ELFT>
233void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
234 for (InputSectionBase<ELFT> *S : V) {
235 S->Live = false;
236 reportDiscarded(S);
237 }
238}
239
George Rimar06ae6832016-08-12 09:07:57 +0000240template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000241std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000242LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000243 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000244
George Rimar06ae6832016-08-12 09:07:57 +0000245 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000246 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
247 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000248 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000249 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000250 for (InputSectionData *S : Cmd->Sections)
251 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000252 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000253
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000254 return Ret;
255}
256
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000257template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000258static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
259 StringRef OutsecName) {
260 // When using linker script the merge rules are different.
261 // Unfortunately, linker scripts are name based. This means that expressions
262 // like *(.foo*) can refer to multiple input sections that would normally be
263 // placed in different output sections. We cannot put them in different
264 // output sections or we would produce wrong results for
265 // start = .; *(.foo.*) end = .; *(.bar)
266 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
267 // another. The problem is that there is no way to layout those output
268 // sections such that the .foo sections are the only thing between the
269 // start and end symbols.
270
271 // An extra annoyance is that we cannot simply disable merging of the contents
272 // of SHF_MERGE sections, but our implementation requires one output section
273 // per "kind" (string or not, which size/aligment).
274 // Fortunately, creating symbols in the middle of a merge section is not
275 // supported by bfd or gold, so we can just create multiple section in that
276 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000277 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000278 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000279
280 uintX_t Alignment = 0;
281 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000282 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000283
284 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
285}
286
287template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000288void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
289 InputSectionBase<ELFT> *Sec,
290 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000291 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000292 bool IsNew;
293 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
294 if (IsNew)
295 OutputSections->push_back(OutSec);
296 OutSec->addSection(Sec);
297}
298
299template <class ELFT>
300void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000301 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
302 auto Iter = Opt.Commands.begin() + I;
303 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000304
305 // Handle symbol assignments outside of any output section.
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000306 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
307 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000308 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000309 continue;
310 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000311
Eugene Leviant20d03192016-09-16 15:30:47 +0000312 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
313 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000314 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000315 // will not be called, so ASSERT should be evaluated now.
316 if (!Opt.HasSections)
317 Cmd->Expression(0);
318 continue;
319 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000320
Eugene Leviantceabe802016-08-11 07:56:43 +0000321 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000322 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
323
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000324 // The output section name `/DISCARD/' is special.
325 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000326 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000327 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000328 continue;
329 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000330
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000331 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
332 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
333 // sections satisfy a given constraint. If not, a directive is handled
334 // as if it wasn't present from the beginning.
335 //
336 // Because we'll iterate over Commands many more times, the easiest
337 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000338 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
339 for (InputSectionBase<ELFT> *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000340 S->Assigned = false;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000341 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000342 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000343 continue;
344 }
345
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000346 // A directive may contain symbol definitions like this:
347 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000348 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
349 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
350 if (shouldDefine<ELFT>(OutCmd))
351 addSymbol<ELFT>(OutCmd);
352
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000353 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
354 // is given, input sections are aligned to that value, whether the
355 // given value is larger or smaller than the original section alignment.
356 if (Cmd->SubalignExpr) {
357 uint32_t Subalign = Cmd->SubalignExpr(0);
358 for (InputSectionBase<ELFT> *S : V)
359 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000360 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000361
362 // Add input sections to an output section.
363 for (InputSectionBase<ELFT> *S : V)
364 addSection(Factory, S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000365 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000366 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000367}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000368
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000369// Add sections that didn't match any sections command.
Eugene Leviant20d03192016-09-16 15:30:47 +0000370template <class ELFT>
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000371void LinkerScript<ELFT>::addOrphanSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000372 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000373 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000374 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000375}
376
Eugene Leviantdb741e72016-09-07 07:08:43 +0000377// Sets value of a section-defined symbol. Two kinds of
378// symbols are processed: synthetic symbols, whose value
379// is an offset from beginning of section and regular
380// symbols whose value is absolute.
381template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000382static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000383 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000384 if (!Cmd->Sym)
385 return;
386
387 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000388 Body->Section = Cmd->Expression.Section();
389 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000390 return;
391 }
392 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000393 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000394}
395
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000396template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000397 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000398}
399
Rafael Espindolad3190792016-09-16 15:10:23 +0000400template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
401 if (!AlreadyOutputIS.insert(S).second)
402 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000403 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000404
Rafael Espindolad3190792016-09-16 15:10:23 +0000405 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
406 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000407 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000408 Pos += S->getSize();
409
410 // Update output section size after adding each section. This is so that
411 // SIZEOF works correctly in the case below:
412 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000413 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000414
Rafael Espindola7252ae52016-09-22 12:00:08 +0000415 if (IsTbss)
416 ThreadBssOffset = Pos - Dot;
417 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000418 Dot = Pos;
419}
420
421template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000422 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
423 return;
424 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000425 for (InputSection<ELFT> *I : OutSec->Sections)
426 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000427 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000428 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000429 }
430}
431
432template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000433void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000434 if (CurOutSec == Sec)
435 return;
436 if (AlreadyOutputOS.count(Sec))
437 return;
438
439 flush();
440 CurOutSec = Sec;
441
Rafael Espindola04a2e342016-11-09 01:42:41 +0000442 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000443 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000444
445 // If neither AT nor AT> is specified for an allocatable section, the linker
446 // will set the LMA such that the difference between VMA and LMA for the
447 // section is the same as the preceding output section in the same region
448 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
449 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000450}
451
452template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000453 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000454 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
455 if (AssignCmd->Name == ".") {
456 // Update to location counter means update to section size.
457 Dot = AssignCmd->Expression(Dot);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000458 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000459 return;
460 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000461 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000462 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000463 }
George Rimare38cbab2016-09-26 19:22:50 +0000464
465 // Handle BYTE(), SHORT(), LONG(), or QUAD().
466 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000467 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000468 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000469 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000470 return;
471 }
472
473 // It handles single input section description command,
474 // calculates and assigns the offsets for each section and also
475 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000476 auto &ICmd = cast<InputSectionDescription>(Base);
477 for (InputSectionData *ID : ICmd.Sections) {
478 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
479 switchTo(IB->OutSec);
480 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
481 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000482 else
483 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000484 }
485}
486
George Rimar8f66df92016-08-12 20:38:20 +0000487template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000488static std::vector<OutputSectionBase *>
489findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
490 std::vector<OutputSectionBase *> Ret;
491 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000492 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000493 Ret.push_back(Sec);
494 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000495}
496
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000497// This function assigns offsets to input sections and an output section
498// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000499template <class ELFT>
500void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000501 if (Cmd->LMAExpr)
502 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000503 std::vector<OutputSectionBase *> Sections =
504 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000505 if (Sections.empty())
506 return;
507 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000508
Rafael Espindolad3190792016-09-16 15:10:23 +0000509 // Find the last section output location. We will output orphan sections
510 // there so that end symbols point to the correct location.
511 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
512 [](const std::unique_ptr<BaseCommand> &Cmd) {
513 return !isa<SymbolAssignment>(*Cmd);
514 })
515 .base();
516 for (auto I = Cmd->Commands.begin(); I != E; ++I)
517 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000518 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000519 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000520 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000521 std::for_each(E, Cmd->Commands.end(),
522 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000523}
524
Rafael Espindola07fe6122016-11-14 14:23:35 +0000525template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000526 // It is common practice to use very generic linker scripts. So for any
527 // given run some of the output sections in the script will be empty.
528 // We could create corresponding empty output sections, but that would
529 // clutter the output.
530 // We instead remove trivially empty sections. The bfd linker seems even
531 // more aggressive at removing them.
532 auto Pos = std::remove_if(
533 Opt.Commands.begin(), Opt.Commands.end(),
534 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000535 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
536 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
537 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000538 });
539 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000540}
541
Rafael Espindola6a537372016-11-14 14:33:49 +0000542static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
543 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
544 if (!isa<InputSectionDescription>(*I))
545 return false;
546 return true;
547}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000548
Rafael Espindola6a537372016-11-14 14:33:49 +0000549template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000550 // If the output section contains only symbol assignments, create a
551 // corresponding output section. The bfd linker seems to only create them if
552 // '.' is assigned to, but creating these section should not have any bad
553 // consequeces and gives us a section to put the symbol in.
554 uintX_t Flags = SHF_ALLOC;
555 uint32_t Type = 0;
556 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
557 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
558 if (!Cmd)
559 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000560 std::vector<OutputSectionBase *> Secs =
561 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000562 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000563 Flags = Secs[0]->Flags;
564 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000565 continue;
566 }
567
Rafael Espindola6a537372016-11-14 14:33:49 +0000568 if (isAllSectionDescription(*Cmd))
569 continue;
570
Rui Ueyama95642b92016-11-01 23:09:07 +0000571 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000572 OutputSections->push_back(OutSec);
573 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000574}
575
576template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
577 placeOrphanSections();
578
579 // If output section command doesn't specify any segments,
580 // and we haven't previously assigned any section to segment,
581 // then we simply assign section to the very first load segment.
582 // Below is an example of such linker script:
583 // PHDRS { seg PT_LOAD; }
584 // SECTIONS { .aaa : { *(.aaa) } }
585 std::vector<StringRef> DefPhdrs;
586 auto FirstPtLoad =
587 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
588 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
589 if (FirstPtLoad != Opt.PhdrsCommands.end())
590 DefPhdrs.push_back(FirstPtLoad->Name);
591
592 // Walk the commands and propagate the program headers to commands that don't
593 // explicitly specify them.
594 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
595 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
596 if (!Cmd)
597 continue;
598 if (Cmd->Phdrs.empty())
599 Cmd->Phdrs = DefPhdrs;
600 else
601 DefPhdrs = Cmd->Phdrs;
602 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000603
604 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000605}
606
Rafael Espindola15c57952016-09-22 18:05:49 +0000607// When placing orphan sections, we want to place them after symbol assignments
608// so that an orphan after
609// begin_foo = .;
610// foo : { *(foo) }
611// end_foo = .;
612// doesn't break the intended meaning of the begin/end symbols.
613// We don't want to go over sections since Writer<ELFT>::sortSections is the
614// one in charge of deciding the order of the sections.
615// We don't want to go over alignments, since doing so in
616// rx_sec : { *(rx_sec) }
617// . = ALIGN(0x1000);
618// /* The RW PT_LOAD starts here*/
619// rw_sec : { *(rw_sec) }
620// would mean that the RW PT_LOAD would become unaligned.
621static bool shouldSkip(const BaseCommand &Cmd) {
622 if (isa<OutputSectionCommand>(Cmd))
623 return false;
624 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
625 if (!Assign)
626 return true;
627 return Assign->Name != ".";
628}
629
Rafael Espindola337f9032016-11-14 14:13:32 +0000630// Orphan sections are sections present in the input files which are not
631// explicitly placed into the output file by the linker script. This just
632// places them in the order already decided in OutputSections.
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000633template <class ELFT>
Rafael Espindola337f9032016-11-14 14:13:32 +0000634void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000635 // The OutputSections are already in the correct order.
636 // This loops creates or moves commands as needed so that they are in the
637 // correct order.
638 int CmdIndex = 0;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000639 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000640 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000641
642 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000643 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000644 auto CmdIter = Opt.Commands.begin() + CmdIndex;
645 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000646 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000647 ++CmdIter;
648 ++CmdIndex;
649 }
650
651 auto Pos =
652 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
653 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
654 return Cmd && Cmd->Name == Name;
655 });
656 if (Pos == E) {
657 Opt.Commands.insert(CmdIter,
658 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000659 ++CmdIndex;
660 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000661 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000662
663 // Continue from where we found it.
664 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000665 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000666}
667
668template <class ELFT>
669void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000670 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000671 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000672
George Rimar076fe152016-07-21 06:43:01 +0000673 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
674 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000675 if (Cmd->Name == ".") {
676 Dot = Cmd->Expression(Dot);
677 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000678 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000679 }
George Rimar652852c2016-04-16 10:10:32 +0000680 continue;
681 }
682
George Rimareefa7582016-08-04 09:29:31 +0000683 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
684 Cmd->Expression(Dot);
685 continue;
686 }
687
George Rimar076fe152016-07-21 06:43:01 +0000688 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000689 if (Cmd->AddrExpr)
690 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000691 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000692 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000693
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000694 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000695 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000696 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000697 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000698 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000699 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000700 }
701
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000702 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000703 auto FirstPTLoad =
704 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
705 return E.H.p_type == PT_LOAD;
706 });
Rafael Espindolad8b81d62016-11-17 14:18:08 +0000707 if (FirstPTLoad == Phdrs.end())
708 return;
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000709
Rafael Espindola1c570072016-11-21 19:59:33 +0000710 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
711 // now that we know we have space.
712 if (HeaderSize <= MinVA && !hasPhdrsCommands()) {
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000713 FirstPTLoad->First = Out<ELFT>::ElfHeader;
714 if (!FirstPTLoad->Last)
715 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Rafael Espindola1c570072016-11-21 19:59:33 +0000716 }
717
718 // ELF and Program headers need to be right before the first section in
719 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000720 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000721 Out<ELFT>::ElfHeader->Addr = MinVA;
722 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
723
724 if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000725 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000726 // This happens if (all conditions met):
727 // - Linker script is used
728 // - First section in ELF image is not RO
729 // - Not enough space for program headers.
730 // The code below removes empty PT_LOAD segment and updates
731 // program headers size.
732 Phdrs.erase(FirstPTLoad);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000733 Out<ELFT>::ProgramHeaders->Size =
734 sizeof(typename ELFT::Phdr) * Phdrs.size();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000735 }
George Rimar652852c2016-04-16 10:10:32 +0000736}
737
Rui Ueyama464daad2016-08-22 04:55:20 +0000738// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000739template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000740std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000741 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000742
Rui Ueyama464daad2016-08-22 04:55:20 +0000743 // Process PHDRS and FILEHDR keywords because they are not
744 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000745 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000746 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
747 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000748
749 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000750 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000751 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000752 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000753
754 if (Cmd.LMAExpr) {
755 Phdr.H.p_paddr = Cmd.LMAExpr(0);
756 Phdr.HasLMA = true;
757 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000758 }
759
Rui Ueyama464daad2016-08-22 04:55:20 +0000760 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000761 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000762 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000763 break;
764
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000765 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000766 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000767 Ret[Id].add(Sec);
768 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
769 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000770 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000771 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000772 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000773}
774
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000775template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
776 // Ignore .interp section in case we have PHDRS specification
777 // and PT_INTERP isn't listed.
778 return !Opt.PhdrsCommands.empty() &&
779 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
780 return Cmd.Type == PT_INTERP;
781 }) == Opt.PhdrsCommands.end();
782}
783
Eugene Leviantbbe38602016-07-19 09:25:43 +0000784template <class ELFT>
Rui Ueyama16068ae2016-11-19 18:05:56 +0000785uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000786 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
787 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
788 if (Cmd->Name == Name)
789 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000790 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000791}
792
George Rimare38cbab2016-09-26 19:22:50 +0000793template <class ELFT>
794static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
795 const endianness E = ELFT::TargetEndianness;
796
797 switch (Size) {
798 case 1:
799 *Buf = (uint8_t)Data;
800 break;
801 case 2:
802 write16<E>(Buf, Data);
803 break;
804 case 4:
805 write32<E>(Buf, Data);
806 break;
807 case 8:
808 write64<E>(Buf, Data);
809 break;
810 default:
811 llvm_unreachable("unsupported Size argument");
812 }
813}
814
815template <class ELFT>
816void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
817 int I = getSectionIndex(Name);
818 if (I == INT_MAX)
819 return;
820
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000821 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
822 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
823 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
824 writeInt<ELFT>(Buf + Data->Offset, Data->Data, Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000825}
826
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000827template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000828 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
829 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000830 if (Cmd->LMAExpr && Cmd->Name == Name)
831 return true;
832 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000833}
834
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000835// Returns the index of the given section name in linker script
836// SECTIONS commands. Sections are laid out as the same order as they
837// were in the script. If a given name did not appear in the script,
838// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000839template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000840 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
841 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000842 if (Cmd->Name == Name)
843 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000844 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000845}
846
Eugene Leviantbbe38602016-07-19 09:25:43 +0000847template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
848 return !Opt.PhdrsCommands.empty();
849}
850
George Rimar9e694502016-07-29 16:18:47 +0000851template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000852const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(StringRef Name) {
853 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000854
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000855 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000856 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000857 return Sec;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000858 error("undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000859 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000860}
861
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000862// This function is essentially the same as getOutputSection(Name)->Size,
863// but it won't print out an error message if a given section is not found.
864//
865// Linker script does not create an output section if its content is empty.
866// We want to allow SIZEOF(.foo) where .foo is a section which happened to
867// be empty. That is why this function is different from getOutputSection().
868template <class ELFT>
869uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
870 for (OutputSectionBase *Sec : *OutputSections)
871 if (Sec->getName() == Name)
872 return Sec->Size;
873 return 0;
874}
875
George Rimar884e7862016-09-08 08:19:13 +0000876template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000877 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000878}
879
George Rimar884e7862016-09-08 08:19:13 +0000880template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
881 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
882 return B->getVA<ELFT>();
883 error("symbol not found: " + S);
884 return 0;
885}
886
George Rimarf34f45f2016-09-23 13:17:23 +0000887template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
888 return Symtab<ELFT>::X->find(S) != nullptr;
889}
890
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000891template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
892 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
893 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
894 return DR && !DR->Section;
895}
896
Eugene Leviantafaa9342016-11-16 09:49:39 +0000897// Gets section symbol belongs to. Symbol "." doesn't belong to any
898// specific section but isn't absolute at the same time, so we try
899// to find suitable section for it as well.
900template <class ELFT>
901const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
902 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
903 if (!Sym) {
904 if (OutputSections->empty())
905 return nullptr;
906 return CurOutSec ? CurOutSec : (*OutputSections)[0];
907 }
908
909 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
910 return DR->Section ? DR->Section->OutSec : nullptr;
911 if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
912 return DS->Section;
913
914 return nullptr;
915}
916
Eugene Leviantbbe38602016-07-19 09:25:43 +0000917// Returns indices of ELF headers containing specific section, identified
918// by Name. Each index is a zero based number of ELF header listed within
919// PHDRS {} script block.
920template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000921std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000922 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
923 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000924 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000925 continue;
926
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000927 std::vector<size_t> Ret;
928 for (StringRef PhdrName : Cmd->Phdrs)
929 Ret.push_back(getPhdrIndex(PhdrName));
930 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000931 }
George Rimar31d842f2016-07-20 16:43:03 +0000932 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000933}
934
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000935template <class ELFT>
936size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
937 size_t I = 0;
938 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
939 if (Cmd.Name == PhdrName)
940 return I;
941 ++I;
942 }
943 error("section header '" + PhdrName + "' is not listed in PHDRS");
944 return 0;
945}
946
Eugene Leviant03ff0162016-11-21 15:49:56 +0000947class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000948 typedef void (ScriptParser::*Handler)();
949
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000950public:
Eugene Leviant03ff0162016-11-21 15:49:56 +0000951 ScriptParser(MemoryBufferRef MB, bool B)
952 : ScriptParserBase(MB), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000953
George Rimar20b65982016-08-31 09:08:26 +0000954 void readLinkerScript();
955 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000956
957private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000958 void addFile(StringRef Path);
959
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000960 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000961 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000962 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000963 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000964 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000965 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000966 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000967 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000968 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000969 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000970 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000971 void readVersion();
972 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000973
Rui Ueyama113cdec2016-07-24 23:05:57 +0000974 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000975 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000976 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000977 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000978 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000979 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000980 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000981 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000982 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000983 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000984 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000985 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000986 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000987 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000988 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000989 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000990
991 Expr readExpr();
992 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000993 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000994 Expr readPrimary();
995 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000996 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000997
George Rimar20b65982016-08-31 09:08:26 +0000998 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +0000999 std::vector<SymbolVersion> readVersionExtern();
1000 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001001 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001002 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001003
Rui Ueyama07320e42016-04-20 20:13:41 +00001004 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001005 bool IsUnderSysroot;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001006 std::vector<std::unique_ptr<MemoryBuffer>> OwningMBs;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001007};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001008
George Rimar20b65982016-08-31 09:08:26 +00001009void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001010 readVersionScriptCommand();
1011 if (!atEOF())
1012 setError("EOF expected, but got " + next());
1013}
1014
1015void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001016 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001017 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001018 return;
1019 }
1020
Rui Ueyama95769b42016-08-31 20:03:54 +00001021 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001022 StringRef VerStr = next();
1023 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001024 setError("anonymous version definition is used in "
1025 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001026 return;
1027 }
1028 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001029 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001030 }
1031}
1032
Rui Ueyama95769b42016-08-31 20:03:54 +00001033void ScriptParser::readVersion() {
1034 expect("{");
1035 readVersionScriptCommand();
1036 expect("}");
1037}
1038
George Rimar20b65982016-08-31 09:08:26 +00001039void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001040 while (!atEOF()) {
1041 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001042 if (Tok == ";")
1043 continue;
1044
Eugene Leviant20d03192016-09-16 15:30:47 +00001045 if (Tok == "ASSERT") {
1046 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1047 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001048 readEntry();
1049 } else if (Tok == "EXTERN") {
1050 readExtern();
1051 } else if (Tok == "GROUP" || Tok == "INPUT") {
1052 readGroup();
1053 } else if (Tok == "INCLUDE") {
1054 readInclude();
1055 } else if (Tok == "OUTPUT") {
1056 readOutput();
1057 } else if (Tok == "OUTPUT_ARCH") {
1058 readOutputArch();
1059 } else if (Tok == "OUTPUT_FORMAT") {
1060 readOutputFormat();
1061 } else if (Tok == "PHDRS") {
1062 readPhdrs();
1063 } else if (Tok == "SEARCH_DIR") {
1064 readSearchDir();
1065 } else if (Tok == "SECTIONS") {
1066 readSections();
1067 } else if (Tok == "VERSION") {
1068 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001069 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001070 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001071 } else {
George Rimar57610422016-03-11 14:43:02 +00001072 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001073 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001074 }
1075}
1076
Rui Ueyama717677a2016-02-11 21:17:59 +00001077void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001078 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001079 SmallString<128> PathData;
1080 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001081 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001082 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001083 return;
1084 }
1085 }
1086
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001087 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001088 Driver->addFile(S);
1089 } else if (S.startswith("=")) {
1090 if (Config->Sysroot.empty())
1091 Driver->addFile(S.substr(1));
1092 else
1093 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1094 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001095 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001096 } else if (sys::fs::exists(S)) {
1097 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001098 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001099 if (Optional<std::string> Path = findFromSearchPaths(S))
1100 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001101 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001102 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001103 }
1104}
1105
Rui Ueyama717677a2016-02-11 21:17:59 +00001106void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001107 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001108 bool Orig = Config->AsNeeded;
1109 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001110 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001111 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001112 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001113}
1114
Rui Ueyama717677a2016-02-11 21:17:59 +00001115void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001116 // -e <symbol> takes predecence over ENTRY(<symbol>).
1117 expect("(");
1118 StringRef Tok = next();
1119 if (Config->Entry.empty())
1120 Config->Entry = Tok;
1121 expect(")");
1122}
1123
Rui Ueyama717677a2016-02-11 21:17:59 +00001124void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001125 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001126 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001127 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001128}
1129
Rui Ueyama717677a2016-02-11 21:17:59 +00001130void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001131 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001132 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001133 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001134 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001135 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001136 else
George Rimarcd574a52016-09-09 14:35:36 +00001137 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001138 }
1139}
1140
Rui Ueyama717677a2016-02-11 21:17:59 +00001141void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001142 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001143 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001144 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001145 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001146 return;
1147 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001148 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001149 tokenize(MB->getMemBufferRef());
1150 OwningMBs.push_back(std::move(MB));
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001151}
1152
Rui Ueyama717677a2016-02-11 21:17:59 +00001153void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001154 // -o <file> takes predecence over OUTPUT(<file>).
1155 expect("(");
1156 StringRef Tok = next();
1157 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001158 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001159 expect(")");
1160}
1161
Rui Ueyama717677a2016-02-11 21:17:59 +00001162void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001163 // Error checking only for now.
1164 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001165 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001166 expect(")");
1167}
1168
Rui Ueyama717677a2016-02-11 21:17:59 +00001169void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001170 // Error checking only for now.
1171 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001172 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001173 StringRef Tok = next();
1174 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001175 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001176 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001177 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001178 return;
1179 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001180 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001181 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001182 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001183 expect(")");
1184}
1185
Eugene Leviantbbe38602016-07-19 09:25:43 +00001186void ScriptParser::readPhdrs() {
1187 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001188 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001189 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001190 Opt.PhdrsCommands.push_back(
1191 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001192 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1193
1194 PhdrCmd.Type = readPhdrType();
1195 do {
1196 Tok = next();
1197 if (Tok == ";")
1198 break;
1199 if (Tok == "FILEHDR")
1200 PhdrCmd.HasFilehdr = true;
1201 else if (Tok == "PHDRS")
1202 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001203 else if (Tok == "AT")
1204 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001205 else if (Tok == "FLAGS") {
1206 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001207 // Passing 0 for the value of dot is a bit of a hack. It means that
1208 // we accept expressions like ".|1".
1209 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001210 expect(")");
1211 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001212 setError("unexpected header attribute: " + Tok);
1213 } while (!Error);
1214 }
1215}
1216
Rui Ueyama717677a2016-02-11 21:17:59 +00001217void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001218 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001219 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001220 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001221 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001222 expect(")");
1223}
1224
Rui Ueyama717677a2016-02-11 21:17:59 +00001225void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001226 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001227 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001228 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001229 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001230 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001231 if (!Cmd) {
1232 if (Tok == "ASSERT")
1233 Cmd = new AssertCommand(readAssert());
1234 else
1235 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001236 }
Rui Ueyama10416562016-08-04 02:03:27 +00001237 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001238 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001239}
1240
Rui Ueyama708019c2016-07-24 18:19:40 +00001241static int precedence(StringRef Op) {
1242 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001243 .Cases("*", "/", 5)
1244 .Cases("+", "-", 4)
1245 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001246 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001247 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001248 .Default(-1);
1249}
1250
Eugene Leviantdb688452016-11-03 10:54:58 +00001251StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001252 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001253 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001254 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001255 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001256}
1257
George Rimarbe394db2016-09-16 20:21:55 +00001258SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001259 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001260 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001261 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001262 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001263 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001264 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001265 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001266 return SortSectionPolicy::None;
1267 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001268}
1269
George Rimar395281c2016-09-16 17:42:10 +00001270// Method reads a list of sequence of excluded files and section globs given in
1271// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1272// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001273// The semantics of that is next:
1274// * Include .foo.1 from every file.
1275// * Include .foo.2 from every file but a.o
1276// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001277std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1278 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001279 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001280 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001281 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001282 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001283 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001284 }
1285
George Rimar601e9892016-09-21 08:53:21 +00001286 std::vector<StringRef> V;
1287 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1288 V.push_back(next());
1289
1290 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001291 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001292 else
1293 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001294 }
George Rimar07171f22016-09-21 15:56:44 +00001295 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001296}
1297
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001298// Reads contents of "SECTIONS" directive. That directive contains a
1299// list of glob patterns for input sections. The grammar is as follows.
1300//
1301// <patterns> ::= <section-list>
1302// | <sort> "(" <section-list> ")"
1303// | <sort> "(" <sort> "(" <section-list> ")" ")"
1304//
1305// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1306// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1307//
1308// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001309InputSectionDescription *
1310ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001311 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001312 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001313 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001314 SortSectionPolicy Outer = readSortKind();
1315 SortSectionPolicy Inner = SortSectionPolicy::Default;
1316 std::vector<SectionPattern> V;
1317 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001318 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001319 Inner = readSortKind();
1320 if (Inner != SortSectionPolicy::Default) {
1321 expect("(");
1322 V = readInputSectionsList();
1323 expect(")");
1324 } else {
1325 V = readInputSectionsList();
1326 }
George Rimar350ece42016-08-03 08:35:59 +00001327 expect(")");
1328 } else {
George Rimar07171f22016-09-21 15:56:44 +00001329 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001330 }
George Rimar0702c4e2016-07-29 15:32:46 +00001331
George Rimar07171f22016-09-21 15:56:44 +00001332 for (SectionPattern &Pat : V) {
1333 Pat.SortInner = Inner;
1334 Pat.SortOuter = Outer;
1335 }
1336
1337 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1338 }
Rui Ueyama10416562016-08-04 02:03:27 +00001339 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001340}
1341
George Rimara2496cb2016-08-30 09:46:59 +00001342InputSectionDescription *
1343ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001344 // Input section wildcard can be surrounded by KEEP.
1345 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001346 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001347 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001348 StringRef FilePattern = next();
1349 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001350 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001351 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001352 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001353 }
George Rimara2496cb2016-08-30 09:46:59 +00001354 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001355}
1356
George Rimar03fc0102016-07-28 07:18:23 +00001357void ScriptParser::readSort() {
1358 expect("(");
1359 expect("CONSTRUCTORS");
1360 expect(")");
1361}
1362
George Rimareefa7582016-08-04 09:29:31 +00001363Expr ScriptParser::readAssert() {
1364 expect("(");
1365 Expr E = readExpr();
1366 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001367 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001368 expect(")");
1369 return [=](uint64_t Dot) {
1370 uint64_t V = E(Dot);
1371 if (!V)
1372 error(Msg);
1373 return V;
1374 };
1375}
1376
Rui Ueyama25150e82016-09-06 17:46:43 +00001377// Reads a FILL(expr) command. We handle the FILL command as an
1378// alias for =fillexp section attribute, which is different from
1379// what GNU linkers do.
1380// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001381uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001382 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001383 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001384 expect(")");
1385 expect(";");
1386 return V;
1387}
1388
Rui Ueyama10416562016-08-04 02:03:27 +00001389OutputSectionCommand *
1390ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001391 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001392
1393 // Read an address expression.
1394 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1395 if (peek() != ":")
1396 Cmd->AddrExpr = readExpr();
1397
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001398 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001399
Rui Ueyama83043f22016-10-17 16:01:53 +00001400 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001401 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001402 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001403 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001404 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001405 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001406
Davide Italiano246f6812016-07-22 03:36:24 +00001407 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001408 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001409 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001410 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001411 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001412 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001413
Rui Ueyama83043f22016-10-17 16:01:53 +00001414 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001415 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001416 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001417 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001418 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1419 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001420 else if (Tok == "FILL")
1421 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001422 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001423 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001424 else if (peek() == "(")
1425 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001426 else
1427 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001428 }
George Rimar076fe152016-07-21 06:43:01 +00001429 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001430
Rui Ueyama83043f22016-10-17 16:01:53 +00001431 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001432 Cmd->Filler = readOutputSectionFiller(next());
1433 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001434 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001435
Rui Ueyama10416562016-08-04 02:03:27 +00001436 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001437}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001438
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001439// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1440// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1441//
1442// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1443// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1444// as 32-bit big-endian values. We will do the same as ld.gold does
1445// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001446uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001447 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001448 if (!Tok.getAsInteger(0, V))
1449 return V;
1450 setError("invalid filler expression: " + Tok);
1451 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001452}
1453
Petr Hoseka35e39c2016-08-16 01:11:16 +00001454SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001455 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001456 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001457 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001458 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001459 expect(")");
1460 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001461 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001462}
1463
Rafael Espindolac96da112016-11-01 11:30:45 +00001464SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001465 SymbolAssignment *Cmd = nullptr;
1466 if (peek() == "=" || peek() == "+=") {
1467 Cmd = readAssignment(Tok);
1468 expect(";");
1469 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001470 Cmd = readProvideHidden(true, false);
1471 } else if (Tok == "HIDDEN") {
1472 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001473 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001474 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001475 }
1476 return Cmd;
1477}
1478
George Rimar30835ea2016-07-28 21:08:56 +00001479static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1480 if (S == ".")
1481 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001482 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001483}
1484
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001485static bool isAbsolute(StringRef S) {
1486 if (S == ".")
1487 return false;
1488 return ScriptBase->isAbsolute(S);
1489}
1490
George Rimar30835ea2016-07-28 21:08:56 +00001491SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1492 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001493 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001494 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001495 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001496 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1497 // Call readExpr1 to read the whole expression.
1498 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001499 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001500 } else {
1501 E = readExpr();
1502 }
George Rimar30835ea2016-07-28 21:08:56 +00001503 if (Op == "+=")
1504 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001505 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001506}
1507
1508// This is an operator-precedence parser to parse a linker
1509// script expression.
1510Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1511
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001512static Expr combine(StringRef Op, Expr L, Expr R) {
1513 if (Op == "*")
1514 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1515 if (Op == "/") {
1516 return [=](uint64_t Dot) -> uint64_t {
1517 uint64_t RHS = R(Dot);
1518 if (RHS == 0) {
1519 error("division by zero");
1520 return 0;
1521 }
1522 return L(Dot) / RHS;
1523 };
1524 }
1525 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001526 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001527 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1528 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001529 const OutputSectionBase *S = L.Section();
1530 return S ? S : R.Section();
1531 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001532 if (Op == "-")
1533 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001534 if (Op == "<<")
1535 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1536 if (Op == ">>")
1537 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001538 if (Op == "<")
1539 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1540 if (Op == ">")
1541 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1542 if (Op == ">=")
1543 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1544 if (Op == "<=")
1545 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1546 if (Op == "==")
1547 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1548 if (Op == "!=")
1549 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1550 if (Op == "&")
1551 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001552 if (Op == "|")
1553 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001554 llvm_unreachable("invalid operator");
1555}
1556
Rui Ueyama708019c2016-07-24 18:19:40 +00001557// This is a part of the operator-precedence parser. This function
1558// assumes that the remaining token stream starts with an operator.
1559Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1560 while (!atEOF() && !Error) {
1561 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001562 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001563 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001564 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001565 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001566 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001567 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001568 Expr Rhs = readPrimary();
1569
1570 // Evaluate the remaining part of the expression first if the
1571 // next operator has greater precedence than the previous one.
1572 // For example, if we have read "+" and "3", and if the next
1573 // operator is "*", then we'll evaluate 3 * ... part first.
1574 while (!atEOF()) {
1575 StringRef Op2 = peek();
1576 if (precedence(Op2) <= precedence(Op1))
1577 break;
1578 Rhs = readExpr1(Rhs, precedence(Op2));
1579 }
1580
1581 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001582 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001583 return Lhs;
1584}
1585
1586uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001587 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001588 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001589 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001590 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001591 error("unknown constant: " + S);
1592 return 0;
1593}
1594
Rui Ueyama626e0b02016-09-02 18:19:00 +00001595// Parses Tok as an integer. Returns true if successful.
1596// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1597// and decimal numbers. Decimal numbers may have "K" (kilo) or
1598// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001599static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001600 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001601 if (Tok.startswith("-")) {
1602 if (!readInteger(Tok.substr(1), Result))
1603 return false;
1604 Result = -Result;
1605 return true;
1606 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001607
1608 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001609 if (Tok.startswith_lower("0x"))
1610 return !Tok.substr(2).getAsInteger(16, Result);
1611 if (Tok.endswith_lower("H"))
1612 return !Tok.drop_back().getAsInteger(16, Result);
1613
Rui Ueyama46247b82016-11-18 06:49:07 +00001614 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001615 int Suffix = 1;
1616 if (Tok.endswith_lower("K")) {
1617 Suffix = 1024;
1618 Tok = Tok.drop_back();
1619 } else if (Tok.endswith_lower("M")) {
1620 Suffix = 1024 * 1024;
1621 Tok = Tok.drop_back();
1622 }
1623 if (Tok.getAsInteger(10, Result))
1624 return false;
1625 Result *= Suffix;
1626 return true;
1627}
1628
George Rimare38cbab2016-09-26 19:22:50 +00001629BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1630 int Size = StringSwitch<unsigned>(Tok)
1631 .Case("BYTE", 1)
1632 .Case("SHORT", 2)
1633 .Case("LONG", 4)
1634 .Case("QUAD", 8)
1635 .Default(-1);
1636 if (Size == -1)
1637 return nullptr;
1638
1639 expect("(");
1640 uint64_t Val = 0;
1641 StringRef S = next();
1642 if (!readInteger(S, Val))
1643 setError("unexpected value: " + S);
1644 expect(")");
1645 return new BytesDataCommand(Val, Size);
1646}
1647
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001648StringRef ScriptParser::readParenLiteral() {
1649 expect("(");
1650 StringRef Tok = next();
1651 expect(")");
1652 return Tok;
1653}
1654
Rui Ueyama708019c2016-07-24 18:19:40 +00001655Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001656 if (peek() == "(")
1657 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001658
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001659 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001660
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001661 if (Tok == "~") {
1662 Expr E = readPrimary();
1663 return [=](uint64_t Dot) { return ~E(Dot); };
1664 }
1665 if (Tok == "-") {
1666 Expr E = readPrimary();
1667 return [=](uint64_t Dot) { return -E(Dot); };
1668 }
1669
Rui Ueyama708019c2016-07-24 18:19:40 +00001670 // Built-in functions are parsed here.
1671 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001672 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001673 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001674 return {
1675 [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; },
Rui Ueyama009d1742016-11-18 06:49:09 +00001676 [=] { return false; },
1677 [=] { return ScriptBase->getOutputSection(Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001678 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001679 if (Tok == "LOADADDR") {
1680 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001681 return [=](uint64_t Dot) {
1682 return ScriptBase->getOutputSection(Name)->getLMA();
1683 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001684 }
George Rimareefa7582016-08-04 09:29:31 +00001685 if (Tok == "ASSERT")
1686 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001687 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001688 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001689 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1690 }
1691 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001692 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001693 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001694 }
George Rimarf34f45f2016-09-23 13:17:23 +00001695 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001696 StringRef Name = readParenLiteral();
1697 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001698 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001699 if (Tok == "SEGMENT_START") {
1700 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001701 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001702 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001703 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001704 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001705 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001706 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001707 if (Tok == "DATA_SEGMENT_ALIGN") {
1708 expect("(");
1709 Expr E = readExpr();
1710 expect(",");
1711 readExpr();
1712 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001713 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001714 }
1715 if (Tok == "DATA_SEGMENT_END") {
1716 expect("(");
1717 expect(".");
1718 expect(")");
1719 return [](uint64_t Dot) { return Dot; };
1720 }
George Rimar276b4e62016-07-26 17:58:44 +00001721 // GNU linkers implements more complicated logic to handle
1722 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1723 // the next page boundary for simplicity.
1724 if (Tok == "DATA_SEGMENT_RELRO_END") {
1725 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001726 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001727 expect(",");
1728 readExpr();
1729 expect(")");
1730 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1731 }
George Rimar9e694502016-07-29 16:18:47 +00001732 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001733 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001734 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001735 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001736 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001737 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001738 return [=](uint64_t Dot) {
1739 return ScriptBase->getOutputSection(Name)->Addralign;
1740 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001741 }
George Rimare32a3592016-08-10 07:59:34 +00001742 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001743 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001744
George Rimar9f2f7ad2016-09-02 16:01:42 +00001745 // Tok is a literal number.
1746 uint64_t V;
1747 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001748 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001749
1750 // Tok is a symbol name.
1751 if (Tok != "." && !isValidCIdentifier(Tok))
1752 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001753 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001754 [=] { return isAbsolute(Tok); },
1755 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001756}
1757
1758Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001759 Expr L = readExpr();
1760 expect(":");
1761 Expr R = readExpr();
1762 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1763}
1764
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001765Expr ScriptParser::readParenExpr() {
1766 expect("(");
1767 Expr E = readExpr();
1768 expect(")");
1769 return E;
1770}
1771
Eugene Leviantbbe38602016-07-19 09:25:43 +00001772std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1773 std::vector<StringRef> Phdrs;
1774 while (!Error && peek().startswith(":")) {
1775 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001776 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001777 }
1778 return Phdrs;
1779}
1780
George Rimar95dd7182016-10-18 10:49:50 +00001781// Read a program header type name. The next token must be a
1782// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001783unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001784 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001785 uint64_t Val;
1786 if (readInteger(Tok, Val))
1787 return Val;
1788
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001789 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001790 .Case("PT_NULL", PT_NULL)
1791 .Case("PT_LOAD", PT_LOAD)
1792 .Case("PT_DYNAMIC", PT_DYNAMIC)
1793 .Case("PT_INTERP", PT_INTERP)
1794 .Case("PT_NOTE", PT_NOTE)
1795 .Case("PT_SHLIB", PT_SHLIB)
1796 .Case("PT_PHDR", PT_PHDR)
1797 .Case("PT_TLS", PT_TLS)
1798 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1799 .Case("PT_GNU_STACK", PT_GNU_STACK)
1800 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001801 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001802 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001803 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001804
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001805 if (Ret == (unsigned)-1) {
1806 setError("invalid program header type: " + Tok);
1807 return PT_NULL;
1808 }
1809 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001810}
1811
Rui Ueyama12450b22016-11-18 06:30:09 +00001812// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1813void ScriptParser::readAnonymousDeclaration() {
1814 // Read global symbols first. "global:" is default, so if there's
1815 // no label, we assume global symbols.
1816 if (consume("global:") || peek() != "local:")
1817 Config->VersionScriptGlobals = readSymbols();
1818
1819 // Next, read local symbols.
1820 if (consume("local:")) {
1821 if (consume("*")) {
1822 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1823 expect(";");
1824 } else {
1825 setError("local symbol list for anonymous version is not supported");
1826 }
1827 }
1828 expect("}");
1829 expect(";");
1830}
1831
1832// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001833void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001834 // Identifiers start at 2 because 0 and 1 are reserved
1835 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001836 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001837 Config->VersionDefinitions.push_back({VerStr, VersionId});
1838
Rui Ueyama12450b22016-11-18 06:30:09 +00001839 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001840 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001841 Config->VersionDefinitions.back().Globals = readSymbols();
1842
1843 // Read local symbols.
1844 if (consume("local:")) {
1845 if (consume("*")) {
1846 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1847 expect(";");
1848 } else {
1849 for (SymbolVersion V : readSymbols())
1850 Config->VersionScriptLocals.push_back(V);
1851 }
1852 }
George Rimar20b65982016-08-31 09:08:26 +00001853 expect("}");
1854
Rui Ueyama12450b22016-11-18 06:30:09 +00001855 // Each version may have a parent version. For example, "Ver2"
1856 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1857 // as a parent. This version hierarchy is, probably against your
1858 // instinct, purely for hint; the runtime doesn't care about it
1859 // at all. In LLD, we simply ignore it.
1860 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001861 skip();
George Rimar20b65982016-08-31 09:08:26 +00001862 expect(";");
1863}
1864
Rui Ueyama12450b22016-11-18 06:30:09 +00001865// Reads a list of symbols for a versions cript.
1866std::vector<SymbolVersion> ScriptParser::readSymbols() {
1867 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001868 for (;;) {
1869 if (consume("extern"))
Rui Ueyama12450b22016-11-18 06:30:09 +00001870 for (SymbolVersion V : readVersionExtern())
1871 Ret.push_back(V);
George Rimare0fc2422016-11-16 17:59:10 +00001872
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001873 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001874 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001875 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001876 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001877 expect(";");
1878 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001879 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001880}
1881
Rui Ueyama12450b22016-11-18 06:30:09 +00001882// Reads an "extern C++" directive, e.g.,
1883// "extern "C++" { ns::*; "f(int, double)"; };"
1884std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
George Rimarcd574a52016-09-09 14:35:36 +00001885 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001886 expect("{");
1887
Rui Ueyama12450b22016-11-18 06:30:09 +00001888 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001889 while (!Error && peek() != "}") {
1890 StringRef Tok = next();
1891 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rui Ueyama12450b22016-11-18 06:30:09 +00001892 Ret.push_back({unquote(Tok), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001893 expect(";");
1894 }
1895
1896 expect("}");
1897 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001898 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001899}
1900
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001901static bool isUnderSysroot(StringRef Path) {
1902 if (Config->Sysroot == "")
1903 return false;
1904 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1905 if (sys::fs::equivalent(Config->Sysroot, Path))
1906 return true;
1907 return false;
1908}
1909
Rui Ueyama07320e42016-04-20 20:13:41 +00001910void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001911 StringRef Path = MB.getBufferIdentifier();
Eugene Leviant03ff0162016-11-21 15:49:56 +00001912 ScriptParser(MB, isUnderSysroot(Path)).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001913}
1914
1915void elf::readVersionScript(MemoryBufferRef MB) {
Eugene Leviant03ff0162016-11-21 15:49:56 +00001916 ScriptParser(MB, false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001917}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001918
Rui Ueyama07320e42016-04-20 20:13:41 +00001919template class elf::LinkerScript<ELF32LE>;
1920template class elf::LinkerScript<ELF32BE>;
1921template class elf::LinkerScript<ELF64LE>;
1922template class elf::LinkerScript<ELF64BE>;