blob: add5b38fa63383dc882f0bb3e5d71b74e92ab7a8 [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
Meador Ingeb2d99d62016-11-22 18:01:50 +0000473 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
474 AssertCmd->Expression(Dot);
475 return;
476 }
477
George Rimare38cbab2016-09-26 19:22:50 +0000478 // It handles single input section description command,
479 // calculates and assigns the offsets for each section and also
480 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000481 auto &ICmd = cast<InputSectionDescription>(Base);
482 for (InputSectionData *ID : ICmd.Sections) {
483 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
484 switchTo(IB->OutSec);
485 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
486 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000487 else
488 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000489 }
490}
491
George Rimar8f66df92016-08-12 20:38:20 +0000492template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000493static std::vector<OutputSectionBase *>
494findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
495 std::vector<OutputSectionBase *> Ret;
496 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000497 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000498 Ret.push_back(Sec);
499 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000500}
501
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000502// This function assigns offsets to input sections and an output section
503// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindolad3190792016-09-16 15:10:23 +0000504template <class ELFT>
505void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000506 if (Cmd->LMAExpr)
507 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000508 std::vector<OutputSectionBase *> Sections =
509 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000510 if (Sections.empty())
511 return;
512 switchTo(Sections[0]);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000513
Rafael Espindolad3190792016-09-16 15:10:23 +0000514 // Find the last section output location. We will output orphan sections
515 // there so that end symbols point to the correct location.
516 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
517 [](const std::unique_ptr<BaseCommand> &Cmd) {
518 return !isa<SymbolAssignment>(*Cmd);
519 })
520 .base();
521 for (auto I = Cmd->Commands.begin(); I != E; ++I)
522 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000523 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000524 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000525 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000526 std::for_each(E, Cmd->Commands.end(),
527 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000528}
529
Rafael Espindola07fe6122016-11-14 14:23:35 +0000530template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000531 // It is common practice to use very generic linker scripts. So for any
532 // given run some of the output sections in the script will be empty.
533 // We could create corresponding empty output sections, but that would
534 // clutter the output.
535 // We instead remove trivially empty sections. The bfd linker seems even
536 // more aggressive at removing them.
537 auto Pos = std::remove_if(
538 Opt.Commands.begin(), Opt.Commands.end(),
539 [&](const std::unique_ptr<BaseCommand> &Base) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000540 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
541 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
542 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000543 });
544 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000545}
546
Rafael Espindola6a537372016-11-14 14:33:49 +0000547static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
548 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
549 if (!isa<InputSectionDescription>(*I))
550 return false;
551 return true;
552}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000553
Rafael Espindola6a537372016-11-14 14:33:49 +0000554template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000555 // If the output section contains only symbol assignments, create a
556 // corresponding output section. The bfd linker seems to only create them if
557 // '.' is assigned to, but creating these section should not have any bad
558 // consequeces and gives us a section to put the symbol in.
559 uintX_t Flags = SHF_ALLOC;
560 uint32_t Type = 0;
561 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
562 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
563 if (!Cmd)
564 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000565 std::vector<OutputSectionBase *> Secs =
566 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000567 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000568 Flags = Secs[0]->Flags;
569 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000570 continue;
571 }
572
Rafael Espindola6a537372016-11-14 14:33:49 +0000573 if (isAllSectionDescription(*Cmd))
574 continue;
575
Rui Ueyama95642b92016-11-01 23:09:07 +0000576 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000577 OutputSections->push_back(OutSec);
578 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000579}
580
581template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
582 placeOrphanSections();
583
584 // If output section command doesn't specify any segments,
585 // and we haven't previously assigned any section to segment,
586 // then we simply assign section to the very first load segment.
587 // Below is an example of such linker script:
588 // PHDRS { seg PT_LOAD; }
589 // SECTIONS { .aaa : { *(.aaa) } }
590 std::vector<StringRef> DefPhdrs;
591 auto FirstPtLoad =
592 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
593 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
594 if (FirstPtLoad != Opt.PhdrsCommands.end())
595 DefPhdrs.push_back(FirstPtLoad->Name);
596
597 // Walk the commands and propagate the program headers to commands that don't
598 // explicitly specify them.
599 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
600 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
601 if (!Cmd)
602 continue;
603 if (Cmd->Phdrs.empty())
604 Cmd->Phdrs = DefPhdrs;
605 else
606 DefPhdrs = Cmd->Phdrs;
607 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000608
609 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000610}
611
Rafael Espindola15c57952016-09-22 18:05:49 +0000612// When placing orphan sections, we want to place them after symbol assignments
613// so that an orphan after
614// begin_foo = .;
615// foo : { *(foo) }
616// end_foo = .;
617// doesn't break the intended meaning of the begin/end symbols.
618// We don't want to go over sections since Writer<ELFT>::sortSections is the
619// one in charge of deciding the order of the sections.
620// We don't want to go over alignments, since doing so in
621// rx_sec : { *(rx_sec) }
622// . = ALIGN(0x1000);
623// /* The RW PT_LOAD starts here*/
624// rw_sec : { *(rw_sec) }
625// would mean that the RW PT_LOAD would become unaligned.
626static bool shouldSkip(const BaseCommand &Cmd) {
627 if (isa<OutputSectionCommand>(Cmd))
628 return false;
629 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
630 if (!Assign)
631 return true;
632 return Assign->Name != ".";
633}
634
Rafael Espindola337f9032016-11-14 14:13:32 +0000635// Orphan sections are sections present in the input files which are not
636// explicitly placed into the output file by the linker script. This just
637// places them in the order already decided in OutputSections.
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000638template <class ELFT>
Rafael Espindola337f9032016-11-14 14:13:32 +0000639void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000640 // The OutputSections are already in the correct order.
641 // This loops creates or moves commands as needed so that they are in the
642 // correct order.
643 int CmdIndex = 0;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000644 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000645 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000646
647 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000648 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000649 auto CmdIter = Opt.Commands.begin() + CmdIndex;
650 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000651 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000652 ++CmdIter;
653 ++CmdIndex;
654 }
655
656 auto Pos =
657 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
658 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
659 return Cmd && Cmd->Name == Name;
660 });
661 if (Pos == E) {
662 Opt.Commands.insert(CmdIter,
663 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000664 ++CmdIndex;
665 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000666 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000667
668 // Continue from where we found it.
669 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000670 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000671}
672
673template <class ELFT>
674void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000675 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000676 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000677
George Rimar076fe152016-07-21 06:43:01 +0000678 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
679 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000680 if (Cmd->Name == ".") {
681 Dot = Cmd->Expression(Dot);
682 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000683 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000684 }
George Rimar652852c2016-04-16 10:10:32 +0000685 continue;
686 }
687
George Rimareefa7582016-08-04 09:29:31 +0000688 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
689 Cmd->Expression(Dot);
690 continue;
691 }
692
George Rimar076fe152016-07-21 06:43:01 +0000693 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rafael Espindolad3190792016-09-16 15:10:23 +0000694 if (Cmd->AddrExpr)
695 Dot = Cmd->AddrExpr(Dot);
Rafael Espindolad3190792016-09-16 15:10:23 +0000696 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000697 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000698
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000699 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000700 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000701 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000702 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000703 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000704 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000705 }
706
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000707 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000708 auto FirstPTLoad =
709 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
710 return E.H.p_type == PT_LOAD;
711 });
Rafael Espindolad8b81d62016-11-17 14:18:08 +0000712 if (FirstPTLoad == Phdrs.end())
713 return;
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000714
Rafael Espindola1c570072016-11-21 19:59:33 +0000715 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
716 // now that we know we have space.
717 if (HeaderSize <= MinVA && !hasPhdrsCommands()) {
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000718 FirstPTLoad->First = Out<ELFT>::ElfHeader;
719 if (!FirstPTLoad->Last)
720 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Rafael Espindola1c570072016-11-21 19:59:33 +0000721 }
722
723 // ELF and Program headers need to be right before the first section in
724 // memory. Set their addresses accordingly.
Rafael Espindola28d5f052016-11-21 20:20:04 +0000725 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
Rafael Espindola1c570072016-11-21 19:59:33 +0000726 Out<ELFT>::ElfHeader->Addr = MinVA;
727 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
728
729 if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000730 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000731 // This happens if (all conditions met):
732 // - Linker script is used
733 // - First section in ELF image is not RO
734 // - Not enough space for program headers.
735 // The code below removes empty PT_LOAD segment and updates
736 // program headers size.
737 Phdrs.erase(FirstPTLoad);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000738 Out<ELFT>::ProgramHeaders->Size =
739 sizeof(typename ELFT::Phdr) * Phdrs.size();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000740 }
George Rimar652852c2016-04-16 10:10:32 +0000741}
742
Rui Ueyama464daad2016-08-22 04:55:20 +0000743// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000744template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000745std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000746 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000747
Rui Ueyama464daad2016-08-22 04:55:20 +0000748 // Process PHDRS and FILEHDR keywords because they are not
749 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000750 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000751 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
752 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000753
754 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000755 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000756 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000757 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000758
759 if (Cmd.LMAExpr) {
760 Phdr.H.p_paddr = Cmd.LMAExpr(0);
761 Phdr.HasLMA = true;
762 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000763 }
764
Rui Ueyama464daad2016-08-22 04:55:20 +0000765 // Add output sections to program headers.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000766 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000767 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000768 break;
769
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000770 // Assign headers specified by linker script
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000771 for (size_t Id : getPhdrIndices(Sec->getName())) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000772 Ret[Id].add(Sec);
773 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
774 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000775 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000776 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000777 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000778}
779
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000780template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
781 // Ignore .interp section in case we have PHDRS specification
782 // and PT_INTERP isn't listed.
783 return !Opt.PhdrsCommands.empty() &&
784 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
785 return Cmd.Type == PT_INTERP;
786 }) == Opt.PhdrsCommands.end();
787}
788
Eugene Leviantbbe38602016-07-19 09:25:43 +0000789template <class ELFT>
Rui Ueyama16068ae2016-11-19 18:05:56 +0000790uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000791 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
792 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
793 if (Cmd->Name == Name)
794 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000795 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000796}
797
George Rimare38cbab2016-09-26 19:22:50 +0000798template <class ELFT>
799static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
800 const endianness E = ELFT::TargetEndianness;
801
802 switch (Size) {
803 case 1:
804 *Buf = (uint8_t)Data;
805 break;
806 case 2:
807 write16<E>(Buf, Data);
808 break;
809 case 4:
810 write32<E>(Buf, Data);
811 break;
812 case 8:
813 write64<E>(Buf, Data);
814 break;
815 default:
816 llvm_unreachable("unsupported Size argument");
817 }
818}
819
820template <class ELFT>
821void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
822 int I = getSectionIndex(Name);
823 if (I == INT_MAX)
824 return;
825
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000826 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
827 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
828 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
829 writeInt<ELFT>(Buf + Data->Offset, Data->Data, Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000830}
831
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000832template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000833 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
834 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000835 if (Cmd->LMAExpr && Cmd->Name == Name)
836 return true;
837 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000838}
839
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000840// Returns the index of the given section name in linker script
841// SECTIONS commands. Sections are laid out as the same order as they
842// were in the script. If a given name did not appear in the script,
843// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000844template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000845 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
846 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000847 if (Cmd->Name == Name)
848 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000849 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000850}
851
Eugene Leviantbbe38602016-07-19 09:25:43 +0000852template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
853 return !Opt.PhdrsCommands.empty();
854}
855
George Rimar9e694502016-07-29 16:18:47 +0000856template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000857const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(StringRef Name) {
858 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000859
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000860 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000861 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000862 return Sec;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000863 error("undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000864 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000865}
866
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000867// This function is essentially the same as getOutputSection(Name)->Size,
868// but it won't print out an error message if a given section is not found.
869//
870// Linker script does not create an output section if its content is empty.
871// We want to allow SIZEOF(.foo) where .foo is a section which happened to
872// be empty. That is why this function is different from getOutputSection().
873template <class ELFT>
874uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
875 for (OutputSectionBase *Sec : *OutputSections)
876 if (Sec->getName() == Name)
877 return Sec->Size;
878 return 0;
879}
880
George Rimar884e7862016-09-08 08:19:13 +0000881template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000882 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000883}
884
George Rimar884e7862016-09-08 08:19:13 +0000885template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
886 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
887 return B->getVA<ELFT>();
888 error("symbol not found: " + S);
889 return 0;
890}
891
George Rimarf34f45f2016-09-23 13:17:23 +0000892template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
893 return Symtab<ELFT>::X->find(S) != nullptr;
894}
895
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000896template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
897 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
898 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
899 return DR && !DR->Section;
900}
901
Eugene Leviantafaa9342016-11-16 09:49:39 +0000902// Gets section symbol belongs to. Symbol "." doesn't belong to any
903// specific section but isn't absolute at the same time, so we try
904// to find suitable section for it as well.
905template <class ELFT>
906const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
907 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
908 if (!Sym) {
909 if (OutputSections->empty())
910 return nullptr;
911 return CurOutSec ? CurOutSec : (*OutputSections)[0];
912 }
913
914 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
915 return DR->Section ? DR->Section->OutSec : nullptr;
916 if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
917 return DS->Section;
918
919 return nullptr;
920}
921
Eugene Leviantbbe38602016-07-19 09:25:43 +0000922// Returns indices of ELF headers containing specific section, identified
923// by Name. Each index is a zero based number of ELF header listed within
924// PHDRS {} script block.
925template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000926std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000927 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
928 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000929 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000930 continue;
931
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000932 std::vector<size_t> Ret;
933 for (StringRef PhdrName : Cmd->Phdrs)
934 Ret.push_back(getPhdrIndex(PhdrName));
935 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000936 }
George Rimar31d842f2016-07-20 16:43:03 +0000937 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000938}
939
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000940template <class ELFT>
941size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
942 size_t I = 0;
943 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
944 if (Cmd.Name == PhdrName)
945 return I;
946 ++I;
947 }
948 error("section header '" + PhdrName + "' is not listed in PHDRS");
949 return 0;
950}
951
Eugene Leviant03ff0162016-11-21 15:49:56 +0000952class elf::ScriptParser final : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000953 typedef void (ScriptParser::*Handler)();
954
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000955public:
Eugene Leviant03ff0162016-11-21 15:49:56 +0000956 ScriptParser(MemoryBufferRef MB, bool B)
957 : ScriptParserBase(MB), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000958
George Rimar20b65982016-08-31 09:08:26 +0000959 void readLinkerScript();
960 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000961
962private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000963 void addFile(StringRef Path);
964
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000965 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000966 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000967 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000968 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000969 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000970 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000971 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000972 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000973 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000974 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000975 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000976 void readVersion();
977 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000978
Rui Ueyama113cdec2016-07-24 23:05:57 +0000979 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000980 BytesDataCommand *readBytesDataCommand(StringRef Tok);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000981 uint32_t readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000982 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyama16068ae2016-11-19 18:05:56 +0000983 uint32_t readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000984 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000985 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000986 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000987 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000988 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000989 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000990 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000991 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000992 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000993 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000994 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000995
996 Expr readExpr();
997 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000998 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000999 Expr readPrimary();
1000 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001001 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001002
George Rimar20b65982016-08-31 09:08:26 +00001003 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001004 std::vector<SymbolVersion> readVersionExtern();
1005 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001006 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001007 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001008
Rui Ueyama07320e42016-04-20 20:13:41 +00001009 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001010 bool IsUnderSysroot;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001011 std::vector<std::unique_ptr<MemoryBuffer>> OwningMBs;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001012};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001013
George Rimar20b65982016-08-31 09:08:26 +00001014void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001015 readVersionScriptCommand();
1016 if (!atEOF())
1017 setError("EOF expected, but got " + next());
1018}
1019
1020void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001021 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001022 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001023 return;
1024 }
1025
Rui Ueyama95769b42016-08-31 20:03:54 +00001026 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001027 StringRef VerStr = next();
1028 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001029 setError("anonymous version definition is used in "
1030 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001031 return;
1032 }
1033 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001034 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001035 }
1036}
1037
Rui Ueyama95769b42016-08-31 20:03:54 +00001038void ScriptParser::readVersion() {
1039 expect("{");
1040 readVersionScriptCommand();
1041 expect("}");
1042}
1043
George Rimar20b65982016-08-31 09:08:26 +00001044void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001045 while (!atEOF()) {
1046 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001047 if (Tok == ";")
1048 continue;
1049
Eugene Leviant20d03192016-09-16 15:30:47 +00001050 if (Tok == "ASSERT") {
1051 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1052 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001053 readEntry();
1054 } else if (Tok == "EXTERN") {
1055 readExtern();
1056 } else if (Tok == "GROUP" || Tok == "INPUT") {
1057 readGroup();
1058 } else if (Tok == "INCLUDE") {
1059 readInclude();
1060 } else if (Tok == "OUTPUT") {
1061 readOutput();
1062 } else if (Tok == "OUTPUT_ARCH") {
1063 readOutputArch();
1064 } else if (Tok == "OUTPUT_FORMAT") {
1065 readOutputFormat();
1066 } else if (Tok == "PHDRS") {
1067 readPhdrs();
1068 } else if (Tok == "SEARCH_DIR") {
1069 readSearchDir();
1070 } else if (Tok == "SECTIONS") {
1071 readSections();
1072 } else if (Tok == "VERSION") {
1073 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001074 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001075 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001076 } else {
George Rimar57610422016-03-11 14:43:02 +00001077 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001078 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001079 }
1080}
1081
Rui Ueyama717677a2016-02-11 21:17:59 +00001082void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001083 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001084 SmallString<128> PathData;
1085 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001086 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001087 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001088 return;
1089 }
1090 }
1091
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001092 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001093 Driver->addFile(S);
1094 } else if (S.startswith("=")) {
1095 if (Config->Sysroot.empty())
1096 Driver->addFile(S.substr(1));
1097 else
1098 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1099 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001100 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001101 } else if (sys::fs::exists(S)) {
1102 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001103 } else {
Rui Ueyama061f9282016-11-19 19:23:58 +00001104 if (Optional<std::string> Path = findFromSearchPaths(S))
1105 Driver->addFile(Saver.save(*Path));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001106 else
Rui Ueyama061f9282016-11-19 19:23:58 +00001107 setError("unable to find " + S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001108 }
1109}
1110
Rui Ueyama717677a2016-02-11 21:17:59 +00001111void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001112 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001113 bool Orig = Config->AsNeeded;
1114 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001115 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001116 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001117 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001118}
1119
Rui Ueyama717677a2016-02-11 21:17:59 +00001120void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001121 // -e <symbol> takes predecence over ENTRY(<symbol>).
1122 expect("(");
1123 StringRef Tok = next();
1124 if (Config->Entry.empty())
1125 Config->Entry = Tok;
1126 expect(")");
1127}
1128
Rui Ueyama717677a2016-02-11 21:17:59 +00001129void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001130 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001131 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001132 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001133}
1134
Rui Ueyama717677a2016-02-11 21:17:59 +00001135void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001136 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001137 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001138 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001139 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001140 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001141 else
George Rimarcd574a52016-09-09 14:35:36 +00001142 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001143 }
1144}
1145
Rui Ueyama717677a2016-02-11 21:17:59 +00001146void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001147 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001148 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001149 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001150 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001151 return;
1152 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001153 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Eugene Leviant03ff0162016-11-21 15:49:56 +00001154 tokenize(MB->getMemBufferRef());
1155 OwningMBs.push_back(std::move(MB));
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001156}
1157
Rui Ueyama717677a2016-02-11 21:17:59 +00001158void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001159 // -o <file> takes predecence over OUTPUT(<file>).
1160 expect("(");
1161 StringRef Tok = next();
1162 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001163 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001164 expect(")");
1165}
1166
Rui Ueyama717677a2016-02-11 21:17:59 +00001167void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001168 // Error checking only for now.
1169 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001170 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001171 expect(")");
1172}
1173
Rui Ueyama717677a2016-02-11 21:17:59 +00001174void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001175 // Error checking only for now.
1176 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001177 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001178 StringRef Tok = next();
1179 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001180 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001181 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001182 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001183 return;
1184 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001185 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001186 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001187 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001188 expect(")");
1189}
1190
Eugene Leviantbbe38602016-07-19 09:25:43 +00001191void ScriptParser::readPhdrs() {
1192 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001193 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001194 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001195 Opt.PhdrsCommands.push_back(
1196 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001197 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1198
1199 PhdrCmd.Type = readPhdrType();
1200 do {
1201 Tok = next();
1202 if (Tok == ";")
1203 break;
1204 if (Tok == "FILEHDR")
1205 PhdrCmd.HasFilehdr = true;
1206 else if (Tok == "PHDRS")
1207 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001208 else if (Tok == "AT")
1209 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001210 else if (Tok == "FLAGS") {
1211 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001212 // Passing 0 for the value of dot is a bit of a hack. It means that
1213 // we accept expressions like ".|1".
1214 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001215 expect(")");
1216 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001217 setError("unexpected header attribute: " + Tok);
1218 } while (!Error);
1219 }
1220}
1221
Rui Ueyama717677a2016-02-11 21:17:59 +00001222void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001223 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001224 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001225 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001226 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001227 expect(")");
1228}
1229
Rui Ueyama717677a2016-02-11 21:17:59 +00001230void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001231 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001232 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001233 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001234 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001235 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001236 if (!Cmd) {
1237 if (Tok == "ASSERT")
1238 Cmd = new AssertCommand(readAssert());
1239 else
1240 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001241 }
Rui Ueyama10416562016-08-04 02:03:27 +00001242 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001243 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001244}
1245
Rui Ueyama708019c2016-07-24 18:19:40 +00001246static int precedence(StringRef Op) {
1247 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001248 .Cases("*", "/", 5)
1249 .Cases("+", "-", 4)
1250 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001251 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001252 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001253 .Default(-1);
1254}
1255
Eugene Leviantdb688452016-11-03 10:54:58 +00001256StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001257 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001258 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001259 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001260 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001261}
1262
George Rimarbe394db2016-09-16 20:21:55 +00001263SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001264 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001265 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001266 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001267 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001268 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001269 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001270 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001271 return SortSectionPolicy::None;
1272 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001273}
1274
George Rimar395281c2016-09-16 17:42:10 +00001275// Method reads a list of sequence of excluded files and section globs given in
1276// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1277// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001278// The semantics of that is next:
1279// * Include .foo.1 from every file.
1280// * Include .foo.2 from every file but a.o
1281// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001282std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1283 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001284 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001285 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001286 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001287 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001288 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001289 }
1290
George Rimar601e9892016-09-21 08:53:21 +00001291 std::vector<StringRef> V;
1292 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1293 V.push_back(next());
1294
1295 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001296 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001297 else
1298 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001299 }
George Rimar07171f22016-09-21 15:56:44 +00001300 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001301}
1302
Rui Ueyamaf8f6f1e2016-11-18 07:03:56 +00001303// Reads contents of "SECTIONS" directive. That directive contains a
1304// list of glob patterns for input sections. The grammar is as follows.
1305//
1306// <patterns> ::= <section-list>
1307// | <sort> "(" <section-list> ")"
1308// | <sort> "(" <sort> "(" <section-list> ")" ")"
1309//
1310// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1311// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1312//
1313// <section-list> is parsed by readInputSectionsList().
George Rimara2496cb2016-08-30 09:46:59 +00001314InputSectionDescription *
1315ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001316 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001317 expect("(");
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001318 while (!Error && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001319 SortSectionPolicy Outer = readSortKind();
1320 SortSectionPolicy Inner = SortSectionPolicy::Default;
1321 std::vector<SectionPattern> V;
1322 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001323 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001324 Inner = readSortKind();
1325 if (Inner != SortSectionPolicy::Default) {
1326 expect("(");
1327 V = readInputSectionsList();
1328 expect(")");
1329 } else {
1330 V = readInputSectionsList();
1331 }
George Rimar350ece42016-08-03 08:35:59 +00001332 expect(")");
1333 } else {
George Rimar07171f22016-09-21 15:56:44 +00001334 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001335 }
George Rimar0702c4e2016-07-29 15:32:46 +00001336
George Rimar07171f22016-09-21 15:56:44 +00001337 for (SectionPattern &Pat : V) {
1338 Pat.SortInner = Inner;
1339 Pat.SortOuter = Outer;
1340 }
1341
1342 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1343 }
Rui Ueyama10416562016-08-04 02:03:27 +00001344 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001345}
1346
George Rimara2496cb2016-08-30 09:46:59 +00001347InputSectionDescription *
1348ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001349 // Input section wildcard can be surrounded by KEEP.
1350 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001351 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001352 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001353 StringRef FilePattern = next();
1354 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001355 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001356 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001357 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001358 }
George Rimara2496cb2016-08-30 09:46:59 +00001359 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001360}
1361
George Rimar03fc0102016-07-28 07:18:23 +00001362void ScriptParser::readSort() {
1363 expect("(");
1364 expect("CONSTRUCTORS");
1365 expect(")");
1366}
1367
George Rimareefa7582016-08-04 09:29:31 +00001368Expr ScriptParser::readAssert() {
1369 expect("(");
1370 Expr E = readExpr();
1371 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001372 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001373 expect(")");
1374 return [=](uint64_t Dot) {
1375 uint64_t V = E(Dot);
1376 if (!V)
1377 error(Msg);
1378 return V;
1379 };
1380}
1381
Rui Ueyama25150e82016-09-06 17:46:43 +00001382// Reads a FILL(expr) command. We handle the FILL command as an
1383// alias for =fillexp section attribute, which is different from
1384// what GNU linkers do.
1385// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
Rui Ueyama16068ae2016-11-19 18:05:56 +00001386uint32_t ScriptParser::readFill() {
George Rimarff1f29e2016-09-06 13:51:57 +00001387 expect("(");
Rui Ueyama16068ae2016-11-19 18:05:56 +00001388 uint32_t V = readOutputSectionFiller(next());
George Rimarff1f29e2016-09-06 13:51:57 +00001389 expect(")");
1390 expect(";");
1391 return V;
1392}
1393
Rui Ueyama10416562016-08-04 02:03:27 +00001394OutputSectionCommand *
1395ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001396 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001397
1398 // Read an address expression.
1399 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1400 if (peek() != ":")
1401 Cmd->AddrExpr = readExpr();
1402
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001403 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001404
Rui Ueyama83043f22016-10-17 16:01:53 +00001405 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001406 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001407 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001408 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001409 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001410 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001411
Davide Italiano246f6812016-07-22 03:36:24 +00001412 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001413 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001414 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001415 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001416 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001417 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001418
Rui Ueyama83043f22016-10-17 16:01:53 +00001419 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001420 StringRef Tok = next();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001421 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001422 Cmd->Commands.emplace_back(Assignment);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001423 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
George Rimare38cbab2016-09-26 19:22:50 +00001424 Cmd->Commands.emplace_back(Data);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001425 } else if (Tok == "ASSERT") {
1426 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1427 expect(";");
1428 } else if (Tok == "FILL") {
George Rimarff1f29e2016-09-06 13:51:57 +00001429 Cmd->Filler = readFill();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001430 } else if (Tok == "SORT") {
George Rimar03fc0102016-07-28 07:18:23 +00001431 readSort();
Meador Ingeb2d99d62016-11-22 18:01:50 +00001432 } else if (peek() == "(") {
George Rimara2496cb2016-08-30 09:46:59 +00001433 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Meador Ingeb2d99d62016-11-22 18:01:50 +00001434 } else {
Eugene Leviantceabe802016-08-11 07:56:43 +00001435 setError("unknown command " + Tok);
Meador Ingeb2d99d62016-11-22 18:01:50 +00001436 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001437 }
George Rimar076fe152016-07-21 06:43:01 +00001438 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001439
Rui Ueyama83043f22016-10-17 16:01:53 +00001440 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001441 Cmd->Filler = readOutputSectionFiller(next());
1442 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001443 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001444
Rui Ueyama10416562016-08-04 02:03:27 +00001445 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001446}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001447
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001448// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1449// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1450//
1451// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1452// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1453// as 32-bit big-endian values. We will do the same as ld.gold does
1454// because it's simpler than what ld.bfd does.
Rui Ueyama16068ae2016-11-19 18:05:56 +00001455uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001456 uint32_t V;
Rui Ueyama16068ae2016-11-19 18:05:56 +00001457 if (!Tok.getAsInteger(0, V))
1458 return V;
1459 setError("invalid filler expression: " + Tok);
1460 return 0;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001461}
1462
Petr Hoseka35e39c2016-08-16 01:11:16 +00001463SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001464 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001465 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001466 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001467 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001468 expect(")");
1469 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001470 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001471}
1472
Rafael Espindolac96da112016-11-01 11:30:45 +00001473SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001474 SymbolAssignment *Cmd = nullptr;
1475 if (peek() == "=" || peek() == "+=") {
1476 Cmd = readAssignment(Tok);
1477 expect(";");
1478 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001479 Cmd = readProvideHidden(true, false);
1480 } else if (Tok == "HIDDEN") {
1481 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001482 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001483 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001484 }
1485 return Cmd;
1486}
1487
George Rimar30835ea2016-07-28 21:08:56 +00001488static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1489 if (S == ".")
1490 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001491 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001492}
1493
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001494static bool isAbsolute(StringRef S) {
1495 if (S == ".")
1496 return false;
1497 return ScriptBase->isAbsolute(S);
1498}
1499
George Rimar30835ea2016-07-28 21:08:56 +00001500SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1501 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001502 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001503 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001504 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001505 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1506 // Call readExpr1 to read the whole expression.
1507 E = readExpr1(readParenExpr(), 0);
Rui Ueyama009d1742016-11-18 06:49:09 +00001508 E.IsAbsolute = [] { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001509 } else {
1510 E = readExpr();
1511 }
George Rimar30835ea2016-07-28 21:08:56 +00001512 if (Op == "+=")
1513 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001514 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001515}
1516
1517// This is an operator-precedence parser to parse a linker
1518// script expression.
1519Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1520
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001521static Expr combine(StringRef Op, Expr L, Expr R) {
1522 if (Op == "*")
1523 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1524 if (Op == "/") {
1525 return [=](uint64_t Dot) -> uint64_t {
1526 uint64_t RHS = R(Dot);
1527 if (RHS == 0) {
1528 error("division by zero");
1529 return 0;
1530 }
1531 return L(Dot) / RHS;
1532 };
1533 }
1534 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001535 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001536 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1537 [=] {
Eugene Leviantafaa9342016-11-16 09:49:39 +00001538 const OutputSectionBase *S = L.Section();
1539 return S ? S : R.Section();
1540 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001541 if (Op == "-")
1542 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001543 if (Op == "<<")
1544 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1545 if (Op == ">>")
1546 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001547 if (Op == "<")
1548 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1549 if (Op == ">")
1550 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1551 if (Op == ">=")
1552 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1553 if (Op == "<=")
1554 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1555 if (Op == "==")
1556 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1557 if (Op == "!=")
1558 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1559 if (Op == "&")
1560 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001561 if (Op == "|")
1562 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001563 llvm_unreachable("invalid operator");
1564}
1565
Rui Ueyama708019c2016-07-24 18:19:40 +00001566// This is a part of the operator-precedence parser. This function
1567// assumes that the remaining token stream starts with an operator.
1568Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1569 while (!atEOF() && !Error) {
1570 // Read an operator and an expression.
Rui Ueyama46247b82016-11-18 06:49:07 +00001571 if (consume("?"))
Rui Ueyama708019c2016-07-24 18:19:40 +00001572 return readTernary(Lhs);
Rui Ueyama46247b82016-11-18 06:49:07 +00001573 StringRef Op1 = peek();
Rui Ueyama708019c2016-07-24 18:19:40 +00001574 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001575 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001576 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001577 Expr Rhs = readPrimary();
1578
1579 // Evaluate the remaining part of the expression first if the
1580 // next operator has greater precedence than the previous one.
1581 // For example, if we have read "+" and "3", and if the next
1582 // operator is "*", then we'll evaluate 3 * ... part first.
1583 while (!atEOF()) {
1584 StringRef Op2 = peek();
1585 if (precedence(Op2) <= precedence(Op1))
1586 break;
1587 Rhs = readExpr1(Rhs, precedence(Op2));
1588 }
1589
1590 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001591 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001592 return Lhs;
1593}
1594
1595uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001596 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001597 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001598 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001599 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001600 error("unknown constant: " + S);
1601 return 0;
1602}
1603
Rui Ueyama626e0b02016-09-02 18:19:00 +00001604// Parses Tok as an integer. Returns true if successful.
1605// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1606// and decimal numbers. Decimal numbers may have "K" (kilo) or
1607// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001608static bool readInteger(StringRef Tok, uint64_t &Result) {
Rui Ueyama46247b82016-11-18 06:49:07 +00001609 // Negative number
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001610 if (Tok.startswith("-")) {
1611 if (!readInteger(Tok.substr(1), Result))
1612 return false;
1613 Result = -Result;
1614 return true;
1615 }
Rui Ueyama46247b82016-11-18 06:49:07 +00001616
1617 // Hexadecimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001618 if (Tok.startswith_lower("0x"))
1619 return !Tok.substr(2).getAsInteger(16, Result);
1620 if (Tok.endswith_lower("H"))
1621 return !Tok.drop_back().getAsInteger(16, Result);
1622
Rui Ueyama46247b82016-11-18 06:49:07 +00001623 // Decimal
George Rimar9f2f7ad2016-09-02 16:01:42 +00001624 int Suffix = 1;
1625 if (Tok.endswith_lower("K")) {
1626 Suffix = 1024;
1627 Tok = Tok.drop_back();
1628 } else if (Tok.endswith_lower("M")) {
1629 Suffix = 1024 * 1024;
1630 Tok = Tok.drop_back();
1631 }
1632 if (Tok.getAsInteger(10, Result))
1633 return false;
1634 Result *= Suffix;
1635 return true;
1636}
1637
George Rimare38cbab2016-09-26 19:22:50 +00001638BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1639 int Size = StringSwitch<unsigned>(Tok)
1640 .Case("BYTE", 1)
1641 .Case("SHORT", 2)
1642 .Case("LONG", 4)
1643 .Case("QUAD", 8)
1644 .Default(-1);
1645 if (Size == -1)
1646 return nullptr;
1647
1648 expect("(");
1649 uint64_t Val = 0;
1650 StringRef S = next();
1651 if (!readInteger(S, Val))
1652 setError("unexpected value: " + S);
1653 expect(")");
1654 return new BytesDataCommand(Val, Size);
1655}
1656
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001657StringRef ScriptParser::readParenLiteral() {
1658 expect("(");
1659 StringRef Tok = next();
1660 expect(")");
1661 return Tok;
1662}
1663
Rui Ueyama708019c2016-07-24 18:19:40 +00001664Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001665 if (peek() == "(")
1666 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001667
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001668 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001669
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001670 if (Tok == "~") {
1671 Expr E = readPrimary();
1672 return [=](uint64_t Dot) { return ~E(Dot); };
1673 }
1674 if (Tok == "-") {
1675 Expr E = readPrimary();
1676 return [=](uint64_t Dot) { return -E(Dot); };
1677 }
1678
Rui Ueyama708019c2016-07-24 18:19:40 +00001679 // Built-in functions are parsed here.
1680 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001681 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001682 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001683 return {
1684 [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; },
Rui Ueyama009d1742016-11-18 06:49:09 +00001685 [=] { return false; },
1686 [=] { return ScriptBase->getOutputSection(Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001687 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001688 if (Tok == "LOADADDR") {
1689 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001690 return [=](uint64_t Dot) {
1691 return ScriptBase->getOutputSection(Name)->getLMA();
1692 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001693 }
George Rimareefa7582016-08-04 09:29:31 +00001694 if (Tok == "ASSERT")
1695 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001696 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001697 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001698 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1699 }
1700 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001701 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001702 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001703 }
George Rimarf34f45f2016-09-23 13:17:23 +00001704 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001705 StringRef Name = readParenLiteral();
1706 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001707 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001708 if (Tok == "SEGMENT_START") {
1709 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001710 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001711 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001712 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001713 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001714 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001715 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001716 if (Tok == "DATA_SEGMENT_ALIGN") {
1717 expect("(");
1718 Expr E = readExpr();
1719 expect(",");
1720 readExpr();
1721 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001722 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001723 }
1724 if (Tok == "DATA_SEGMENT_END") {
1725 expect("(");
1726 expect(".");
1727 expect(")");
1728 return [](uint64_t Dot) { return Dot; };
1729 }
George Rimar276b4e62016-07-26 17:58:44 +00001730 // GNU linkers implements more complicated logic to handle
1731 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1732 // the next page boundary for simplicity.
1733 if (Tok == "DATA_SEGMENT_RELRO_END") {
1734 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001735 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001736 expect(",");
1737 readExpr();
1738 expect(")");
1739 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1740 }
George Rimar9e694502016-07-29 16:18:47 +00001741 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001742 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001743 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001744 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001745 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001746 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001747 return [=](uint64_t Dot) {
1748 return ScriptBase->getOutputSection(Name)->Addralign;
1749 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001750 }
George Rimare32a3592016-08-10 07:59:34 +00001751 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001752 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001753
George Rimar9f2f7ad2016-09-02 16:01:42 +00001754 // Tok is a literal number.
1755 uint64_t V;
1756 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001757 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001758
1759 // Tok is a symbol name.
1760 if (Tok != "." && !isValidCIdentifier(Tok))
1761 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001762 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Rui Ueyama009d1742016-11-18 06:49:09 +00001763 [=] { return isAbsolute(Tok); },
1764 [=] { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001765}
1766
1767Expr ScriptParser::readTernary(Expr Cond) {
Rui Ueyama708019c2016-07-24 18:19:40 +00001768 Expr L = readExpr();
1769 expect(":");
1770 Expr R = readExpr();
1771 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1772}
1773
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001774Expr ScriptParser::readParenExpr() {
1775 expect("(");
1776 Expr E = readExpr();
1777 expect(")");
1778 return E;
1779}
1780
Eugene Leviantbbe38602016-07-19 09:25:43 +00001781std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1782 std::vector<StringRef> Phdrs;
1783 while (!Error && peek().startswith(":")) {
1784 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001785 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001786 }
1787 return Phdrs;
1788}
1789
George Rimar95dd7182016-10-18 10:49:50 +00001790// Read a program header type name. The next token must be a
1791// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001792unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001793 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001794 uint64_t Val;
1795 if (readInteger(Tok, Val))
1796 return Val;
1797
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001798 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001799 .Case("PT_NULL", PT_NULL)
1800 .Case("PT_LOAD", PT_LOAD)
1801 .Case("PT_DYNAMIC", PT_DYNAMIC)
1802 .Case("PT_INTERP", PT_INTERP)
1803 .Case("PT_NOTE", PT_NOTE)
1804 .Case("PT_SHLIB", PT_SHLIB)
1805 .Case("PT_PHDR", PT_PHDR)
1806 .Case("PT_TLS", PT_TLS)
1807 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1808 .Case("PT_GNU_STACK", PT_GNU_STACK)
1809 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001810 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001811 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001812 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001813
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001814 if (Ret == (unsigned)-1) {
1815 setError("invalid program header type: " + Tok);
1816 return PT_NULL;
1817 }
1818 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001819}
1820
Rui Ueyama12450b22016-11-18 06:30:09 +00001821// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1822void ScriptParser::readAnonymousDeclaration() {
1823 // Read global symbols first. "global:" is default, so if there's
1824 // no label, we assume global symbols.
1825 if (consume("global:") || peek() != "local:")
1826 Config->VersionScriptGlobals = readSymbols();
1827
1828 // Next, read local symbols.
1829 if (consume("local:")) {
1830 if (consume("*")) {
1831 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1832 expect(";");
1833 } else {
1834 setError("local symbol list for anonymous version is not supported");
1835 }
1836 }
1837 expect("}");
1838 expect(";");
1839}
1840
1841// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001842void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001843 // Identifiers start at 2 because 0 and 1 are reserved
1844 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001845 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001846 Config->VersionDefinitions.push_back({VerStr, VersionId});
1847
Rui Ueyama12450b22016-11-18 06:30:09 +00001848 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001849 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001850 Config->VersionDefinitions.back().Globals = readSymbols();
1851
1852 // Read local symbols.
1853 if (consume("local:")) {
1854 if (consume("*")) {
1855 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1856 expect(";");
1857 } else {
1858 for (SymbolVersion V : readSymbols())
1859 Config->VersionScriptLocals.push_back(V);
1860 }
1861 }
George Rimar20b65982016-08-31 09:08:26 +00001862 expect("}");
1863
Rui Ueyama12450b22016-11-18 06:30:09 +00001864 // Each version may have a parent version. For example, "Ver2"
1865 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1866 // as a parent. This version hierarchy is, probably against your
1867 // instinct, purely for hint; the runtime doesn't care about it
1868 // at all. In LLD, we simply ignore it.
1869 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001870 skip();
George Rimar20b65982016-08-31 09:08:26 +00001871 expect(";");
1872}
1873
Rui Ueyama12450b22016-11-18 06:30:09 +00001874// Reads a list of symbols for a versions cript.
1875std::vector<SymbolVersion> ScriptParser::readSymbols() {
1876 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001877 for (;;) {
1878 if (consume("extern"))
Rui Ueyama12450b22016-11-18 06:30:09 +00001879 for (SymbolVersion V : readVersionExtern())
1880 Ret.push_back(V);
George Rimare0fc2422016-11-16 17:59:10 +00001881
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001882 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001883 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001884 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001885 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001886 expect(";");
1887 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001888 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001889}
1890
Rui Ueyama12450b22016-11-18 06:30:09 +00001891// Reads an "extern C++" directive, e.g.,
1892// "extern "C++" { ns::*; "f(int, double)"; };"
1893std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
George Rimarcd574a52016-09-09 14:35:36 +00001894 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001895 expect("{");
1896
Rui Ueyama12450b22016-11-18 06:30:09 +00001897 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001898 while (!Error && peek() != "}") {
1899 StringRef Tok = next();
1900 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rui Ueyama12450b22016-11-18 06:30:09 +00001901 Ret.push_back({unquote(Tok), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001902 expect(";");
1903 }
1904
1905 expect("}");
1906 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001907 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001908}
1909
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001910static bool isUnderSysroot(StringRef Path) {
1911 if (Config->Sysroot == "")
1912 return false;
1913 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1914 if (sys::fs::equivalent(Config->Sysroot, Path))
1915 return true;
1916 return false;
1917}
1918
Rui Ueyama07320e42016-04-20 20:13:41 +00001919void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001920 StringRef Path = MB.getBufferIdentifier();
Eugene Leviant03ff0162016-11-21 15:49:56 +00001921 ScriptParser(MB, isUnderSysroot(Path)).readLinkerScript();
George Rimar20b65982016-08-31 09:08:26 +00001922}
1923
1924void elf::readVersionScript(MemoryBufferRef MB) {
Eugene Leviant03ff0162016-11-21 15:49:56 +00001925 ScriptParser(MB, false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001926}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001927
Rui Ueyama07320e42016-04-20 20:13:41 +00001928template class elf::LinkerScript<ELF32LE>;
1929template class elf::LinkerScript<ELF32BE>;
1930template class elf::LinkerScript<ELF64LE>;
1931template class elf::LinkerScript<ELF64BE>;