blob: 229947cefe664a4e94ebe506f276ea0b630c61da [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
Rui Ueyamaedf75e72016-11-17 20:27:10 +0000871// This function is essentially the same as getOutputSection(Name)->Size,
872// but it won't print out an error message if a given section is not found.
873//
874// Linker script does not create an output section if its content is empty.
875// We want to allow SIZEOF(.foo) where .foo is a section which happened to
876// be empty. That is why this function is different from getOutputSection().
877template <class ELFT>
878uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
879 for (OutputSectionBase *Sec : *OutputSections)
880 if (Sec->getName() == Name)
881 return Sec->Size;
882 return 0;
883}
884
George Rimar884e7862016-09-08 08:19:13 +0000885template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000886 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000887}
888
George Rimar884e7862016-09-08 08:19:13 +0000889template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
890 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
891 return B->getVA<ELFT>();
892 error("symbol not found: " + S);
893 return 0;
894}
895
George Rimarf34f45f2016-09-23 13:17:23 +0000896template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
897 return Symtab<ELFT>::X->find(S) != nullptr;
898}
899
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000900template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
901 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
902 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
903 return DR && !DR->Section;
904}
905
Eugene Leviantafaa9342016-11-16 09:49:39 +0000906// Gets section symbol belongs to. Symbol "." doesn't belong to any
907// specific section but isn't absolute at the same time, so we try
908// to find suitable section for it as well.
909template <class ELFT>
910const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
911 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
912 if (!Sym) {
913 if (OutputSections->empty())
914 return nullptr;
915 return CurOutSec ? CurOutSec : (*OutputSections)[0];
916 }
917
918 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
919 return DR->Section ? DR->Section->OutSec : nullptr;
920 if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
921 return DS->Section;
922
923 return nullptr;
924}
925
Eugene Leviantbbe38602016-07-19 09:25:43 +0000926// Returns indices of ELF headers containing specific section, identified
927// by Name. Each index is a zero based number of ELF header listed within
928// PHDRS {} script block.
929template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000930std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000931 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
932 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000933 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000934 continue;
935
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000936 std::vector<size_t> Ret;
937 for (StringRef PhdrName : Cmd->Phdrs)
938 Ret.push_back(getPhdrIndex(PhdrName));
939 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000940 }
George Rimar31d842f2016-07-20 16:43:03 +0000941 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000942}
943
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000944template <class ELFT>
945size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
946 size_t I = 0;
947 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
948 if (Cmd.Name == PhdrName)
949 return I;
950 ++I;
951 }
952 error("section header '" + PhdrName + "' is not listed in PHDRS");
953 return 0;
954}
955
Rui Ueyama07320e42016-04-20 20:13:41 +0000956class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000957 typedef void (ScriptParser::*Handler)();
958
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000959public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000960 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000961
George Rimar20b65982016-08-31 09:08:26 +0000962 void readLinkerScript();
963 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000964
965private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000966 void addFile(StringRef Path);
967
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000968 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000969 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000970 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000971 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000972 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000973 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000974 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000975 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000976 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000977 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000978 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000979 void readVersion();
980 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000981
Rui Ueyama113cdec2016-07-24 23:05:57 +0000982 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000983 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000984 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000985 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000986 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000987 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000988 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000989 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000990 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000991 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000992 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000993 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000994 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000995 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000996 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000997 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000998
999 Expr readExpr();
1000 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001001 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +00001002 Expr readPrimary();
1003 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001004 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001005
George Rimar20b65982016-08-31 09:08:26 +00001006 // For parsing version script.
Rui Ueyama12450b22016-11-18 06:30:09 +00001007 std::vector<SymbolVersion> readVersionExtern();
1008 void readAnonymousDeclaration();
Rui Ueyama95769b42016-08-31 20:03:54 +00001009 void readVersionDeclaration(StringRef VerStr);
Rui Ueyama12450b22016-11-18 06:30:09 +00001010 std::vector<SymbolVersion> readSymbols();
George Rimar20b65982016-08-31 09:08:26 +00001011
Rui Ueyama07320e42016-04-20 20:13:41 +00001012 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001013 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001014};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001015
George Rimar20b65982016-08-31 09:08:26 +00001016void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +00001017 readVersionScriptCommand();
1018 if (!atEOF())
1019 setError("EOF expected, but got " + next());
1020}
1021
1022void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001023 if (consume("{")) {
Rui Ueyama12450b22016-11-18 06:30:09 +00001024 readAnonymousDeclaration();
George Rimar20b65982016-08-31 09:08:26 +00001025 return;
1026 }
1027
Rui Ueyama95769b42016-08-31 20:03:54 +00001028 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001029 StringRef VerStr = next();
1030 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001031 setError("anonymous version definition is used in "
1032 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001033 return;
1034 }
1035 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001036 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001037 }
1038}
1039
Rui Ueyama95769b42016-08-31 20:03:54 +00001040void ScriptParser::readVersion() {
1041 expect("{");
1042 readVersionScriptCommand();
1043 expect("}");
1044}
1045
George Rimar20b65982016-08-31 09:08:26 +00001046void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001047 while (!atEOF()) {
1048 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001049 if (Tok == ";")
1050 continue;
1051
Eugene Leviant20d03192016-09-16 15:30:47 +00001052 if (Tok == "ASSERT") {
1053 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1054 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001055 readEntry();
1056 } else if (Tok == "EXTERN") {
1057 readExtern();
1058 } else if (Tok == "GROUP" || Tok == "INPUT") {
1059 readGroup();
1060 } else if (Tok == "INCLUDE") {
1061 readInclude();
1062 } else if (Tok == "OUTPUT") {
1063 readOutput();
1064 } else if (Tok == "OUTPUT_ARCH") {
1065 readOutputArch();
1066 } else if (Tok == "OUTPUT_FORMAT") {
1067 readOutputFormat();
1068 } else if (Tok == "PHDRS") {
1069 readPhdrs();
1070 } else if (Tok == "SEARCH_DIR") {
1071 readSearchDir();
1072 } else if (Tok == "SECTIONS") {
1073 readSections();
1074 } else if (Tok == "VERSION") {
1075 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001076 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001077 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001078 } else {
George Rimar57610422016-03-11 14:43:02 +00001079 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001080 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001081 }
1082}
1083
Rui Ueyama717677a2016-02-11 21:17:59 +00001084void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001085 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001086 SmallString<128> PathData;
1087 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001088 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001089 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001090 return;
1091 }
1092 }
1093
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001094 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001095 Driver->addFile(S);
1096 } else if (S.startswith("=")) {
1097 if (Config->Sysroot.empty())
1098 Driver->addFile(S.substr(1));
1099 else
1100 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1101 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001102 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001103 } else if (sys::fs::exists(S)) {
1104 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001105 } else {
1106 std::string Path = findFromSearchPaths(S);
1107 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001108 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001109 else
1110 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001111 }
1112}
1113
Rui Ueyama717677a2016-02-11 21:17:59 +00001114void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001115 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001116 bool Orig = Config->AsNeeded;
1117 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001118 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001119 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001120 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001121}
1122
Rui Ueyama717677a2016-02-11 21:17:59 +00001123void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001124 // -e <symbol> takes predecence over ENTRY(<symbol>).
1125 expect("(");
1126 StringRef Tok = next();
1127 if (Config->Entry.empty())
1128 Config->Entry = Tok;
1129 expect(")");
1130}
1131
Rui Ueyama717677a2016-02-11 21:17:59 +00001132void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001133 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001134 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001135 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001136}
1137
Rui Ueyama717677a2016-02-11 21:17:59 +00001138void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001139 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001140 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001141 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001142 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001143 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001144 else
George Rimarcd574a52016-09-09 14:35:36 +00001145 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001146 }
1147}
1148
Rui Ueyama717677a2016-02-11 21:17:59 +00001149void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001150 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001151 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001152 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001153 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001154 return;
1155 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001156 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001157 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1158 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001159 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001160}
1161
Rui Ueyama717677a2016-02-11 21:17:59 +00001162void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001163 // -o <file> takes predecence over OUTPUT(<file>).
1164 expect("(");
1165 StringRef Tok = next();
1166 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001167 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001168 expect(")");
1169}
1170
Rui Ueyama717677a2016-02-11 21:17:59 +00001171void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001172 // Error checking only for now.
1173 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001174 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001175 expect(")");
1176}
1177
Rui Ueyama717677a2016-02-11 21:17:59 +00001178void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001179 // Error checking only for now.
1180 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001181 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001182 StringRef Tok = next();
1183 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001184 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001185 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001186 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001187 return;
1188 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001189 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001190 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001191 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001192 expect(")");
1193}
1194
Eugene Leviantbbe38602016-07-19 09:25:43 +00001195void ScriptParser::readPhdrs() {
1196 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001197 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001198 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001199 Opt.PhdrsCommands.push_back(
1200 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001201 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1202
1203 PhdrCmd.Type = readPhdrType();
1204 do {
1205 Tok = next();
1206 if (Tok == ";")
1207 break;
1208 if (Tok == "FILEHDR")
1209 PhdrCmd.HasFilehdr = true;
1210 else if (Tok == "PHDRS")
1211 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001212 else if (Tok == "AT")
1213 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001214 else if (Tok == "FLAGS") {
1215 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001216 // Passing 0 for the value of dot is a bit of a hack. It means that
1217 // we accept expressions like ".|1".
1218 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001219 expect(")");
1220 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001221 setError("unexpected header attribute: " + Tok);
1222 } while (!Error);
1223 }
1224}
1225
Rui Ueyama717677a2016-02-11 21:17:59 +00001226void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001227 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001228 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001229 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001230 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001231 expect(")");
1232}
1233
Rui Ueyama717677a2016-02-11 21:17:59 +00001234void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001235 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001236 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001237 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001238 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001239 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001240 if (!Cmd) {
1241 if (Tok == "ASSERT")
1242 Cmd = new AssertCommand(readAssert());
1243 else
1244 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001245 }
Rui Ueyama10416562016-08-04 02:03:27 +00001246 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001247 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001248}
1249
Rui Ueyama708019c2016-07-24 18:19:40 +00001250static int precedence(StringRef Op) {
1251 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001252 .Cases("*", "/", 5)
1253 .Cases("+", "-", 4)
1254 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001255 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001256 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001257 .Default(-1);
1258}
1259
Eugene Leviantdb688452016-11-03 10:54:58 +00001260StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001261 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001262 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001263 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001264 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001265}
1266
George Rimarbe394db2016-09-16 20:21:55 +00001267SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001268 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001269 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001270 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001271 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001272 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001273 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001274 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001275 return SortSectionPolicy::None;
1276 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001277}
1278
George Rimar395281c2016-09-16 17:42:10 +00001279// Method reads a list of sequence of excluded files and section globs given in
1280// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1281// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001282// The semantics of that is next:
1283// * Include .foo.1 from every file.
1284// * Include .foo.2 from every file but a.o
1285// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001286std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1287 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001288 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001289 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001290 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001291 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001292 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001293 }
1294
George Rimar601e9892016-09-21 08:53:21 +00001295 std::vector<StringRef> V;
1296 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1297 V.push_back(next());
1298
1299 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001300 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001301 else
1302 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001303 }
George Rimar07171f22016-09-21 15:56:44 +00001304 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001305}
1306
George Rimar07171f22016-09-21 15:56:44 +00001307// Section pattern grammar can have complex expressions, for example:
1308// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1309// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1310// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1311// This methods handles wrapping sequences of excluded files and section globs
1312// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001313InputSectionDescription *
1314ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001315 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001316 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001317 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001318 SortSectionPolicy Outer = readSortKind();
1319 SortSectionPolicy Inner = SortSectionPolicy::Default;
1320 std::vector<SectionPattern> V;
1321 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001322 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001323 Inner = readSortKind();
1324 if (Inner != SortSectionPolicy::Default) {
1325 expect("(");
1326 V = readInputSectionsList();
1327 expect(")");
1328 } else {
1329 V = readInputSectionsList();
1330 }
George Rimar350ece42016-08-03 08:35:59 +00001331 expect(")");
1332 } else {
George Rimar07171f22016-09-21 15:56:44 +00001333 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001334 }
George Rimar0702c4e2016-07-29 15:32:46 +00001335
George Rimar07171f22016-09-21 15:56:44 +00001336 for (SectionPattern &Pat : V) {
1337 Pat.SortInner = Inner;
1338 Pat.SortOuter = Outer;
1339 }
1340
1341 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1342 }
Rui Ueyama10416562016-08-04 02:03:27 +00001343 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001344}
1345
George Rimara2496cb2016-08-30 09:46:59 +00001346InputSectionDescription *
1347ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001348 // Input section wildcard can be surrounded by KEEP.
1349 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001350 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001351 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001352 StringRef FilePattern = next();
1353 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001354 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001355 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001356 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001357 }
George Rimara2496cb2016-08-30 09:46:59 +00001358 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001359}
1360
George Rimar03fc0102016-07-28 07:18:23 +00001361void ScriptParser::readSort() {
1362 expect("(");
1363 expect("CONSTRUCTORS");
1364 expect(")");
1365}
1366
George Rimareefa7582016-08-04 09:29:31 +00001367Expr ScriptParser::readAssert() {
1368 expect("(");
1369 Expr E = readExpr();
1370 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001371 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001372 expect(")");
1373 return [=](uint64_t Dot) {
1374 uint64_t V = E(Dot);
1375 if (!V)
1376 error(Msg);
1377 return V;
1378 };
1379}
1380
Rui Ueyama25150e82016-09-06 17:46:43 +00001381// Reads a FILL(expr) command. We handle the FILL command as an
1382// alias for =fillexp section attribute, which is different from
1383// what GNU linkers do.
1384// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001385std::vector<uint8_t> ScriptParser::readFill() {
1386 expect("(");
1387 std::vector<uint8_t> V = readOutputSectionFiller(next());
1388 expect(")");
1389 expect(";");
1390 return V;
1391}
1392
Rui Ueyama10416562016-08-04 02:03:27 +00001393OutputSectionCommand *
1394ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001395 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001396
1397 // Read an address expression.
1398 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1399 if (peek() != ":")
1400 Cmd->AddrExpr = readExpr();
1401
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001402 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001403
Rui Ueyama83043f22016-10-17 16:01:53 +00001404 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001405 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001406 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001407 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001408 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001409 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001410
Davide Italiano246f6812016-07-22 03:36:24 +00001411 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001412 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001413 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001414 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001415 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001416 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001417
Rui Ueyama83043f22016-10-17 16:01:53 +00001418 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001419 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001420 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001421 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001422 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1423 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001424 else if (Tok == "FILL")
1425 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001426 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001427 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001428 else if (peek() == "(")
1429 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001430 else
1431 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001432 }
George Rimar076fe152016-07-21 06:43:01 +00001433 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001434
Rui Ueyama83043f22016-10-17 16:01:53 +00001435 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001436 Cmd->Filler = readOutputSectionFiller(next());
1437 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001438 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001439
Rui Ueyama10416562016-08-04 02:03:27 +00001440 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001441}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001442
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001443// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1444// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1445//
1446// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1447// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1448// as 32-bit big-endian values. We will do the same as ld.gold does
1449// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001450std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001451 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001452 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001453 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001454 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001455 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001456 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001457}
1458
Petr Hoseka35e39c2016-08-16 01:11:16 +00001459SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001460 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001461 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001462 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001463 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001464 expect(")");
1465 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001466 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001467}
1468
Rafael Espindolac96da112016-11-01 11:30:45 +00001469SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001470 SymbolAssignment *Cmd = nullptr;
1471 if (peek() == "=" || peek() == "+=") {
1472 Cmd = readAssignment(Tok);
1473 expect(";");
1474 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001475 Cmd = readProvideHidden(true, false);
1476 } else if (Tok == "HIDDEN") {
1477 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001478 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001479 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001480 }
1481 return Cmd;
1482}
1483
George Rimar30835ea2016-07-28 21:08:56 +00001484static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1485 if (S == ".")
1486 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001487 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001488}
1489
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001490static bool isAbsolute(StringRef S) {
1491 if (S == ".")
1492 return false;
1493 return ScriptBase->isAbsolute(S);
1494}
1495
George Rimar30835ea2016-07-28 21:08:56 +00001496SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1497 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001498 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001499 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001500 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001501 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1502 // Call readExpr1 to read the whole expression.
1503 E = readExpr1(readParenExpr(), 0);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001504 E.IsAbsolute = []() { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001505 } else {
1506 E = readExpr();
1507 }
George Rimar30835ea2016-07-28 21:08:56 +00001508 if (Op == "+=")
1509 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001510 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001511}
1512
1513// This is an operator-precedence parser to parse a linker
1514// script expression.
1515Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1516
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001517static Expr combine(StringRef Op, Expr L, Expr R) {
1518 if (Op == "*")
1519 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1520 if (Op == "/") {
1521 return [=](uint64_t Dot) -> uint64_t {
1522 uint64_t RHS = R(Dot);
1523 if (RHS == 0) {
1524 error("division by zero");
1525 return 0;
1526 }
1527 return L(Dot) / RHS;
1528 };
1529 }
1530 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001531 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
Eugene Leviantafaa9342016-11-16 09:49:39 +00001532 [=]() { return L.IsAbsolute() && R.IsAbsolute(); },
1533 [=]() {
1534 const OutputSectionBase *S = L.Section();
1535 return S ? S : R.Section();
1536 }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001537 if (Op == "-")
1538 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001539 if (Op == "<<")
1540 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1541 if (Op == ">>")
1542 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001543 if (Op == "<")
1544 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1545 if (Op == ">")
1546 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1547 if (Op == ">=")
1548 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1549 if (Op == "<=")
1550 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1551 if (Op == "==")
1552 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1553 if (Op == "!=")
1554 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1555 if (Op == "&")
1556 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001557 if (Op == "|")
1558 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001559 llvm_unreachable("invalid operator");
1560}
1561
Rui Ueyama708019c2016-07-24 18:19:40 +00001562// This is a part of the operator-precedence parser. This function
1563// assumes that the remaining token stream starts with an operator.
1564Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1565 while (!atEOF() && !Error) {
1566 // Read an operator and an expression.
1567 StringRef Op1 = peek();
1568 if (Op1 == "?")
1569 return readTernary(Lhs);
1570 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001571 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001572 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001573 Expr Rhs = readPrimary();
1574
1575 // Evaluate the remaining part of the expression first if the
1576 // next operator has greater precedence than the previous one.
1577 // For example, if we have read "+" and "3", and if the next
1578 // operator is "*", then we'll evaluate 3 * ... part first.
1579 while (!atEOF()) {
1580 StringRef Op2 = peek();
1581 if (precedence(Op2) <= precedence(Op1))
1582 break;
1583 Rhs = readExpr1(Rhs, precedence(Op2));
1584 }
1585
1586 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001587 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001588 return Lhs;
1589}
1590
1591uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001592 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001593 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001594 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001595 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001596 error("unknown constant: " + S);
1597 return 0;
1598}
1599
Rui Ueyama626e0b02016-09-02 18:19:00 +00001600// Parses Tok as an integer. Returns true if successful.
1601// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1602// and decimal numbers. Decimal numbers may have "K" (kilo) or
1603// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001604static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001605 if (Tok.startswith("-")) {
1606 if (!readInteger(Tok.substr(1), Result))
1607 return false;
1608 Result = -Result;
1609 return true;
1610 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001611 if (Tok.startswith_lower("0x"))
1612 return !Tok.substr(2).getAsInteger(16, Result);
1613 if (Tok.endswith_lower("H"))
1614 return !Tok.drop_back().getAsInteger(16, Result);
1615
1616 int Suffix = 1;
1617 if (Tok.endswith_lower("K")) {
1618 Suffix = 1024;
1619 Tok = Tok.drop_back();
1620 } else if (Tok.endswith_lower("M")) {
1621 Suffix = 1024 * 1024;
1622 Tok = Tok.drop_back();
1623 }
1624 if (Tok.getAsInteger(10, Result))
1625 return false;
1626 Result *= Suffix;
1627 return true;
1628}
1629
George Rimare38cbab2016-09-26 19:22:50 +00001630BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1631 int Size = StringSwitch<unsigned>(Tok)
1632 .Case("BYTE", 1)
1633 .Case("SHORT", 2)
1634 .Case("LONG", 4)
1635 .Case("QUAD", 8)
1636 .Default(-1);
1637 if (Size == -1)
1638 return nullptr;
1639
1640 expect("(");
1641 uint64_t Val = 0;
1642 StringRef S = next();
1643 if (!readInteger(S, Val))
1644 setError("unexpected value: " + S);
1645 expect(")");
1646 return new BytesDataCommand(Val, Size);
1647}
1648
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001649StringRef ScriptParser::readParenLiteral() {
1650 expect("(");
1651 StringRef Tok = next();
1652 expect(")");
1653 return Tok;
1654}
1655
Rui Ueyama708019c2016-07-24 18:19:40 +00001656Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001657 if (peek() == "(")
1658 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001659
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001660 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001661
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001662 if (Tok == "~") {
1663 Expr E = readPrimary();
1664 return [=](uint64_t Dot) { return ~E(Dot); };
1665 }
1666 if (Tok == "-") {
1667 Expr E = readPrimary();
1668 return [=](uint64_t Dot) { return -E(Dot); };
1669 }
1670
Rui Ueyama708019c2016-07-24 18:19:40 +00001671 // Built-in functions are parsed here.
1672 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001673 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001674 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001675 return {
1676 [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; },
1677 [=]() { return false; },
1678 [=]() { return ScriptBase->getOutputSection(Name); }};
George Rimar96659df2016-08-30 09:54:01 +00001679 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001680 if (Tok == "LOADADDR") {
1681 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001682 return [=](uint64_t Dot) {
1683 return ScriptBase->getOutputSection(Name)->getLMA();
1684 };
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001685 }
George Rimareefa7582016-08-04 09:29:31 +00001686 if (Tok == "ASSERT")
1687 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001688 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001689 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001690 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1691 }
1692 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001693 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001694 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001695 }
George Rimarf34f45f2016-09-23 13:17:23 +00001696 if (Tok == "DEFINED") {
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001697 StringRef Name = readParenLiteral();
1698 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001699 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001700 if (Tok == "SEGMENT_START") {
1701 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001702 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001703 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001704 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001705 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001706 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001707 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001708 if (Tok == "DATA_SEGMENT_ALIGN") {
1709 expect("(");
1710 Expr E = readExpr();
1711 expect(",");
1712 readExpr();
1713 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001714 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001715 }
1716 if (Tok == "DATA_SEGMENT_END") {
1717 expect("(");
1718 expect(".");
1719 expect(")");
1720 return [](uint64_t Dot) { return Dot; };
1721 }
George Rimar276b4e62016-07-26 17:58:44 +00001722 // GNU linkers implements more complicated logic to handle
1723 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1724 // the next page boundary for simplicity.
1725 if (Tok == "DATA_SEGMENT_RELRO_END") {
1726 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001727 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001728 expect(",");
1729 readExpr();
1730 expect(")");
1731 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1732 }
George Rimar9e694502016-07-29 16:18:47 +00001733 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001734 StringRef Name = readParenLiteral();
Rui Ueyamaedf75e72016-11-17 20:27:10 +00001735 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001736 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001737 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001738 StringRef Name = readParenLiteral();
Eugene Leviantafaa9342016-11-16 09:49:39 +00001739 return [=](uint64_t Dot) {
1740 return ScriptBase->getOutputSection(Name)->Addralign;
1741 };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001742 }
George Rimare32a3592016-08-10 07:59:34 +00001743 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001744 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001745
George Rimar9f2f7ad2016-09-02 16:01:42 +00001746 // Tok is a literal number.
1747 uint64_t V;
1748 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001749 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001750
1751 // Tok is a symbol name.
1752 if (Tok != "." && !isValidCIdentifier(Tok))
1753 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001754 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
Eugene Leviantafaa9342016-11-16 09:49:39 +00001755 [=]() { return isAbsolute(Tok); },
1756 [=]() { return ScriptBase->getSymbolSection(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001757}
1758
1759Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001760 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001761 Expr L = readExpr();
1762 expect(":");
1763 Expr R = readExpr();
1764 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1765}
1766
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001767Expr ScriptParser::readParenExpr() {
1768 expect("(");
1769 Expr E = readExpr();
1770 expect(")");
1771 return E;
1772}
1773
Eugene Leviantbbe38602016-07-19 09:25:43 +00001774std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1775 std::vector<StringRef> Phdrs;
1776 while (!Error && peek().startswith(":")) {
1777 StringRef Tok = next();
George Rimarda841c12016-11-14 10:03:54 +00001778 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
Eugene Leviantbbe38602016-07-19 09:25:43 +00001779 }
1780 return Phdrs;
1781}
1782
George Rimar95dd7182016-10-18 10:49:50 +00001783// Read a program header type name. The next token must be a
1784// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001785unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001786 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001787 uint64_t Val;
1788 if (readInteger(Tok, Val))
1789 return Val;
1790
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001791 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001792 .Case("PT_NULL", PT_NULL)
1793 .Case("PT_LOAD", PT_LOAD)
1794 .Case("PT_DYNAMIC", PT_DYNAMIC)
1795 .Case("PT_INTERP", PT_INTERP)
1796 .Case("PT_NOTE", PT_NOTE)
1797 .Case("PT_SHLIB", PT_SHLIB)
1798 .Case("PT_PHDR", PT_PHDR)
1799 .Case("PT_TLS", PT_TLS)
1800 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1801 .Case("PT_GNU_STACK", PT_GNU_STACK)
1802 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001803 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001804 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001805 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001806
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001807 if (Ret == (unsigned)-1) {
1808 setError("invalid program header type: " + Tok);
1809 return PT_NULL;
1810 }
1811 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001812}
1813
Rui Ueyama12450b22016-11-18 06:30:09 +00001814// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1815void ScriptParser::readAnonymousDeclaration() {
1816 // Read global symbols first. "global:" is default, so if there's
1817 // no label, we assume global symbols.
1818 if (consume("global:") || peek() != "local:")
1819 Config->VersionScriptGlobals = readSymbols();
1820
1821 // Next, read local symbols.
1822 if (consume("local:")) {
1823 if (consume("*")) {
1824 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1825 expect(";");
1826 } else {
1827 setError("local symbol list for anonymous version is not supported");
1828 }
1829 }
1830 expect("}");
1831 expect(";");
1832}
1833
1834// Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
Rui Ueyama95769b42016-08-31 20:03:54 +00001835void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001836 // Identifiers start at 2 because 0 and 1 are reserved
1837 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
Rui Ueyamada805c42016-11-17 03:39:21 +00001838 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
George Rimar20b65982016-08-31 09:08:26 +00001839 Config->VersionDefinitions.push_back({VerStr, VersionId});
1840
Rui Ueyama12450b22016-11-18 06:30:09 +00001841 // Read global symbols.
Rui Ueyama83043f22016-10-17 16:01:53 +00001842 if (consume("global:") || peek() != "local:")
Rui Ueyama12450b22016-11-18 06:30:09 +00001843 Config->VersionDefinitions.back().Globals = readSymbols();
1844
1845 // Read local symbols.
1846 if (consume("local:")) {
1847 if (consume("*")) {
1848 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1849 expect(";");
1850 } else {
1851 for (SymbolVersion V : readSymbols())
1852 Config->VersionScriptLocals.push_back(V);
1853 }
1854 }
George Rimar20b65982016-08-31 09:08:26 +00001855 expect("}");
1856
Rui Ueyama12450b22016-11-18 06:30:09 +00001857 // Each version may have a parent version. For example, "Ver2"
1858 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1859 // as a parent. This version hierarchy is, probably against your
1860 // instinct, purely for hint; the runtime doesn't care about it
1861 // at all. In LLD, we simply ignore it.
1862 if (peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001863 skip();
George Rimar20b65982016-08-31 09:08:26 +00001864 expect(";");
1865}
1866
Rui Ueyama12450b22016-11-18 06:30:09 +00001867// Reads a list of symbols for a versions cript.
1868std::vector<SymbolVersion> ScriptParser::readSymbols() {
1869 std::vector<SymbolVersion> Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001870 for (;;) {
1871 if (consume("extern"))
Rui Ueyama12450b22016-11-18 06:30:09 +00001872 for (SymbolVersion V : readVersionExtern())
1873 Ret.push_back(V);
George Rimare0fc2422016-11-16 17:59:10 +00001874
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001875 if (peek() == "}" || peek() == "local:" || Error)
Rui Ueyama12450b22016-11-18 06:30:09 +00001876 break;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001877 StringRef Tok = next();
Rui Ueyama12450b22016-11-18 06:30:09 +00001878 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
George Rimare0fc2422016-11-16 17:59:10 +00001879 expect(";");
1880 }
Rui Ueyama12450b22016-11-18 06:30:09 +00001881 return Ret;
George Rimare0fc2422016-11-16 17:59:10 +00001882}
1883
Rui Ueyama12450b22016-11-18 06:30:09 +00001884// Reads an "extern C++" directive, e.g.,
1885// "extern "C++" { ns::*; "f(int, double)"; };"
1886std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
George Rimarcd574a52016-09-09 14:35:36 +00001887 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001888 expect("{");
1889
Rui Ueyama12450b22016-11-18 06:30:09 +00001890 std::vector<SymbolVersion> Ret;
Rui Ueyama0ee25a62016-11-17 03:52:14 +00001891 while (!Error && peek() != "}") {
1892 StringRef Tok = next();
1893 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
Rui Ueyama12450b22016-11-18 06:30:09 +00001894 Ret.push_back({unquote(Tok), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001895 expect(";");
1896 }
1897
1898 expect("}");
1899 expect(";");
Rui Ueyama12450b22016-11-18 06:30:09 +00001900 return Ret;
George Rimar20b65982016-08-31 09:08:26 +00001901}
1902
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001903static bool isUnderSysroot(StringRef Path) {
1904 if (Config->Sysroot == "")
1905 return false;
1906 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1907 if (sys::fs::equivalent(Config->Sysroot, Path))
1908 return true;
1909 return false;
1910}
1911
Rui Ueyama07320e42016-04-20 20:13:41 +00001912void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001913 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001914 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1915}
1916
1917void elf::readVersionScript(MemoryBufferRef MB) {
1918 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001919}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001920
Rui Ueyama07320e42016-04-20 20:13:41 +00001921template class elf::LinkerScript<ELF32LE>;
1922template class elf::LinkerScript<ELF32BE>;
1923template class elf::LinkerScript<ELF64LE>;
1924template class elf::LinkerScript<ELF64BE>;