blob: 2b7d246215f22e6a75ef858c7841b9ca1aba0f0c [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 Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000024#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000025#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000026#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000027#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000029#include "Symbols.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000030#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000031#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000032#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000033#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000034#include "llvm/ADT/StringRef.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000035#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000036#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000037#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include "llvm/Support/Endian.h"
39#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000040#include "llvm/Support/FileSystem.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000041#include "llvm/Support/MathExtras.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000042#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000043#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000044#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <iterator>
49#include <limits>
50#include <memory>
51#include <string>
52#include <tuple>
53#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000054
55using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000056using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000057using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000058using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000059using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000060using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000061
George Rimar884e7862016-09-08 08:19:13 +000062LinkerScriptBase *elf::ScriptBase;
Rui Ueyama07320e42016-04-20 20:13:41 +000063ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000064
George Rimar6c55f0e2016-09-08 08:20:30 +000065template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
Rafael Espindola3dabfc62016-10-31 13:14:53 +000066 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rui Ueyama1bdaf3e2016-11-09 23:37:40 +000067 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
George Rimar463984d2016-11-15 08:07:14 +000068 0, 0, STB_GLOBAL, nullptr, nullptr);
Rui Ueyama16024212016-08-11 23:22:52 +000069 Cmd->Sym = Sym->body();
Eugene Leviant20d03192016-09-16 15:30:47 +000070
71 // If we have no SECTIONS then we don't have '.' and don't call
72 // assignAddresses(). We calculate symbol value immediately in this case.
73 if (!ScriptConfig->HasSections)
74 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
Eugene Leviantceabe802016-08-11 07:56:43 +000075}
76
Rui Ueyama0c70d3c2016-08-12 03:31:09 +000077template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
Eugene Leviantafaa9342016-11-16 09:49:39 +000078 // If we have SECTIONS block then output sections haven't been created yet.
79 const OutputSectionBase *Sec =
80 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
George Rimare1937bb2016-08-19 15:36:32 +000081 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
Eugene Leviantafaa9342016-11-16 09:49:39 +000082 Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000083 Cmd->Sym = Sym->body();
Eugene Leviantafaa9342016-11-16 09:49:39 +000084
85 // If we already know section then we can calculate symbol value immediately.
86 if (Sec)
87 cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
88 Cmd->Expression(0) - Sec->Addr;
Eugene Leviantceabe802016-08-11 07:56:43 +000089}
90
Eugene Leviantdb741e72016-09-07 07:08:43 +000091template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000092 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000093 addRegular<ELFT>(Cmd);
94 else
95 addSynthetic<ELFT>(Cmd);
96}
Rui Ueyama16024212016-08-11 23:22:52 +000097// If a symbol was in PROVIDE(), we need to define it only when
98// it is an undefined symbol.
99template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
100 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +0000101 return false;
Rui Ueyama16024212016-08-11 23:22:52 +0000102 if (!Cmd->Provide)
103 return true;
104 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
105 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +0000106}
107
George Rimar076fe152016-07-21 06:43:01 +0000108bool SymbolAssignment::classof(const BaseCommand *C) {
109 return C->Kind == AssignmentKind;
110}
111
112bool OutputSectionCommand::classof(const BaseCommand *C) {
113 return C->Kind == OutputSectionKind;
114}
115
George Rimareea31142016-07-21 14:26:59 +0000116bool InputSectionDescription::classof(const BaseCommand *C) {
117 return C->Kind == InputSectionKind;
118}
119
George Rimareefa7582016-08-04 09:29:31 +0000120bool AssertCommand::classof(const BaseCommand *C) {
121 return C->Kind == AssertKind;
122}
123
George Rimare38cbab2016-09-26 19:22:50 +0000124bool BytesDataCommand::classof(const BaseCommand *C) {
125 return C->Kind == BytesDataKind;
126}
127
Eugene Zelenko22886a22016-11-05 01:00:56 +0000128template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
129template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000130
Rui Ueyama07320e42016-04-20 20:13:41 +0000131template <class ELFT>
132bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000133 for (InputSectionDescription *ID : Opt.KeptSections) {
134 StringRef Filename = S->getFile()->getName();
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000135 if (!ID->FilePat.match(sys::path::filename(Filename)))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000136 continue;
Rui Ueyamab66260a2016-10-05 20:09:50 +0000137
138 for (SectionPattern &P : ID->SectionPatterns)
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000139 if (P.SectionPat.match(S->Name))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000140 return true;
141 }
George Rimareea31142016-07-21 14:26:59 +0000142 return false;
143}
144
George Rimar575208c2016-09-15 19:15:12 +0000145static bool comparePriority(InputSectionData *A, InputSectionData *B) {
146 return getPriority(A->Name) < getPriority(B->Name);
147}
148
Rafael Espindolac0028d32016-09-08 20:47:52 +0000149static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000150 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000151}
George Rimar350ece42016-08-03 08:35:59 +0000152
Rafael Espindolac0028d32016-09-08 20:47:52 +0000153static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000154 // ">" is not a mistake. Larger alignments are placed before smaller
155 // alignments in order to reduce the amount of padding necessary.
156 // This is compatible with GNU.
157 return A->Alignment > B->Alignment;
158}
George Rimar350ece42016-08-03 08:35:59 +0000159
Rafael Espindolac0028d32016-09-08 20:47:52 +0000160static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000161getComparator(SortSectionPolicy K) {
162 switch (K) {
163 case SortSectionPolicy::Alignment:
164 return compareAlignment;
165 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000166 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000167 case SortSectionPolicy::Priority:
168 return comparePriority;
169 default:
170 llvm_unreachable("unknown sort policy");
171 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000172}
George Rimar0702c4e2016-07-29 15:32:46 +0000173
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000174template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000175static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000176 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000177 if (Kind == ConstraintKind::NoConstraint)
178 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000179 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000180 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000181 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000182 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000183 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
184 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000185}
186
George Rimar07171f22016-09-21 15:56:44 +0000187static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000188 SortSectionPolicy K) {
189 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000190 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000191}
192
Rafael Espindolad3190792016-09-16 15:10:23 +0000193// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000194template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000195void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000196 // Collects all sections that satisfy constraints of I
197 // and attach them to I.
198 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000199 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000200
201 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000202 if (!S->Live || S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000203 continue;
204
205 StringRef Filename;
206 if (elf::ObjectFile<ELFT> *F = S->getFile())
207 Filename = sys::path::filename(F->getName());
208
Rui Ueyamae8a61022016-11-05 23:05:47 +0000209 if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) &&
210 Pat.SectionPat.match(S->Name))
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000211 I->Sections.push_back(S);
George Rimar395281c2016-09-16 17:42:10 +0000212 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000213
George Rimar07171f22016-09-21 15:56:44 +0000214 // Sort sections as instructed by SORT-family commands and --sort-section
215 // option. Because SORT-family commands can be nested at most two depth
216 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
217 // line option is respected even if a SORT command is given, the exact
218 // behavior we have here is a bit complicated. Here are the rules.
219 //
220 // 1. If two SORT commands are given, --sort-section is ignored.
221 // 2. If one SORT command is given, and if it is not SORT_NONE,
222 // --sort-section is handled as an inner SORT command.
223 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
224 // 4. If no SORT command is given, sort according to --sort-section.
225 InputSectionData **Begin = I->Sections.data() + SizeBefore;
226 InputSectionData **End = I->Sections.data() + I->Sections.size();
227 if (Pat.SortOuter != SortSectionPolicy::None) {
228 if (Pat.SortInner == SortSectionPolicy::Default)
229 sortSections(Begin, End, Config->SortSection);
230 else
231 sortSections(Begin, End, Pat.SortInner);
232 sortSections(Begin, End, Pat.SortOuter);
233 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000234 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000235
236 // We do not add duplicate input sections, so mark them with a dummy output
237 // section for now.
238 for (InputSectionData *S : I->Sections) {
239 auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000240 S2->OutSec = (OutputSectionBase *)-1;
Rafael Espindolad3190792016-09-16 15:10:23 +0000241 }
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000242}
243
244template <class ELFT>
245void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
246 for (InputSectionBase<ELFT> *S : V) {
247 S->Live = false;
248 reportDiscarded(S);
249 }
250}
251
George Rimar06ae6832016-08-12 09:07:57 +0000252template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000253std::vector<InputSectionBase<ELFT> *>
George Rimar06ae6832016-08-12 09:07:57 +0000254LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000255 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000256
George Rimar06ae6832016-08-12 09:07:57 +0000257 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000258 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
259 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000260 continue;
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000261 computeInputSections(Cmd);
Rafael Espindolad3190792016-09-16 15:10:23 +0000262 for (InputSectionData *S : Cmd->Sections)
263 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000264 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000265
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000266 // After we created final list we should now set OutSec pointer to null,
George Rimara4c7e742016-10-20 08:36:42 +0000267 // instead of -1. Otherwise we may get a crash when writing relocs, in
Eugene Leviantcc1ba8c2016-10-12 12:31:34 +0000268 // case section is discarded by linker script
269 for (InputSectionBase<ELFT> *S : Ret)
270 S->OutSec = nullptr;
271
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000272 return Ret;
273}
274
Petr Hoseke5d3ca52016-08-31 15:31:17 +0000275template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +0000276static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
277 StringRef OutsecName) {
278 // When using linker script the merge rules are different.
279 // Unfortunately, linker scripts are name based. This means that expressions
280 // like *(.foo*) can refer to multiple input sections that would normally be
281 // placed in different output sections. We cannot put them in different
282 // output sections or we would produce wrong results for
283 // start = .; *(.foo.*) end = .; *(.bar)
284 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
285 // another. The problem is that there is no way to layout those output
286 // sections such that the .foo sections are the only thing between the
287 // start and end symbols.
288
289 // An extra annoyance is that we cannot simply disable merging of the contents
290 // of SHF_MERGE sections, but our implementation requires one output section
291 // per "kind" (string or not, which size/aligment).
292 // Fortunately, creating symbols in the middle of a merge section is not
293 // supported by bfd or gold, so we can just create multiple section in that
294 // case.
Rafael Espindola10897f12016-09-13 14:23:14 +0000295 typedef typename ELFT::uint uintX_t;
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000296 uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
Rafael Espindola10897f12016-09-13 14:23:14 +0000297
298 uintX_t Alignment = 0;
299 if (isa<MergeInputSection<ELFT>>(C))
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000300 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola10897f12016-09-13 14:23:14 +0000301
302 return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
303}
304
305template <class ELFT>
Eugene Leviant20d03192016-09-16 15:30:47 +0000306void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
307 InputSectionBase<ELFT> *Sec,
308 StringRef Name) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000309 OutputSectionBase *OutSec;
Eugene Leviant20d03192016-09-16 15:30:47 +0000310 bool IsNew;
311 std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
312 if (IsNew)
313 OutputSections->push_back(OutSec);
314 OutSec->addSection(Sec);
315}
316
317template <class ELFT>
318void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000319 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
320 auto Iter = Opt.Commands.begin() + I;
321 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000322 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
323 if (shouldDefine<ELFT>(Cmd))
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000324 addSymbol<ELFT>(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000325 continue;
326 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000327 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
328 // If we don't have SECTIONS then output sections have already been
George Rimar194470cd2016-09-17 19:21:05 +0000329 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
Eugene Leviant20d03192016-09-16 15:30:47 +0000330 // will not be called, so ASSERT should be evaluated now.
331 if (!Opt.HasSections)
332 Cmd->Expression(0);
333 continue;
334 }
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000335
Eugene Leviantceabe802016-08-11 07:56:43 +0000336 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000337 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
338
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000339 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000340 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000341 continue;
342 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000343
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000344 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
345 for (InputSectionBase<ELFT> *S : V)
346 S->OutSec = nullptr;
347 Opt.Commands.erase(Iter);
George Rimardfbbbc82016-09-17 09:50:10 +0000348 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000349 continue;
350 }
351
352 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
353 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
354 if (shouldDefine<ELFT>(OutCmd))
355 addSymbol<ELFT>(OutCmd);
356
Eugene Leviant97403d12016-09-01 09:55:57 +0000357 if (V.empty())
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000358 continue;
359
George Rimardb24d9c2016-08-19 15:18:23 +0000360 for (InputSectionBase<ELFT> *Sec : V) {
Eugene Leviant20d03192016-09-16 15:30:47 +0000361 addSection(Factory, Sec, Cmd->Name);
362 if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
George Rimardb24d9c2016-08-19 15:18:23 +0000363 Sec->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000364 }
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
Eugene Leviant20d03192016-09-16 15:30:47 +0000369template <class ELFT>
370void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
371 processCommands(Factory);
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000372
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000373 // Add orphan sections.
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000374 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000375 if (S->Live && !S->OutSec)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000376 addSection(Factory, S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000377}
378
Eugene Leviantdb741e72016-09-07 07:08:43 +0000379// Sets value of a section-defined symbol. Two kinds of
380// symbols are processed: synthetic symbols, whose value
381// is an offset from beginning of section and regular
382// symbols whose value is absolute.
383template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000384static void assignSectionSymbol(SymbolAssignment *Cmd,
Rafael Espindola498ed712016-10-31 14:44:41 +0000385 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000386 if (!Cmd->Sym)
387 return;
388
389 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000390 Body->Section = Cmd->Expression.Section();
391 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
Eugene Leviantdb741e72016-09-07 07:08:43 +0000392 return;
393 }
394 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000395 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000396}
397
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000398template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000399 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000400}
401
Rafael Espindolad3190792016-09-16 15:10:23 +0000402template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
403 if (!AlreadyOutputIS.insert(S).second)
404 return;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000405 bool IsTbss = isTbss<ELFT>(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000406
Rafael Espindolad3190792016-09-16 15:10:23 +0000407 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
408 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000409 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000410 Pos += S->getSize();
411
412 // Update output section size after adding each section. This is so that
413 // SIZEOF works correctly in the case below:
414 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000415 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000416
Rafael Espindola7252ae52016-09-22 12:00:08 +0000417 if (IsTbss)
418 ThreadBssOffset = Pos - Dot;
419 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000420 Dot = Pos;
421}
422
423template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000424 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
425 return;
426 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000427 for (InputSection<ELFT> *I : OutSec->Sections)
428 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000429 } else {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000430 Dot += CurOutSec->Size;
Eugene Leviant20889c52016-08-31 08:13:33 +0000431 }
432}
433
434template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000435void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000436 if (CurOutSec == Sec)
437 return;
438 if (AlreadyOutputOS.count(Sec))
439 return;
440
441 flush();
442 CurOutSec = Sec;
443
Rafael Espindola04a2e342016-11-09 01:42:41 +0000444 Dot = alignTo(Dot, CurOutSec->Addralign);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000445 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000446
447 // If neither AT nor AT> is specified for an allocatable section, the linker
448 // will set the LMA such that the difference between VMA and LMA for the
449 // section is the same as the preceding output section in the same region
450 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
451 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000452}
453
454template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000455 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000456 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
457 if (AssignCmd->Name == ".") {
458 // Update to location counter means update to section size.
459 Dot = AssignCmd->Expression(Dot);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000460 CurOutSec->Size = Dot - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000461 return;
462 }
Eugene Leviantafaa9342016-11-16 09:49:39 +0000463 assignSectionSymbol<ELFT>(AssignCmd, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000464 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000465 }
George Rimare38cbab2016-09-26 19:22:50 +0000466
467 // Handle BYTE(), SHORT(), LONG(), or QUAD().
468 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000469 DataCmd->Offset = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000470 Dot += DataCmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000471 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000472 return;
473 }
474
475 // It handles single input section description command,
476 // calculates and assigns the offsets for each section and also
477 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000478 auto &ICmd = cast<InputSectionDescription>(Base);
479 for (InputSectionData *ID : ICmd.Sections) {
480 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
481 switchTo(IB->OutSec);
482 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
483 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000484 else
485 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000486 }
487}
488
George Rimar8f66df92016-08-12 20:38:20 +0000489template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000490static std::vector<OutputSectionBase *>
491findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
492 std::vector<OutputSectionBase *> Ret;
493 for (OutputSectionBase *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000494 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000495 Ret.push_back(Sec);
496 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000497}
498
Rafael Espindolad3190792016-09-16 15:10:23 +0000499template <class ELFT>
500void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000501 if (Cmd->LMAExpr)
502 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000503 std::vector<OutputSectionBase *> Sections =
504 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000505 if (Sections.empty())
506 return;
507 switchTo(Sections[0]);
Rafael Espindolad3190792016-09-16 15:10:23 +0000508 // Find the last section output location. We will output orphan sections
509 // there so that end symbols point to the correct location.
510 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
511 [](const std::unique_ptr<BaseCommand> &Cmd) {
512 return !isa<SymbolAssignment>(*Cmd);
513 })
514 .base();
515 for (auto I = Cmd->Commands.begin(); I != E; ++I)
516 process(**I);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000517 for (OutputSectionBase *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000518 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000519 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000520 std::for_each(E, Cmd->Commands.end(),
521 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000522}
523
Rafael Espindola07fe6122016-11-14 14:23:35 +0000524template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000525 // It is common practice to use very generic linker scripts. So for any
526 // given run some of the output sections in the script will be empty.
527 // We could create corresponding empty output sections, but that would
528 // clutter the output.
529 // We instead remove trivially empty sections. The bfd linker seems even
530 // more aggressive at removing them.
531 auto Pos = std::remove_if(
532 Opt.Commands.begin(), Opt.Commands.end(),
533 [&](const std::unique_ptr<BaseCommand> &Base) {
534 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
535 if (!Cmd)
536 return false;
Rafael Espindola6a537372016-11-14 14:33:49 +0000537 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000538 });
539 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000540}
541
Rafael Espindola6a537372016-11-14 14:33:49 +0000542static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
543 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
544 if (!isa<InputSectionDescription>(*I))
545 return false;
546 return true;
547}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000548
Rafael Espindola6a537372016-11-14 14:33:49 +0000549template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000550 // If the output section contains only symbol assignments, create a
551 // corresponding output section. The bfd linker seems to only create them if
552 // '.' is assigned to, but creating these section should not have any bad
553 // consequeces and gives us a section to put the symbol in.
554 uintX_t Flags = SHF_ALLOC;
555 uint32_t Type = 0;
556 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
557 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
558 if (!Cmd)
559 continue;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000560 std::vector<OutputSectionBase *> Secs =
561 findSections<ELFT>(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000562 if (!Secs.empty()) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000563 Flags = Secs[0]->Flags;
564 Type = Secs[0]->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000565 continue;
566 }
567
Rafael Espindola6a537372016-11-14 14:33:49 +0000568 if (isAllSectionDescription(*Cmd))
569 continue;
570
Rui Ueyama95642b92016-11-01 23:09:07 +0000571 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000572 OutputSections->push_back(OutSec);
573 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000574}
575
576template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
577 placeOrphanSections();
578
579 // If output section command doesn't specify any segments,
580 // and we haven't previously assigned any section to segment,
581 // then we simply assign section to the very first load segment.
582 // Below is an example of such linker script:
583 // PHDRS { seg PT_LOAD; }
584 // SECTIONS { .aaa : { *(.aaa) } }
585 std::vector<StringRef> DefPhdrs;
586 auto FirstPtLoad =
587 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
588 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
589 if (FirstPtLoad != Opt.PhdrsCommands.end())
590 DefPhdrs.push_back(FirstPtLoad->Name);
591
592 // Walk the commands and propagate the program headers to commands that don't
593 // explicitly specify them.
594 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
595 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
596 if (!Cmd)
597 continue;
598 if (Cmd->Phdrs.empty())
599 Cmd->Phdrs = DefPhdrs;
600 else
601 DefPhdrs = Cmd->Phdrs;
602 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000603
604 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000605}
606
Rafael Espindola15c57952016-09-22 18:05:49 +0000607// When placing orphan sections, we want to place them after symbol assignments
608// so that an orphan after
609// begin_foo = .;
610// foo : { *(foo) }
611// end_foo = .;
612// doesn't break the intended meaning of the begin/end symbols.
613// We don't want to go over sections since Writer<ELFT>::sortSections is the
614// one in charge of deciding the order of the sections.
615// We don't want to go over alignments, since doing so in
616// rx_sec : { *(rx_sec) }
617// . = ALIGN(0x1000);
618// /* The RW PT_LOAD starts here*/
619// rw_sec : { *(rw_sec) }
620// would mean that the RW PT_LOAD would become unaligned.
621static bool shouldSkip(const BaseCommand &Cmd) {
622 if (isa<OutputSectionCommand>(Cmd))
623 return false;
624 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
625 if (!Assign)
626 return true;
627 return Assign->Name != ".";
628}
629
Rafael Espindola337f9032016-11-14 14:13:32 +0000630// Orphan sections are sections present in the input files which are not
631// explicitly placed into the output file by the linker script. This just
632// places them in the order already decided in OutputSections.
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000633template <class ELFT>
Rafael Espindola337f9032016-11-14 14:13:32 +0000634void LinkerScript<ELFT>::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000635 // The OutputSections are already in the correct order.
636 // This loops creates or moves commands as needed so that they are in the
637 // correct order.
638 int CmdIndex = 0;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000639 for (OutputSectionBase *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000640 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000641
642 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000643 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000644 auto CmdIter = Opt.Commands.begin() + CmdIndex;
645 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000646 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000647 ++CmdIter;
648 ++CmdIndex;
649 }
650
651 auto Pos =
652 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
653 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
654 return Cmd && Cmd->Name == Name;
655 });
656 if (Pos == E) {
657 Opt.Commands.insert(CmdIter,
658 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000659 ++CmdIndex;
660 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000661 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000662
663 // Continue from where we found it.
664 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000665 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000666}
667
668template <class ELFT>
669void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000670 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000671 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000672
George Rimar076fe152016-07-21 06:43:01 +0000673 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
674 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000675 if (Cmd->Name == ".") {
676 Dot = Cmd->Expression(Dot);
677 } else if (Cmd->Sym) {
Eugene Leviantafaa9342016-11-16 09:49:39 +0000678 assignSectionSymbol<ELFT>(Cmd, Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000679 }
George Rimar652852c2016-04-16 10:10:32 +0000680 continue;
681 }
682
George Rimareefa7582016-08-04 09:29:31 +0000683 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
684 Cmd->Expression(Dot);
685 continue;
686 }
687
George Rimar076fe152016-07-21 06:43:01 +0000688 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000689
Rafael Espindolad3190792016-09-16 15:10:23 +0000690 if (Cmd->AddrExpr)
691 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000692
Rafael Espindolad3190792016-09-16 15:10:23 +0000693 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000694 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000695
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000696 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000697 for (OutputSectionBase *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000698 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000699 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000700 else
Rafael Espindola04a2e342016-11-09 01:42:41 +0000701 Sec->Addr = 0;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000702 }
703
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000704 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000705 auto FirstPTLoad =
706 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
707 return E.H.p_type == PT_LOAD;
708 });
Rafael Espindolad8b81d62016-11-17 14:18:08 +0000709 if (FirstPTLoad == Phdrs.end())
710 return;
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000711
Rafael Espindolad8b81d62016-11-17 14:18:08 +0000712 if (HeaderSize <= MinVA) {
George Rimar59d9b4b2016-11-14 10:04:45 +0000713 // If linker script specifies program headers and first PT_LOAD doesn't
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000714 // have both PHDRS and FILEHDR attributes then do nothing
715 if (!Opt.PhdrsCommands.empty()) {
716 size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
717 if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
718 !Opt.PhdrsCommands[SegNum].HasFilehdr)
719 return;
720 }
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000721 // ELF and Program headers need to be right before the first section in
722 // memory. Set their addresses accordingly.
723 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000724 Out<ELFT>::ElfHeader->Addr = MinVA;
725 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000726 FirstPTLoad->First = Out<ELFT>::ElfHeader;
727 if (!FirstPTLoad->Last)
728 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000729 } else 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 Ueyama07320e42016-04-20 20:13:41 +0000790ArrayRef<uint8_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;
795 return {};
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
826 OutputSectionCommand *Cmd =
827 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
828 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
829 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
830 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
831}
832
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000833template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000834 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
835 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000836 if (Cmd->LMAExpr && Cmd->Name == Name)
837 return true;
838 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000839}
840
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000841// Returns the index of the given section name in linker script
842// SECTIONS commands. Sections are laid out as the same order as they
843// were in the script. If a given name did not appear in the script,
844// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000845template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000846 int I = 0;
847 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
848 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
849 if (Cmd->Name == Name)
850 return I;
851 ++I;
852 }
853 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000854}
855
Eugene Leviantbbe38602016-07-19 09:25:43 +0000856template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
857 return !Opt.PhdrsCommands.empty();
858}
859
George Rimar9e694502016-07-29 16:18:47 +0000860template <class ELFT>
Eugene Leviantafaa9342016-11-16 09:49:39 +0000861const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(StringRef Name) {
862 static OutputSectionBase FakeSec("", 0, 0);
George Rimar96659df2016-08-30 09:54:01 +0000863
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000864 for (OutputSectionBase *Sec : *OutputSections)
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000865 if (Sec->getName() == Name)
Eugene Leviantafaa9342016-11-16 09:49:39 +0000866 return Sec;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000867 error("undefined section " + Name);
Eugene Leviantafaa9342016-11-16 09:49:39 +0000868 return &FakeSec;
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000869}
870
George Rimar884e7862016-09-08 08:19:13 +0000871template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000872 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000873}
874
George Rimar884e7862016-09-08 08:19:13 +0000875template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
876 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
877 return B->getVA<ELFT>();
878 error("symbol not found: " + S);
879 return 0;
880}
881
George Rimarf34f45f2016-09-23 13:17:23 +0000882template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
883 return Symtab<ELFT>::X->find(S) != nullptr;
884}
885
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000886template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
887 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
888 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
889 return DR && !DR->Section;
890}
891
Eugene Leviantafaa9342016-11-16 09:49:39 +0000892// Gets section symbol belongs to. Symbol "." doesn't belong to any
893// specific section but isn't absolute at the same time, so we try
894// to find suitable section for it as well.
895template <class ELFT>
896const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
897 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
898 if (!Sym) {
899 if (OutputSections->empty())
900 return nullptr;
901 return CurOutSec ? CurOutSec : (*OutputSections)[0];
902 }
903
904 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
905 return DR->Section ? DR->Section->OutSec : nullptr;
906 if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
907 return DS->Section;
908
909 return nullptr;
910}
911
Eugene Leviantbbe38602016-07-19 09:25:43 +0000912// Returns indices of ELF headers containing specific section, identified
913// by Name. Each index is a zero based number of ELF header listed within
914// PHDRS {} script block.
915template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000916std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000917 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
918 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000919 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000920 continue;
921
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000922 std::vector<size_t> Ret;
923 for (StringRef PhdrName : Cmd->Phdrs)
924 Ret.push_back(getPhdrIndex(PhdrName));
925 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000926 }
George Rimar31d842f2016-07-20 16:43:03 +0000927 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000928}
929
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000930template <class ELFT>
931size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
932 size_t I = 0;
933 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
934 if (Cmd.Name == PhdrName)
935 return I;
936 ++I;
937 }
938 error("section header '" + PhdrName + "' is not listed in PHDRS");
939 return 0;
940}
941
Rui Ueyama07320e42016-04-20 20:13:41 +0000942class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000943 typedef void (ScriptParser::*Handler)();
944
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000945public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000946 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000947
George Rimar20b65982016-08-31 09:08:26 +0000948 void readLinkerScript();
949 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000950
951private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000952 void addFile(StringRef Path);
953
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000954 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000955 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000956 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000957 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000958 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000959 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000960 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000961 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000962 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000963 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000964 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000965 void readVersion();
966 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000967
Rui Ueyama113cdec2016-07-24 23:05:57 +0000968 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000969 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000970 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000971 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000972 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000973 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000974 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000975 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000976 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000977 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000978 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000979 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000980 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000981 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000982 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000983 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000984
985 Expr readExpr();
986 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000987 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000988 Expr readPrimary();
989 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000990 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000991
George Rimar20b65982016-08-31 09:08:26 +0000992 // For parsing version script.
Rui Ueyama2a00b842016-11-15 17:51:07 +0000993 void readVersionExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000994 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000995 void readGlobal(StringRef VerStr);
George Rimarbb6c01e2016-11-12 07:04:15 +0000996 void readLocal(StringRef VerStr);
George Rimare0fc2422016-11-16 17:59:10 +0000997 void readSymbols(std::vector<SymbolVersion> &V);
George Rimar20b65982016-08-31 09:08:26 +0000998
Rui Ueyama07320e42016-04-20 20:13:41 +0000999 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001000 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001001};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001002
George Rimar20b65982016-08-31 09:08:26 +00001003void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001004 readVersionScriptCommand();
1005 if (!atEOF())
1006 setError("EOF expected, but got " + next());
1007}
1008
1009void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001010 if (consume("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +00001011 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +00001012 return;
1013 }
1014
Rui Ueyama95769b42016-08-31 20:03:54 +00001015 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001016 StringRef VerStr = next();
1017 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001018 setError("anonymous version definition is used in "
1019 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001020 return;
1021 }
1022 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001023 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001024 }
1025}
1026
Rui Ueyama95769b42016-08-31 20:03:54 +00001027void ScriptParser::readVersion() {
1028 expect("{");
1029 readVersionScriptCommand();
1030 expect("}");
1031}
1032
George Rimar20b65982016-08-31 09:08:26 +00001033void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001034 while (!atEOF()) {
1035 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001036 if (Tok == ";")
1037 continue;
1038
Eugene Leviant20d03192016-09-16 15:30:47 +00001039 if (Tok == "ASSERT") {
1040 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1041 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001042 readEntry();
1043 } else if (Tok == "EXTERN") {
1044 readExtern();
1045 } else if (Tok == "GROUP" || Tok == "INPUT") {
1046 readGroup();
1047 } else if (Tok == "INCLUDE") {
1048 readInclude();
1049 } else if (Tok == "OUTPUT") {
1050 readOutput();
1051 } else if (Tok == "OUTPUT_ARCH") {
1052 readOutputArch();
1053 } else if (Tok == "OUTPUT_FORMAT") {
1054 readOutputFormat();
1055 } else if (Tok == "PHDRS") {
1056 readPhdrs();
1057 } else if (Tok == "SEARCH_DIR") {
1058 readSearchDir();
1059 } else if (Tok == "SECTIONS") {
1060 readSections();
1061 } else if (Tok == "VERSION") {
1062 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001063 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001064 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001065 } else {
George Rimar57610422016-03-11 14:43:02 +00001066 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001067 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001068 }
1069}
1070
Rui Ueyama717677a2016-02-11 21:17:59 +00001071void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001072 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001073 SmallString<128> PathData;
1074 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001075 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001076 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001077 return;
1078 }
1079 }
1080
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001081 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001082 Driver->addFile(S);
1083 } else if (S.startswith("=")) {
1084 if (Config->Sysroot.empty())
1085 Driver->addFile(S.substr(1));
1086 else
1087 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1088 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001089 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001090 } else if (sys::fs::exists(S)) {
1091 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001092 } else {
1093 std::string Path = findFromSearchPaths(S);
1094 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001095 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001096 else
1097 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001098 }
1099}
1100
Rui Ueyama717677a2016-02-11 21:17:59 +00001101void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001102 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001103 bool Orig = Config->AsNeeded;
1104 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001105 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001106 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001107 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001108}
1109
Rui Ueyama717677a2016-02-11 21:17:59 +00001110void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001111 // -e <symbol> takes predecence over ENTRY(<symbol>).
1112 expect("(");
1113 StringRef Tok = next();
1114 if (Config->Entry.empty())
1115 Config->Entry = Tok;
1116 expect(")");
1117}
1118
Rui Ueyama717677a2016-02-11 21:17:59 +00001119void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001120 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001121 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001122 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001123}
1124
Rui Ueyama717677a2016-02-11 21:17:59 +00001125void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001126 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001127 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001128 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001129 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001130 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001131 else
George Rimarcd574a52016-09-09 14:35:36 +00001132 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001133 }
1134}
1135
Rui Ueyama717677a2016-02-11 21:17:59 +00001136void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001137 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001138 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001139 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001140 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001141 return;
1142 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001143 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001144 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1145 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001146 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001147}
1148
Rui Ueyama717677a2016-02-11 21:17:59 +00001149void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001150 // -o <file> takes predecence over OUTPUT(<file>).
1151 expect("(");
1152 StringRef Tok = next();
1153 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001154 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001155 expect(")");
1156}
1157
Rui Ueyama717677a2016-02-11 21:17:59 +00001158void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001159 // Error checking only for now.
1160 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001161 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001162 expect(")");
1163}
1164
Rui Ueyama717677a2016-02-11 21:17:59 +00001165void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001166 // Error checking only for now.
1167 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001168 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001169 StringRef Tok = next();
1170 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001171 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001172 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001173 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001174 return;
1175 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001176 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001177 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001178 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001179 expect(")");
1180}
1181
Eugene Leviantbbe38602016-07-19 09:25:43 +00001182void ScriptParser::readPhdrs() {
1183 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001184 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001185 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001186 Opt.PhdrsCommands.push_back(
1187 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001188 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1189
1190 PhdrCmd.Type = readPhdrType();
1191 do {
1192 Tok = next();
1193 if (Tok == ";")
1194 break;
1195 if (Tok == "FILEHDR")
1196 PhdrCmd.HasFilehdr = true;
1197 else if (Tok == "PHDRS")
1198 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001199 else if (Tok == "AT")
1200 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001201 else if (Tok == "FLAGS") {
1202 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001203 // Passing 0 for the value of dot is a bit of a hack. It means that
1204 // we accept expressions like ".|1".
1205 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001206 expect(")");
1207 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001208 setError("unexpected header attribute: " + Tok);
1209 } while (!Error);
1210 }
1211}
1212
Rui Ueyama717677a2016-02-11 21:17:59 +00001213void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001214 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001215 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001216 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001217 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001218 expect(")");
1219}
1220
Rui Ueyama717677a2016-02-11 21:17:59 +00001221void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001222 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001223 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001224 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001225 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001226 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001227 if (!Cmd) {
1228 if (Tok == "ASSERT")
1229 Cmd = new AssertCommand(readAssert());
1230 else
1231 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001232 }
Rui Ueyama10416562016-08-04 02:03:27 +00001233 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001234 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001235}
1236
Rui Ueyama708019c2016-07-24 18:19:40 +00001237static int precedence(StringRef Op) {
1238 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001239 .Cases("*", "/", 5)
1240 .Cases("+", "-", 4)
1241 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001242 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001243 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001244 .Default(-1);
1245}
1246
Eugene Leviantdb688452016-11-03 10:54:58 +00001247StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001248 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001249 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001250 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001251 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001252}
1253
George Rimarbe394db2016-09-16 20:21:55 +00001254SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001255 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001256 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001257 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001258 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001259 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001260 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001261 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001262 return SortSectionPolicy::None;
1263 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001264}
1265
George Rimar395281c2016-09-16 17:42:10 +00001266// Method reads a list of sequence of excluded files and section globs given in
1267// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1268// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001269// The semantics of that is next:
1270// * Include .foo.1 from every file.
1271// * Include .foo.2 from every file but a.o
1272// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001273std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1274 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001275 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001276 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001277 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001278 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001279 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001280 }
1281
George Rimar601e9892016-09-21 08:53:21 +00001282 std::vector<StringRef> V;
1283 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1284 V.push_back(next());
1285
1286 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001287 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001288 else
1289 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001290 }
George Rimar07171f22016-09-21 15:56:44 +00001291 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001292}
1293
George Rimar07171f22016-09-21 15:56:44 +00001294// Section pattern grammar can have complex expressions, for example:
1295// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1296// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1297// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1298// This methods handles wrapping sequences of excluded files and section globs
1299// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001300InputSectionDescription *
1301ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001302 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001303 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001304 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001305 SortSectionPolicy Outer = readSortKind();
1306 SortSectionPolicy Inner = SortSectionPolicy::Default;
1307 std::vector<SectionPattern> V;
1308 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001309 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001310 Inner = readSortKind();
1311 if (Inner != SortSectionPolicy::Default) {
1312 expect("(");
1313 V = readInputSectionsList();
1314 expect(")");
1315 } else {
1316 V = readInputSectionsList();
1317 }
George Rimar350ece42016-08-03 08:35:59 +00001318 expect(")");
1319 } else {
George Rimar07171f22016-09-21 15:56:44 +00001320 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001321 }
George Rimar0702c4e2016-07-29 15:32:46 +00001322
George Rimar07171f22016-09-21 15:56:44 +00001323 for (SectionPattern &Pat : V) {
1324 Pat.SortInner = Inner;
1325 Pat.SortOuter = Outer;
1326 }
1327
1328 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1329 }
Rui Ueyama10416562016-08-04 02:03:27 +00001330 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001331}
1332
George Rimara2496cb2016-08-30 09:46:59 +00001333InputSectionDescription *
1334ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001335 // Input section wildcard can be surrounded by KEEP.
1336 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001337 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001338 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001339 StringRef FilePattern = next();
1340 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001341 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001342 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001343 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001344 }
George Rimara2496cb2016-08-30 09:46:59 +00001345 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001346}
1347
George Rimar03fc0102016-07-28 07:18:23 +00001348void ScriptParser::readSort() {
1349 expect("(");
1350 expect("CONSTRUCTORS");
1351 expect(")");
1352}
1353
George Rimareefa7582016-08-04 09:29:31 +00001354Expr ScriptParser::readAssert() {
1355 expect("(");
1356 Expr E = readExpr();
1357 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001358 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001359 expect(")");
1360 return [=](uint64_t Dot) {
1361 uint64_t V = E(Dot);
1362 if (!V)
1363 error(Msg);
1364 return V;
1365 };
1366}
1367
Rui Ueyama25150e82016-09-06 17:46:43 +00001368// Reads a FILL(expr) command. We handle the FILL command as an
1369// alias for =fillexp section attribute, which is different from
1370// what GNU linkers do.
1371// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001372std::vector<uint8_t> ScriptParser::readFill() {
1373 expect("(");
1374 std::vector<uint8_t> V = readOutputSectionFiller(next());
1375 expect(")");
1376 expect(";");
1377 return V;
1378}
1379
Rui Ueyama10416562016-08-04 02:03:27 +00001380OutputSectionCommand *
1381ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001382 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001383
1384 // Read an address expression.
1385 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1386 if (peek() != ":")
1387 Cmd->AddrExpr = readExpr();
1388
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001389 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001390
Rui Ueyama83043f22016-10-17 16:01:53 +00001391 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001392 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001393 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001394 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001395 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001396 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001397
Davide Italiano246f6812016-07-22 03:36:24 +00001398 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001399 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001400 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001401 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001402 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001403 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001404
Rui Ueyama83043f22016-10-17 16:01:53 +00001405 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001406 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001407 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001408 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001409 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1410 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001411 else if (Tok == "FILL")
1412 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001413 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001414 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001415 else if (peek() == "(")
1416 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001417 else
1418 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001419 }
George Rimar076fe152016-07-21 06:43:01 +00001420 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001421
Rui Ueyama83043f22016-10-17 16:01:53 +00001422 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001423 Cmd->Filler = readOutputSectionFiller(next());
1424 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001425 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001426
Rui Ueyama10416562016-08-04 02:03:27 +00001427 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001428}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001429
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001430// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1431// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1432//
1433// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1434// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1435// as 32-bit big-endian values. We will do the same as ld.gold does
1436// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001437std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001438 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001439 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001440 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001441 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001442 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001443 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001444}
1445
Petr Hoseka35e39c2016-08-16 01:11:16 +00001446SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001447 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001448 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001449 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001450 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001451 expect(")");
1452 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001453 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001454}
1455
Rafael Espindolac96da112016-11-01 11:30:45 +00001456SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001457 SymbolAssignment *Cmd = nullptr;
1458 if (peek() == "=" || peek() == "+=") {
1459 Cmd = readAssignment(Tok);
1460 expect(";");
1461 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001462 Cmd = readProvideHidden(true, false);
1463 } else if (Tok == "HIDDEN") {
1464 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001465 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001466 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001467 }
1468 return Cmd;
1469}
1470
George Rimar30835ea2016-07-28 21:08:56 +00001471static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1472 if (S == ".")
1473 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001474 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001475}
1476
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001477static bool isAbsolute(StringRef S) {
1478 if (S == ".")
1479 return false;
1480 return ScriptBase->isAbsolute(S);
1481}
1482
George Rimar30835ea2016-07-28 21:08:56 +00001483SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1484 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001485 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001486 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001487 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001488 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1489 // Call readExpr1 to read the whole expression.
1490 E = readExpr1(readParenExpr(), 0);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001491 E.IsAbsolute = []() { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001492 } else {
1493 E = readExpr();
1494 }
George Rimar30835ea2016-07-28 21:08:56 +00001495 if (Op == "+=")
1496 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001497 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001498}
1499
1500// This is an operator-precedence parser to parse a linker
1501// script expression.
1502Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1503
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001504static Expr combine(StringRef Op, Expr L, Expr R) {
1505 if (Op == "*")
1506 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1507 if (Op == "/") {
1508 return [=](uint64_t Dot) -> uint64_t {
1509 uint64_t RHS = R(Dot);
1510 if (RHS == 0) {
1511 error("division by zero");
1512 return 0;
1513 }
1514 return L(Dot) / RHS;
1515 };
1516 }
1517 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001518 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Eugene Leviantafaa9342016-11-16 09:49:39 +00001519 [=]() { return L.IsAbsolute() && R.IsAbsolute(); },
1520 [=]() {
1521 const OutputSectionBase *S = L.Section();
1522 return S ? S : R.Section();
1523 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001524 if (Op == "-")
1525 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001526 if (Op == "<<")
1527 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1528 if (Op == ">>")
1529 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001530 if (Op == "<")
1531 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1532 if (Op == ">")
1533 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1534 if (Op == ">=")
1535 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1536 if (Op == "<=")
1537 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1538 if (Op == "==")
1539 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1540 if (Op == "!=")
1541 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1542 if (Op == "&")
1543 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001544 if (Op == "|")
1545 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001546 llvm_unreachable("invalid operator");
1547}
1548
Rui Ueyama708019c2016-07-24 18:19:40 +00001549// This is a part of the operator-precedence parser. This function
1550// assumes that the remaining token stream starts with an operator.
1551Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1552 while (!atEOF() && !Error) {
1553 // Read an operator and an expression.
1554 StringRef Op1 = peek();
1555 if (Op1 == "?")
1556 return readTernary(Lhs);
1557 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001558 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001559 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001560 Expr Rhs = readPrimary();
1561
1562 // Evaluate the remaining part of the expression first if the
1563 // next operator has greater precedence than the previous one.
1564 // For example, if we have read "+" and "3", and if the next
1565 // operator is "*", then we'll evaluate 3 * ... part first.
1566 while (!atEOF()) {
1567 StringRef Op2 = peek();
1568 if (precedence(Op2) <= precedence(Op1))
1569 break;
1570 Rhs = readExpr1(Rhs, precedence(Op2));
1571 }
1572
1573 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001574 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001575 return Lhs;
1576}
1577
1578uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001579 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001580 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001581 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001582 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001583 error("unknown constant: " + S);
1584 return 0;
1585}
1586
Rui Ueyama626e0b02016-09-02 18:19:00 +00001587// Parses Tok as an integer. Returns true if successful.
1588// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1589// and decimal numbers. Decimal numbers may have "K" (kilo) or
1590// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001591static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001592 if (Tok.startswith("-")) {
1593 if (!readInteger(Tok.substr(1), Result))
1594 return false;
1595 Result = -Result;
1596 return true;
1597 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001598 if (Tok.startswith_lower("0x"))
1599 return !Tok.substr(2).getAsInteger(16, Result);
1600 if (Tok.endswith_lower("H"))
1601 return !Tok.drop_back().getAsInteger(16, Result);
1602
1603 int Suffix = 1;
1604 if (Tok.endswith_lower("K")) {
1605 Suffix = 1024;
1606 Tok = Tok.drop_back();
1607 } else if (Tok.endswith_lower("M")) {
1608 Suffix = 1024 * 1024;
1609 Tok = Tok.drop_back();
1610 }
1611 if (Tok.getAsInteger(10, Result))
1612 return false;
1613 Result *= Suffix;
1614 return true;
1615}
1616
George Rimare38cbab2016-09-26 19:22:50 +00001617BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1618 int Size = StringSwitch<unsigned>(Tok)
1619 .Case("BYTE", 1)
1620 .Case("SHORT", 2)
1621 .Case("LONG", 4)
1622 .Case("QUAD", 8)
1623 .Default(-1);
1624 if (Size == -1)
1625 return nullptr;
1626
1627 expect("(");
1628 uint64_t Val = 0;
1629 StringRef S = next();
1630 if (!readInteger(S, Val))
1631 setError("unexpected value: " + S);
1632 expect(")");
1633 return new BytesDataCommand(Val, Size);
1634}
1635
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001636StringRef ScriptParser::readParenLiteral() {
1637 expect("(");
1638 StringRef Tok = next();
1639 expect(")");
1640 return Tok;
1641}
1642
Rui Ueyama708019c2016-07-24 18:19:40 +00001643Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001644 if (peek() == "(")
1645 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001646
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001647 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001648
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001649 if (Tok == "~") {
1650 Expr E = readPrimary();
1651 return [=](uint64_t Dot) { return ~E(Dot); };
1652 }
1653 if (Tok == "-") {
1654 Expr E = readPrimary();
1655 return [=](uint64_t Dot) { return -E(Dot); };
1656 }
1657
Rui Ueyama708019c2016-07-24 18:19:40 +00001658 // Built-in functions are parsed here.
1659 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001660 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001661 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001662 return {
1663 [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; },
1664 [=]() { return false; },
1665 [=]() { return ScriptBase->getOutputSection(Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001666 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001667 if (Tok == "LOADADDR") {
1668 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001669 return [=](uint64_t Dot) {
1670 return ScriptBase->getOutputSection(Name)->getLMA();
1671 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001672 }
George Rimareefa7582016-08-04 09:29:31 +00001673 if (Tok == "ASSERT")
1674 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001675 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001676 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001677 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1678 }
1679 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001680 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001681 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001682 }
George Rimarf34f45f2016-09-23 13:17:23 +00001683 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001684 StringRef Name = readParenLiteral();
1685 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001686 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001687 if (Tok == "SEGMENT_START") {
1688 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001689 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001690 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001691 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001692 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001693 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001694 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001695 if (Tok == "DATA_SEGMENT_ALIGN") {
1696 expect("(");
1697 Expr E = readExpr();
1698 expect(",");
1699 readExpr();
1700 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001701 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001702 }
1703 if (Tok == "DATA_SEGMENT_END") {
1704 expect("(");
1705 expect(".");
1706 expect(")");
1707 return [](uint64_t Dot) { return Dot; };
1708 }
George Rimar276b4e62016-07-26 17:58:44 +00001709 // GNU linkers implements more complicated logic to handle
1710 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1711 // the next page boundary for simplicity.
1712 if (Tok == "DATA_SEGMENT_RELRO_END") {
1713 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001714 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001715 expect(",");
1716 readExpr();
1717 expect(")");
1718 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1719 }
George Rimar9e694502016-07-29 16:18:47 +00001720 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001721 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001722 return
1723 [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Size; };
George Rimar9e694502016-07-29 16:18:47 +00001724 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001725 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001726 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001727 return [=](uint64_t Dot) {
1728 return ScriptBase->getOutputSection(Name)->Addralign;
1729 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001730 }
George Rimare32a3592016-08-10 07:59:34 +00001731 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001732 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001733
George Rimar9f2f7ad2016-09-02 16:01:42 +00001734 // Tok is a literal number.
1735 uint64_t V;
1736 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001737 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001738
1739 // Tok is a symbol name.
1740 if (Tok != "." && !isValidCIdentifier(Tok))
1741 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001742 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Eugene Leviantafaa9342016-11-16 09:49:39 +00001743 [=]() { return isAbsolute(Tok); },
1744 [=]() { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001745}
1746
1747Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001748 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001749 Expr L = readExpr();
1750 expect(":");
1751 Expr R = readExpr();
1752 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1753}
1754
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001755Expr ScriptParser::readParenExpr() {
1756 expect("(");
1757 Expr E = readExpr();
1758 expect(")");
1759 return E;
1760}
1761
Eugene Leviantbbe38602016-07-19 09:25:43 +00001762std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1763 std::vector<StringRef> Phdrs;
1764 while (!Error && peek().startswith(":")) {
1765 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001766 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001767 }
1768 return Phdrs;
1769}
1770
George Rimar95dd7182016-10-18 10:49:50 +00001771// Read a program header type name. The next token must be a
1772// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001773unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001774 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001775 uint64_t Val;
1776 if (readInteger(Tok, Val))
1777 return Val;
1778
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001779 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001780 .Case("PT_NULL", PT_NULL)
1781 .Case("PT_LOAD", PT_LOAD)
1782 .Case("PT_DYNAMIC", PT_DYNAMIC)
1783 .Case("PT_INTERP", PT_INTERP)
1784 .Case("PT_NOTE", PT_NOTE)
1785 .Case("PT_SHLIB", PT_SHLIB)
1786 .Case("PT_PHDR", PT_PHDR)
1787 .Case("PT_TLS", PT_TLS)
1788 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1789 .Case("PT_GNU_STACK", PT_GNU_STACK)
1790 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001791 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001792 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001793 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001794
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001795 if (Ret == (unsigned)-1) {
1796 setError("invalid program header type: " + Tok);
1797 return PT_NULL;
1798 }
1799 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001800}
1801
Rui Ueyama95769b42016-08-31 20:03:54 +00001802void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001803 // Identifiers start at 2 because 0 and 1 are reserved
1804 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001805 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001806 Config->VersionDefinitions.push_back({VerStr, VersionId});
1807
Rui Ueyama83043f22016-10-17 16:01:53 +00001808 if (consume("global:") || peek() != "local:")
George Rimar20b65982016-08-31 09:08:26 +00001809 readGlobal(VerStr);
Rui Ueyama83043f22016-10-17 16:01:53 +00001810 if (consume("local:"))
George Rimarbb6c01e2016-11-12 07:04:15 +00001811 readLocal(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001812 expect("}");
1813
1814 // Each version may have a parent version. For example, "Ver2" defined as
1815 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1816 // version hierarchy is, probably against your instinct, purely for human; the
1817 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1818 if (!VerStr.empty() && peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001819 skip();
George Rimar20b65982016-08-31 09:08:26 +00001820 expect(";");
1821}
1822
George Rimare0fc2422016-11-16 17:59:10 +00001823void ScriptParser::readSymbols(std::vector<SymbolVersion> &V) {
1824 for (;;) {
1825 if (consume("extern"))
1826 readVersionExtern(&V);
1827
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001828 if (peek() == "}" || peek() == "local:" || Error)
George Rimare0fc2422016-11-16 17:59:10 +00001829 return;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001830 StringRef Tok = next();
1831 V.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001832 expect(";");
1833 }
1834}
1835
George Rimarbb6c01e2016-11-12 07:04:15 +00001836void ScriptParser::readLocal(StringRef VerStr) {
1837 if (consume("*")) {
1838 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1839 expect(";");
1840 return;
1841 }
1842
1843 if (VerStr.empty())
1844 setError("locals list for anonymous version is not supported");
1845
George Rimar17c65af2016-11-16 18:46:23 +00001846 readSymbols(Config->VersionScriptLocals);
George Rimar20b65982016-08-31 09:08:26 +00001847}
1848
George Rimare0fc2422016-11-16 17:59:10 +00001849void ScriptParser::readVersionExtern(std::vector<SymbolVersion> *V) {
George Rimarcd574a52016-09-09 14:35:36 +00001850 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001851 expect("{");
1852
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001853 while (!Error && peek() != "}") {
1854 StringRef Tok = next();
1855 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1856 V->push_back({unquote(Tok), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001857 expect(";");
1858 }
1859
1860 expect("}");
1861 expect(";");
1862}
1863
1864void ScriptParser::readGlobal(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001865 if (VerStr.empty())
George Rimare0fc2422016-11-16 17:59:10 +00001866 readSymbols(Config->VersionScriptGlobals);
George Rimar20b65982016-08-31 09:08:26 +00001867 else
George Rimare0fc2422016-11-16 17:59:10 +00001868 readSymbols(Config->VersionDefinitions.back().Globals);
George Rimar20b65982016-08-31 09:08:26 +00001869}
1870
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001871static bool isUnderSysroot(StringRef Path) {
1872 if (Config->Sysroot == "")
1873 return false;
1874 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1875 if (sys::fs::equivalent(Config->Sysroot, Path))
1876 return true;
1877 return false;
1878}
1879
Rui Ueyama07320e42016-04-20 20:13:41 +00001880void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001881 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001882 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1883}
1884
1885void elf::readVersionScript(MemoryBufferRef MB) {
1886 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001887}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001888
Rui Ueyama07320e42016-04-20 20:13:41 +00001889template class elf::LinkerScript<ELF32LE>;
1890template class elf::LinkerScript<ELF32BE>;
1891template class elf::LinkerScript<ELF64LE>;
1892template class elf::LinkerScript<ELF64BE>;