blob: dd46faed586ab6d3e0c48814edb8af59444277c9 [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;
67 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, nullptr,
Rafael Espindola093abab2016-10-27 17:45:40 +000068 STB_GLOBAL, STT_NOTYPE, 0);
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) {
George Rimare1937bb2016-08-19 15:36:32 +000078 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
79 Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
Rui Ueyama16024212016-08-11 23:22:52 +000080 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000081}
82
Eugene Leviantdb741e72016-09-07 07:08:43 +000083template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
Rafael Espindola2f831dc2016-10-31 19:56:37 +000084 if (Cmd->Expression.IsAbsolute())
Eugene Leviantdb741e72016-09-07 07:08:43 +000085 addRegular<ELFT>(Cmd);
86 else
87 addSynthetic<ELFT>(Cmd);
88}
Rui Ueyama16024212016-08-11 23:22:52 +000089// If a symbol was in PROVIDE(), we need to define it only when
90// it is an undefined symbol.
91template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
92 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000093 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000094 if (!Cmd->Provide)
95 return true;
96 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
97 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000098}
99
George Rimar076fe152016-07-21 06:43:01 +0000100bool SymbolAssignment::classof(const BaseCommand *C) {
101 return C->Kind == AssignmentKind;
102}
103
104bool OutputSectionCommand::classof(const BaseCommand *C) {
105 return C->Kind == OutputSectionKind;
106}
107
George Rimareea31142016-07-21 14:26:59 +0000108bool InputSectionDescription::classof(const BaseCommand *C) {
109 return C->Kind == InputSectionKind;
110}
111
George Rimareefa7582016-08-04 09:29:31 +0000112bool AssertCommand::classof(const BaseCommand *C) {
113 return C->Kind == AssertKind;
114}
115
George Rimare38cbab2016-09-26 19:22:50 +0000116bool BytesDataCommand::classof(const BaseCommand *C) {
117 return C->Kind == BytesDataKind;
118}
119
Rui Ueyama36a153c2016-07-23 14:09:58 +0000120template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000121 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000122}
123
Eugene Zelenko22886a22016-11-05 01:00:56 +0000124template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
125template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000126
Rui Ueyama07320e42016-04-20 20:13:41 +0000127template <class ELFT>
128bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Eugene Leviantcf43f172016-10-05 09:36:59 +0000129 for (InputSectionDescription *ID : Opt.KeptSections) {
130 StringRef Filename = S->getFile()->getName();
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000131 if (!ID->FilePat.match(sys::path::filename(Filename)))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000132 continue;
Rui Ueyamab66260a2016-10-05 20:09:50 +0000133
134 for (SectionPattern &P : ID->SectionPatterns)
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000135 if (P.SectionPat.match(S->Name))
Eugene Leviantcf43f172016-10-05 09:36:59 +0000136 return true;
137 }
George Rimareea31142016-07-21 14:26:59 +0000138 return false;
139}
140
George Rimar575208c2016-09-15 19:15:12 +0000141static bool comparePriority(InputSectionData *A, InputSectionData *B) {
142 return getPriority(A->Name) < getPriority(B->Name);
143}
144
Rafael Espindolac0028d32016-09-08 20:47:52 +0000145static bool compareName(InputSectionData *A, InputSectionData *B) {
Rafael Espindola042a3f22016-09-08 14:06:08 +0000146 return A->Name < B->Name;
Rui Ueyama742c3832016-08-04 22:27:00 +0000147}
George Rimar350ece42016-08-03 08:35:59 +0000148
Rafael Espindolac0028d32016-09-08 20:47:52 +0000149static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
Rui Ueyama742c3832016-08-04 22:27:00 +0000150 // ">" is not a mistake. Larger alignments are placed before smaller
151 // alignments in order to reduce the amount of padding necessary.
152 // This is compatible with GNU.
153 return A->Alignment > B->Alignment;
154}
George Rimar350ece42016-08-03 08:35:59 +0000155
Rafael Espindolac0028d32016-09-08 20:47:52 +0000156static std::function<bool(InputSectionData *, InputSectionData *)>
George Rimarbe394db2016-09-16 20:21:55 +0000157getComparator(SortSectionPolicy K) {
158 switch (K) {
159 case SortSectionPolicy::Alignment:
160 return compareAlignment;
161 case SortSectionPolicy::Name:
Rafael Espindolac0028d32016-09-08 20:47:52 +0000162 return compareName;
George Rimarbe394db2016-09-16 20:21:55 +0000163 case SortSectionPolicy::Priority:
164 return comparePriority;
165 default:
166 llvm_unreachable("unknown sort policy");
167 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000168}
George Rimar0702c4e2016-07-29 15:32:46 +0000169
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000170template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000171static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000172 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000173 if (Kind == ConstraintKind::NoConstraint)
174 return true;
Rafael Espindolae746e522016-09-21 18:33:44 +0000175 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000176 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000177 return Sec->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000178 });
Rafael Espindolae746e522016-09-21 18:33:44 +0000179 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
180 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000181}
182
George Rimar07171f22016-09-21 15:56:44 +0000183static void sortSections(InputSectionData **Begin, InputSectionData **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000184 SortSectionPolicy K) {
185 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000186 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000187}
188
Rafael Espindolad3190792016-09-16 15:10:23 +0000189// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000190template <class ELFT>
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000191void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000192 // Collects all sections that satisfy constraints of I
193 // and attach them to I.
194 for (SectionPattern &Pat : I->SectionPatterns) {
George Rimar07171f22016-09-21 15:56:44 +0000195 size_t SizeBefore = I->Sections.size();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000196
197 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
198 if (isDiscarded(S) || S->OutSec)
199 continue;
200
201 StringRef Filename;
202 if (elf::ObjectFile<ELFT> *F = S->getFile())
203 Filename = sys::path::filename(F->getName());
204
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000205 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
Rui Ueyama3ff27f42016-09-17 02:15:28 +0000206 continue;
Rui Ueyama4dc07be2016-09-17 02:23:40 +0000207
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000208 if (Pat.SectionPat.match(S->Name))
209 I->Sections.push_back(S);
Rui Ueyamaf91282e2016-11-03 17:57:38 +0000210 if (Pat.SectionPat.match("COMMON"))
Rafael Espindola0e090522016-10-26 00:54:03 +0000211 I->Sections.push_back(InputSection<ELFT>::CommonInputSection);
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);
240 S2->OutSec = (OutputSectionBase<ELFT> *)-1;
241 }
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) {
309 OutputSectionBase<ELFT> *OutSec;
310 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)
375 if (!isDiscarded(S) && !S->OutSec)
376 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>
384static void assignSectionSymbol(SymbolAssignment *Cmd,
385 OutputSectionBase<ELFT> *Sec,
Rafael Espindola498ed712016-10-31 14:44:41 +0000386 typename ELFT::uint Value) {
Eugene Leviantdb741e72016-09-07 07:08:43 +0000387 if (!Cmd->Sym)
388 return;
389
390 if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
391 Body->Section = Sec;
Rafael Espindola498ed712016-10-31 14:44:41 +0000392 Body->Value = Cmd->Expression(Value) - Sec->getVA();
Eugene Leviantdb741e72016-09-07 07:08:43 +0000393 return;
394 }
395 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
Rafael Espindola498ed712016-10-31 14:44:41 +0000396 Body->Value = Cmd->Expression(Value);
Eugene Leviantdb741e72016-09-07 07:08:43 +0000397}
398
Rafael Espindolaa940e532016-09-22 12:35:44 +0000399template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
400 return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
401}
402
Rafael Espindolad3190792016-09-16 15:10:23 +0000403template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
404 if (!AlreadyOutputIS.insert(S).second)
405 return;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000406 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000407
Rafael Espindolad3190792016-09-16 15:10:23 +0000408 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
409 Pos = alignTo(Pos, S->Alignment);
410 S->OutSecOff = Pos - CurOutSec->getVA();
411 Pos += S->getSize();
412
413 // Update output section size after adding each section. This is so that
414 // SIZEOF works correctly in the case below:
415 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
416 CurOutSec->setSize(Pos - CurOutSec->getVA());
417
Rafael Espindola7252ae52016-09-22 12:00:08 +0000418 if (IsTbss)
419 ThreadBssOffset = Pos - Dot;
420 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000421 Dot = Pos;
422}
423
424template <class ELFT> void LinkerScript<ELFT>::flush() {
Rafael Espindola65499b92016-09-23 20:10:47 +0000425 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
426 return;
427 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000428 for (InputSection<ELFT> *I : OutSec->Sections)
429 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000430 } else {
431 Dot += CurOutSec->getSize();
Eugene Leviant20889c52016-08-31 08:13:33 +0000432 }
433}
434
435template <class ELFT>
Rafael Espindolad3190792016-09-16 15:10:23 +0000436void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
437 if (CurOutSec == Sec)
438 return;
439 if (AlreadyOutputOS.count(Sec))
440 return;
441
442 flush();
443 CurOutSec = Sec;
444
445 Dot = alignTo(Dot, CurOutSec->getAlignment());
Rafael Espindolaa940e532016-09-22 12:35:44 +0000446 CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000447
448 // If neither AT nor AT> is specified for an allocatable section, the linker
449 // will set the LMA such that the difference between VMA and LMA for the
450 // section is the same as the preceding output section in the same region
451 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
452 CurOutSec->setLMAOffset(LMAOffset);
Rafael Espindolad3190792016-09-16 15:10:23 +0000453}
454
455template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
George Rimare38cbab2016-09-26 19:22:50 +0000456 // This handles the assignments to symbol or to a location counter (.)
Rafael Espindolad3190792016-09-16 15:10:23 +0000457 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
458 if (AssignCmd->Name == ".") {
459 // Update to location counter means update to section size.
460 Dot = AssignCmd->Expression(Dot);
461 CurOutSec->setSize(Dot - CurOutSec->getVA());
462 return;
463 }
Rafael Espindola498ed712016-10-31 14:44:41 +0000464 assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000465 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000466 }
George Rimare38cbab2016-09-26 19:22:50 +0000467
468 // Handle BYTE(), SHORT(), LONG(), or QUAD().
469 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
470 DataCmd->Offset = Dot - CurOutSec->getVA();
471 Dot += DataCmd->Size;
472 CurOutSec->setSize(Dot - CurOutSec->getVA());
473 return;
474 }
475
476 // It handles single input section description command,
477 // calculates and assigns the offsets for each section and also
478 // updates the output section size.
Rafael Espindolad3190792016-09-16 15:10:23 +0000479 auto &ICmd = cast<InputSectionDescription>(Base);
480 for (InputSectionData *ID : ICmd.Sections) {
481 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
482 switchTo(IB->OutSec);
483 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
484 output(I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000485 else
486 flush();
Eugene Leviantceabe802016-08-11 07:56:43 +0000487 }
488}
489
George Rimar8f66df92016-08-12 20:38:20 +0000490template <class ELFT>
George Rimara14b13d2016-09-07 10:46:07 +0000491static std::vector<OutputSectionBase<ELFT> *>
Eugene Leviant92577642016-10-10 11:23:12 +0000492findSections(StringRef Name,
Rafael Espindolad3190792016-09-16 15:10:23 +0000493 const std::vector<OutputSectionBase<ELFT> *> &Sections) {
George Rimara14b13d2016-09-07 10:46:07 +0000494 std::vector<OutputSectionBase<ELFT> *> Ret;
495 for (OutputSectionBase<ELFT> *Sec : Sections)
Eugene Leviant92577642016-10-10 11:23:12 +0000496 if (Sec->getName() == Name)
George Rimara14b13d2016-09-07 10:46:07 +0000497 Ret.push_back(Sec);
498 return Ret;
George Rimar8f66df92016-08-12 20:38:20 +0000499}
500
Rafael Espindolad3190792016-09-16 15:10:23 +0000501template <class ELFT>
502void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000503 if (Cmd->LMAExpr)
504 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000505 std::vector<OutputSectionBase<ELFT> *> Sections =
Eugene Leviant92577642016-10-10 11:23:12 +0000506 findSections(Cmd->Name, *OutputSections);
Rafael Espindolad3190792016-09-16 15:10:23 +0000507 if (Sections.empty())
508 return;
509 switchTo(Sections[0]);
Rafael Espindolad3190792016-09-16 15:10:23 +0000510 // Find the last section output location. We will output orphan sections
511 // there so that end symbols point to the correct location.
512 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
513 [](const std::unique_ptr<BaseCommand> &Cmd) {
514 return !isa<SymbolAssignment>(*Cmd);
515 })
516 .base();
517 for (auto I = Cmd->Commands.begin(); I != E; ++I)
518 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000519 for (OutputSectionBase<ELFT> *Base : Sections)
Rafael Espindolad3190792016-09-16 15:10:23 +0000520 switchTo(Base);
Rafael Espindola65499b92016-09-23 20:10:47 +0000521 flush();
George Rimarb31dd372016-09-19 13:27:31 +0000522 std::for_each(E, Cmd->Commands.end(),
523 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
Rafael Espindolad3190792016-09-16 15:10:23 +0000524}
525
Rafael Espindola9546fff2016-09-22 14:40:50 +0000526template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000527 // It is common practice to use very generic linker scripts. So for any
528 // given run some of the output sections in the script will be empty.
529 // We could create corresponding empty output sections, but that would
530 // clutter the output.
531 // We instead remove trivially empty sections. The bfd linker seems even
532 // more aggressive at removing them.
533 auto Pos = std::remove_if(
534 Opt.Commands.begin(), Opt.Commands.end(),
535 [&](const std::unique_ptr<BaseCommand> &Base) {
536 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
537 if (!Cmd)
538 return false;
539 std::vector<OutputSectionBase<ELFT> *> Secs =
Eugene Leviant92577642016-10-10 11:23:12 +0000540 findSections(Cmd->Name, *OutputSections);
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000541 if (!Secs.empty())
542 return false;
543 for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
544 if (!isa<InputSectionDescription>(I.get()))
545 return false;
546 return true;
547 });
548 Opt.Commands.erase(Pos, Opt.Commands.end());
549
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;
560 std::vector<OutputSectionBase<ELFT> *> Secs =
Eugene Leviant92577642016-10-10 11:23:12 +0000561 findSections(Cmd->Name, *OutputSections);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000562 if (!Secs.empty()) {
563 Flags = Secs[0]->getFlags();
564 Type = Secs[0]->getType();
565 continue;
566 }
567
Rui Ueyama95642b92016-11-01 23:09:07 +0000568 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000569 OutputSections->push_back(OutSec);
570 }
571}
572
Rafael Espindola15c57952016-09-22 18:05:49 +0000573// When placing orphan sections, we want to place them after symbol assignments
574// so that an orphan after
575// begin_foo = .;
576// foo : { *(foo) }
577// end_foo = .;
578// doesn't break the intended meaning of the begin/end symbols.
579// We don't want to go over sections since Writer<ELFT>::sortSections is the
580// one in charge of deciding the order of the sections.
581// We don't want to go over alignments, since doing so in
582// rx_sec : { *(rx_sec) }
583// . = ALIGN(0x1000);
584// /* The RW PT_LOAD starts here*/
585// rw_sec : { *(rw_sec) }
586// would mean that the RW PT_LOAD would become unaligned.
587static bool shouldSkip(const BaseCommand &Cmd) {
588 if (isa<OutputSectionCommand>(Cmd))
589 return false;
590 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
591 if (!Assign)
592 return true;
593 return Assign->Name != ".";
594}
595
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000596template <class ELFT>
597void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
George Rimar652852c2016-04-16 10:10:32 +0000598 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000599 // are not explicitly placed into the output file by the linker script.
600 // We place orphan sections at end of file.
601 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000602 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000603
604 // The OutputSections are already in the correct order.
605 // This loops creates or moves commands as needed so that they are in the
606 // correct order.
607 int CmdIndex = 0;
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000608 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000609 StringRef Name = Sec->getName();
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000610
611 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000612 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000613 auto CmdIter = Opt.Commands.begin() + CmdIndex;
614 auto E = Opt.Commands.end();
Rafael Espindola15c57952016-09-22 18:05:49 +0000615 while (CmdIter != E && shouldSkip(**CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000616 ++CmdIter;
617 ++CmdIndex;
618 }
619
620 auto Pos =
621 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
622 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
623 return Cmd && Cmd->Name == Name;
624 });
625 if (Pos == E) {
626 Opt.Commands.insert(CmdIter,
627 llvm::make_unique<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000628 ++CmdIndex;
629 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000630 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000631
632 // Continue from where we found it.
633 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000634 }
George Rimar652852c2016-04-16 10:10:32 +0000635
Rui Ueyama7c18c282016-04-18 21:00:40 +0000636 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000637 Dot = 0;
George Rimar652852c2016-04-16 10:10:32 +0000638
George Rimar076fe152016-07-21 06:43:01 +0000639 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
640 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000641 if (Cmd->Name == ".") {
642 Dot = Cmd->Expression(Dot);
643 } else if (Cmd->Sym) {
Rafael Espindolab0de56b2016-10-31 21:36:23 +0000644 assignSectionSymbol(Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0],
645 Dot);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000646 }
George Rimar652852c2016-04-16 10:10:32 +0000647 continue;
648 }
649
George Rimareefa7582016-08-04 09:29:31 +0000650 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
651 Cmd->Expression(Dot);
652 continue;
653 }
654
George Rimar076fe152016-07-21 06:43:01 +0000655 auto *Cmd = cast<OutputSectionCommand>(Base.get());
George Rimar652852c2016-04-16 10:10:32 +0000656
Rafael Espindolad3190792016-09-16 15:10:23 +0000657 if (Cmd->AddrExpr)
658 Dot = Cmd->AddrExpr(Dot);
George Rimar58e5c4d2016-07-25 08:29:46 +0000659
Rafael Espindolad3190792016-09-16 15:10:23 +0000660 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000661 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000662
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000663 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
664 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
665 if (Sec->getFlags() & SHF_ALLOC)
666 MinVA = std::min(MinVA, Sec->getVA());
667 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000668 Sec->setVA(0);
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000669 }
670
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000671 uintX_t HeaderSize = getHeaderSize();
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000672 auto FirstPTLoad =
673 std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
674 return E.H.p_type == PT_LOAD;
675 });
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000676
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000677 if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
Eugene Leviantdb35fdf2016-10-20 09:39:09 +0000678 // If linker script specifies program headers and first PT_LOAD doesn't
679 // have both PHDRS and FILEHDR attributes then do nothing
680 if (!Opt.PhdrsCommands.empty()) {
681 size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
682 if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
683 !Opt.PhdrsCommands[SegNum].HasFilehdr)
684 return;
685 }
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000686 // ELF and Program headers need to be right before the first section in
687 // memory. Set their addresses accordingly.
688 MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
689 Out<ELFT>::ElfHeader->setVA(MinVA);
690 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
691 FirstPTLoad->First = Out<ELFT>::ElfHeader;
692 if (!FirstPTLoad->Last)
693 FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000694 } else if (!FirstPTLoad->First) {
Rui Ueyamab224c0482016-10-10 18:10:01 +0000695 // Sometimes the very first PT_LOAD segment can be empty.
Eugene Leviantcd8eaf82016-10-10 15:09:44 +0000696 // This happens if (all conditions met):
697 // - Linker script is used
698 // - First section in ELF image is not RO
699 // - Not enough space for program headers.
700 // The code below removes empty PT_LOAD segment and updates
701 // program headers size.
702 Phdrs.erase(FirstPTLoad);
703 Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
704 Phdrs.size());
Rafael Espindola6d91fce2016-09-29 18:50:34 +0000705 }
George Rimar652852c2016-04-16 10:10:32 +0000706}
707
Rui Ueyama464daad2016-08-22 04:55:20 +0000708// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyama07320e42016-04-20 20:13:41 +0000709template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000710std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000711 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000712
Rui Ueyama464daad2016-08-22 04:55:20 +0000713 // Process PHDRS and FILEHDR keywords because they are not
714 // real output sections and cannot be added in the following loop.
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000715 std::vector<size_t> DefPhdrIds;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000716 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000717 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
718 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000719
720 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000721 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000722 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000723 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000724
725 if (Cmd.LMAExpr) {
726 Phdr.H.p_paddr = Cmd.LMAExpr(0);
727 Phdr.HasLMA = true;
728 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000729
730 // If output section command doesn't specify any segments,
731 // and we haven't previously assigned any section to segment,
732 // then we simply assign section to the very first load segment.
733 // Below is an example of such linker script:
734 // PHDRS { seg PT_LOAD; }
735 // SECTIONS { .aaa : { *(.aaa) } }
736 if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
737 DefPhdrIds.push_back(Ret.size() - 1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000738 }
739
Rui Ueyama464daad2016-08-22 04:55:20 +0000740 // Add output sections to program headers.
Rui Ueyama464daad2016-08-22 04:55:20 +0000741 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000742 if (!(Sec->getFlags() & SHF_ALLOC))
743 break;
744
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000745 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000746 if (PhdrIds.empty())
747 PhdrIds = std::move(DefPhdrIds);
748
749 // Assign headers specified by linker script
750 for (size_t Id : PhdrIds) {
751 Ret[Id].add(Sec);
752 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
753 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000754 }
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000755 DefPhdrIds = std::move(PhdrIds);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000756 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000757 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000758}
759
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000760template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
761 // Ignore .interp section in case we have PHDRS specification
762 // and PT_INTERP isn't listed.
763 return !Opt.PhdrsCommands.empty() &&
764 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
765 return Cmd.Type == PT_INTERP;
766 }) == Opt.PhdrsCommands.end();
767}
768
Eugene Leviantbbe38602016-07-19 09:25:43 +0000769template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000770ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000771 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
772 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
773 if (Cmd->Name == Name)
774 return Cmd->Filler;
775 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000776}
777
George Rimare38cbab2016-09-26 19:22:50 +0000778template <class ELFT>
779static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
780 const endianness E = ELFT::TargetEndianness;
781
782 switch (Size) {
783 case 1:
784 *Buf = (uint8_t)Data;
785 break;
786 case 2:
787 write16<E>(Buf, Data);
788 break;
789 case 4:
790 write32<E>(Buf, Data);
791 break;
792 case 8:
793 write64<E>(Buf, Data);
794 break;
795 default:
796 llvm_unreachable("unsupported Size argument");
797 }
798}
799
800template <class ELFT>
801void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
802 int I = getSectionIndex(Name);
803 if (I == INT_MAX)
804 return;
805
806 OutputSectionCommand *Cmd =
807 dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
808 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
809 if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
810 writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
811}
812
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000813template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
George Rimar8ceadb32016-08-17 07:44:19 +0000814 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
815 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000816 if (Cmd->LMAExpr && Cmd->Name == Name)
817 return true;
818 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000819}
820
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000821// Returns the index of the given section name in linker script
822// SECTIONS commands. Sections are laid out as the same order as they
823// were in the script. If a given name did not appear in the script,
824// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000825template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000826 int I = 0;
827 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
828 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
829 if (Cmd->Name == Name)
830 return I;
831 ++I;
832 }
833 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000834}
835
Eugene Leviantbbe38602016-07-19 09:25:43 +0000836template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
837 return !Opt.PhdrsCommands.empty();
838}
839
George Rimar9e694502016-07-29 16:18:47 +0000840template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000841uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
George Rimar96659df2016-08-30 09:54:01 +0000842 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
843 if (Sec->getName() == Name)
844 return Sec->getVA();
845 error("undefined section " + Name);
846 return 0;
847}
848
849template <class ELFT>
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000850uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
851 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
852 if (Sec->getName() == Name)
853 return Sec->getLMA();
854 error("undefined section " + Name);
855 return 0;
856}
857
858template <class ELFT>
George Rimar884e7862016-09-08 08:19:13 +0000859uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
George Rimar9e694502016-07-29 16:18:47 +0000860 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
861 if (Sec->getName() == Name)
862 return Sec->getSize();
863 error("undefined section " + Name);
864 return 0;
865}
866
Eugene Leviant36fac7f2016-09-08 09:08:30 +0000867template <class ELFT>
868uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
869 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
870 if (Sec->getName() == Name)
871 return Sec->getAlignment();
872 error("undefined section " + Name);
873 return 0;
874}
875
George Rimar884e7862016-09-08 08:19:13 +0000876template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
Rafael Espindola0d4b6d52016-09-22 16:47:21 +0000877 return elf::getHeaderSize<ELFT>();
George Rimare32a3592016-08-10 07:59:34 +0000878}
879
George Rimar884e7862016-09-08 08:19:13 +0000880template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
881 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
882 return B->getVA<ELFT>();
883 error("symbol not found: " + S);
884 return 0;
885}
886
George Rimarf34f45f2016-09-23 13:17:23 +0000887template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
888 return Symtab<ELFT>::X->find(S) != nullptr;
889}
890
Rafael Espindola2f831dc2016-10-31 19:56:37 +0000891template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
892 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
893 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
894 return DR && !DR->Section;
895}
896
Eugene Leviantbbe38602016-07-19 09:25:43 +0000897// Returns indices of ELF headers containing specific section, identified
898// by Name. Each index is a zero based number of ELF header listed within
899// PHDRS {} script block.
900template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000901std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000902 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
903 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000904 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000905 continue;
906
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000907 std::vector<size_t> Ret;
908 for (StringRef PhdrName : Cmd->Phdrs)
909 Ret.push_back(getPhdrIndex(PhdrName));
910 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000911 }
George Rimar31d842f2016-07-20 16:43:03 +0000912 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000913}
914
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000915template <class ELFT>
916size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
917 size_t I = 0;
918 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
919 if (Cmd.Name == PhdrName)
920 return I;
921 ++I;
922 }
923 error("section header '" + PhdrName + "' is not listed in PHDRS");
924 return 0;
925}
926
Rui Ueyama07320e42016-04-20 20:13:41 +0000927class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000928 typedef void (ScriptParser::*Handler)();
929
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000930public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000931 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000932
George Rimar20b65982016-08-31 09:08:26 +0000933 void readLinkerScript();
934 void readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000935
936private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000937 void addFile(StringRef Path);
938
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000939 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000940 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000941 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000942 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000943 void readInclude();
Rui Ueyamaee592822015-10-07 00:25:09 +0000944 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000945 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000946 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000947 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000948 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000949 void readSections();
Rui Ueyama95769b42016-08-31 20:03:54 +0000950 void readVersion();
951 void readVersionScriptCommand();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000952
Rui Ueyama113cdec2016-07-24 23:05:57 +0000953 SymbolAssignment *readAssignment(StringRef Name);
George Rimare38cbab2016-09-26 19:22:50 +0000954 BytesDataCommand *readBytesDataCommand(StringRef Tok);
George Rimarff1f29e2016-09-06 13:51:57 +0000955 std::vector<uint8_t> readFill();
Rui Ueyama10416562016-08-04 02:03:27 +0000956 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
George Rimarff1f29e2016-09-06 13:51:57 +0000957 std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000958 std::vector<StringRef> readOutputSectionPhdrs();
George Rimara2496cb2016-08-30 09:46:59 +0000959 InputSectionDescription *readInputSectionDescription(StringRef Tok);
Eugene Leviantdb688452016-11-03 10:54:58 +0000960 StringMatcher readFilePatterns();
George Rimar07171f22016-09-21 15:56:44 +0000961 std::vector<SectionPattern> readInputSectionsList();
George Rimara2496cb2016-08-30 09:46:59 +0000962 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000963 unsigned readPhdrType();
George Rimarbe394db2016-09-16 20:21:55 +0000964 SortSectionPolicy readSortKind();
Petr Hoseka35e39c2016-08-16 01:11:16 +0000965 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
Rafael Espindolac96da112016-11-01 11:30:45 +0000966 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
George Rimar03fc0102016-07-28 07:18:23 +0000967 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000968 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000969
970 Expr readExpr();
971 Expr readExpr1(Expr Lhs, int MinPrec);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000972 StringRef readParenLiteral();
Rui Ueyama708019c2016-07-24 18:19:40 +0000973 Expr readPrimary();
974 Expr readTernary(Expr Cond);
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +0000975 Expr readParenExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000976
George Rimar20b65982016-08-31 09:08:26 +0000977 // For parsing version script.
978 void readExtern(std::vector<SymbolVersion> *Globals);
Rui Ueyama95769b42016-08-31 20:03:54 +0000979 void readVersionDeclaration(StringRef VerStr);
George Rimar20b65982016-08-31 09:08:26 +0000980 void readGlobal(StringRef VerStr);
981 void readLocal();
982
Rui Ueyama07320e42016-04-20 20:13:41 +0000983 ScriptConfiguration &Opt = *ScriptConfig;
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000984 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000985};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000986
George Rimar20b65982016-08-31 09:08:26 +0000987void ScriptParser::readVersionScript() {
Rui Ueyama95769b42016-08-31 20:03:54 +0000988 readVersionScriptCommand();
989 if (!atEOF())
990 setError("EOF expected, but got " + next());
991}
992
993void ScriptParser::readVersionScriptCommand() {
Rui Ueyama83043f22016-10-17 16:01:53 +0000994 if (consume("{")) {
Rui Ueyama95769b42016-08-31 20:03:54 +0000995 readVersionDeclaration("");
George Rimar20b65982016-08-31 09:08:26 +0000996 return;
997 }
998
Rui Ueyama95769b42016-08-31 20:03:54 +0000999 while (!atEOF() && !Error && peek() != "}") {
George Rimar20b65982016-08-31 09:08:26 +00001000 StringRef VerStr = next();
1001 if (VerStr == "{") {
Rui Ueyama95769b42016-08-31 20:03:54 +00001002 setError("anonymous version definition is used in "
1003 "combination with other version definitions");
George Rimar20b65982016-08-31 09:08:26 +00001004 return;
1005 }
1006 expect("{");
Rui Ueyama95769b42016-08-31 20:03:54 +00001007 readVersionDeclaration(VerStr);
George Rimar20b65982016-08-31 09:08:26 +00001008 }
1009}
1010
Rui Ueyama95769b42016-08-31 20:03:54 +00001011void ScriptParser::readVersion() {
1012 expect("{");
1013 readVersionScriptCommand();
1014 expect("}");
1015}
1016
George Rimar20b65982016-08-31 09:08:26 +00001017void ScriptParser::readLinkerScript() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001018 while (!atEOF()) {
1019 StringRef Tok = next();
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001020 if (Tok == ";")
1021 continue;
1022
Eugene Leviant20d03192016-09-16 15:30:47 +00001023 if (Tok == "ASSERT") {
1024 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1025 } else if (Tok == "ENTRY") {
Rui Ueyamaa27eecc2016-09-02 18:52:41 +00001026 readEntry();
1027 } else if (Tok == "EXTERN") {
1028 readExtern();
1029 } else if (Tok == "GROUP" || Tok == "INPUT") {
1030 readGroup();
1031 } else if (Tok == "INCLUDE") {
1032 readInclude();
1033 } else if (Tok == "OUTPUT") {
1034 readOutput();
1035 } else if (Tok == "OUTPUT_ARCH") {
1036 readOutputArch();
1037 } else if (Tok == "OUTPUT_FORMAT") {
1038 readOutputFormat();
1039 } else if (Tok == "PHDRS") {
1040 readPhdrs();
1041 } else if (Tok == "SEARCH_DIR") {
1042 readSearchDir();
1043 } else if (Tok == "SECTIONS") {
1044 readSections();
1045 } else if (Tok == "VERSION") {
1046 readVersion();
Rafael Espindolac96da112016-11-01 11:30:45 +00001047 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
Eugene Leviant20d03192016-09-16 15:30:47 +00001048 Opt.Commands.emplace_back(Cmd);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001049 } else {
George Rimar57610422016-03-11 14:43:02 +00001050 setError("unknown directive: " + Tok);
Petr Hoseke5d3ca52016-08-31 15:31:17 +00001051 }
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001052 }
1053}
1054
Rui Ueyama717677a2016-02-11 21:17:59 +00001055void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001056 if (IsUnderSysroot && S.startswith("/")) {
Justin Bogner5af16872016-10-17 06:08:48 +00001057 SmallString<128> PathData;
1058 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001059 if (sys::fs::exists(Path)) {
Justin Bogner5af16872016-10-17 06:08:48 +00001060 Driver->addFile(Saver.save(Path));
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001061 return;
1062 }
1063 }
1064
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +00001065 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +00001066 Driver->addFile(S);
1067 } else if (S.startswith("=")) {
1068 if (Config->Sysroot.empty())
1069 Driver->addFile(S.substr(1));
1070 else
1071 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1072 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +00001073 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +00001074 } else if (sys::fs::exists(S)) {
1075 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +00001076 } else {
1077 std::string Path = findFromSearchPaths(S);
1078 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +00001079 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001080 else
1081 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +00001082 }
1083}
1084
Rui Ueyama717677a2016-02-11 21:17:59 +00001085void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001086 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +00001087 bool Orig = Config->AsNeeded;
1088 Config->AsNeeded = true;
Rui Ueyama83043f22016-10-17 16:01:53 +00001089 while (!Error && !consume(")"))
George Rimarcd574a52016-09-09 14:35:36 +00001090 addFile(unquote(next()));
Rui Ueyama35da9b62015-10-11 20:59:12 +00001091 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001092}
1093
Rui Ueyama717677a2016-02-11 21:17:59 +00001094void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +00001095 // -e <symbol> takes predecence over ENTRY(<symbol>).
1096 expect("(");
1097 StringRef Tok = next();
1098 if (Config->Entry.empty())
1099 Config->Entry = Tok;
1100 expect(")");
1101}
1102
Rui Ueyama717677a2016-02-11 21:17:59 +00001103void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +00001104 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001105 while (!Error && !consume(")"))
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001106 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +00001107}
1108
Rui Ueyama717677a2016-02-11 21:17:59 +00001109void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001110 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001111 while (!Error && !consume(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001112 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001113 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001114 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +00001115 else
George Rimarcd574a52016-09-09 14:35:36 +00001116 addFile(unquote(Tok));
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001117 }
1118}
1119
Rui Ueyama717677a2016-02-11 21:17:59 +00001120void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001121 StringRef Tok = next();
George Rimarcd574a52016-09-09 14:35:36 +00001122 auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
Rui Ueyama025d59b2016-02-02 20:27:59 +00001123 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +00001124 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001125 return;
1126 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001127 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +00001128 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1129 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001130 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +00001131}
1132
Rui Ueyama717677a2016-02-11 21:17:59 +00001133void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +00001134 // -o <file> takes predecence over OUTPUT(<file>).
1135 expect("(");
1136 StringRef Tok = next();
1137 if (Config->OutputFile.empty())
George Rimarcd574a52016-09-09 14:35:36 +00001138 Config->OutputFile = unquote(Tok);
Rui Ueyamaee592822015-10-07 00:25:09 +00001139 expect(")");
1140}
1141
Rui Ueyama717677a2016-02-11 21:17:59 +00001142void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +00001143 // Error checking only for now.
1144 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001145 skip();
Davide Italiano9159ce92015-10-12 21:50:08 +00001146 expect(")");
1147}
1148
Rui Ueyama717677a2016-02-11 21:17:59 +00001149void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001150 // Error checking only for now.
1151 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001152 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001153 StringRef Tok = next();
1154 if (Tok == ")")
George Rimar6c55f0e2016-09-08 08:20:30 +00001155 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +00001156 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +00001157 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +00001158 return;
1159 }
Justin Bogner5424e7c2016-10-17 06:21:13 +00001160 skip();
Davide Italiano6836c612015-10-12 21:08:41 +00001161 expect(",");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001162 skip();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001163 expect(")");
1164}
1165
Eugene Leviantbbe38602016-07-19 09:25:43 +00001166void ScriptParser::readPhdrs() {
1167 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001168 while (!Error && !consume("}")) {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001169 StringRef Tok = next();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001170 Opt.PhdrsCommands.push_back(
1171 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
Eugene Leviantbbe38602016-07-19 09:25:43 +00001172 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1173
1174 PhdrCmd.Type = readPhdrType();
1175 do {
1176 Tok = next();
1177 if (Tok == ";")
1178 break;
1179 if (Tok == "FILEHDR")
1180 PhdrCmd.HasFilehdr = true;
1181 else if (Tok == "PHDRS")
1182 PhdrCmd.HasPhdrs = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +00001183 else if (Tok == "AT")
1184 PhdrCmd.LMAExpr = readParenExpr();
Eugene Leviant865bf862016-07-21 10:43:25 +00001185 else if (Tok == "FLAGS") {
1186 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +00001187 // Passing 0 for the value of dot is a bit of a hack. It means that
1188 // we accept expressions like ".|1".
1189 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +00001190 expect(")");
1191 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +00001192 setError("unexpected header attribute: " + Tok);
1193 } while (!Error);
1194 }
1195}
1196
Rui Ueyama717677a2016-02-11 21:17:59 +00001197void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +00001198 expect("(");
Rui Ueyama86c5fb82016-09-08 23:26:54 +00001199 StringRef Tok = next();
Rui Ueyama6c7ad132016-09-02 19:20:33 +00001200 if (!Config->Nostdlib)
George Rimarcd574a52016-09-09 14:35:36 +00001201 Config->SearchPaths.push_back(unquote(Tok));
Davide Italiano68a39a62015-10-08 17:51:41 +00001202 expect(")");
1203}
1204
Rui Ueyama717677a2016-02-11 21:17:59 +00001205void ScriptParser::readSections() {
Eugene Leviante05336ff2016-09-14 08:32:36 +00001206 Opt.HasSections = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001207 expect("{");
Rui Ueyama83043f22016-10-17 16:01:53 +00001208 while (!Error && !consume("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +00001209 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001210 BaseCommand *Cmd = readProvideOrAssignment(Tok);
Eugene Leviantceabe802016-08-11 07:56:43 +00001211 if (!Cmd) {
1212 if (Tok == "ASSERT")
1213 Cmd = new AssertCommand(readAssert());
1214 else
1215 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +00001216 }
Rui Ueyama10416562016-08-04 02:03:27 +00001217 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +00001218 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001219}
1220
Rui Ueyama708019c2016-07-24 18:19:40 +00001221static int precedence(StringRef Op) {
1222 return StringSwitch<int>(Op)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001223 .Cases("*", "/", 5)
1224 .Cases("+", "-", 4)
1225 .Cases("<<", ">>", 3)
Rui Ueyama9c4ac5f2016-09-23 22:22:34 +00001226 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
Rui Ueyama0120e3f2016-09-23 18:06:51 +00001227 .Cases("&", "|", 1)
Rui Ueyama708019c2016-07-24 18:19:40 +00001228 .Default(-1);
1229}
1230
Eugene Leviantdb688452016-11-03 10:54:58 +00001231StringMatcher ScriptParser::readFilePatterns() {
Rui Ueyama10416562016-08-04 02:03:27 +00001232 std::vector<StringRef> V;
Rui Ueyama83043f22016-10-17 16:01:53 +00001233 while (!Error && !consume(")"))
Rui Ueyama10416562016-08-04 02:03:27 +00001234 V.push_back(next());
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001235 return StringMatcher(V);
George Rimar0702c4e2016-07-29 15:32:46 +00001236}
1237
George Rimarbe394db2016-09-16 20:21:55 +00001238SortSectionPolicy ScriptParser::readSortKind() {
Rui Ueyama83043f22016-10-17 16:01:53 +00001239 if (consume("SORT") || consume("SORT_BY_NAME"))
George Rimarbe394db2016-09-16 20:21:55 +00001240 return SortSectionPolicy::Name;
Rui Ueyama83043f22016-10-17 16:01:53 +00001241 if (consume("SORT_BY_ALIGNMENT"))
George Rimarbe394db2016-09-16 20:21:55 +00001242 return SortSectionPolicy::Alignment;
Rui Ueyama83043f22016-10-17 16:01:53 +00001243 if (consume("SORT_BY_INIT_PRIORITY"))
George Rimarbe394db2016-09-16 20:21:55 +00001244 return SortSectionPolicy::Priority;
Rui Ueyama83043f22016-10-17 16:01:53 +00001245 if (consume("SORT_NONE"))
Rui Ueyamab2a0abd2016-09-16 21:14:55 +00001246 return SortSectionPolicy::None;
1247 return SortSectionPolicy::Default;
George Rimarbe394db2016-09-16 20:21:55 +00001248}
1249
George Rimar395281c2016-09-16 17:42:10 +00001250// Method reads a list of sequence of excluded files and section globs given in
1251// a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1252// Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
George Rimaraf03be12016-09-17 19:17:25 +00001253// The semantics of that is next:
1254// * Include .foo.1 from every file.
1255// * Include .foo.2 from every file but a.o
1256// * Include .foo.3 from every file but b.o
George Rimar07171f22016-09-21 15:56:44 +00001257std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1258 std::vector<SectionPattern> Ret;
George Rimar601e9892016-09-21 08:53:21 +00001259 while (!Error && peek() != ")") {
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001260 StringMatcher ExcludeFilePat;
Rui Ueyama83043f22016-10-17 16:01:53 +00001261 if (consume("EXCLUDE_FILE")) {
George Rimar395281c2016-09-16 17:42:10 +00001262 expect("(");
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001263 ExcludeFilePat = readFilePatterns();
George Rimar395281c2016-09-16 17:42:10 +00001264 }
1265
George Rimar601e9892016-09-21 08:53:21 +00001266 std::vector<StringRef> V;
1267 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1268 V.push_back(next());
1269
1270 if (!V.empty())
Rui Ueyamaf91282e2016-11-03 17:57:38 +00001271 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
George Rimar601e9892016-09-21 08:53:21 +00001272 else
1273 setError("section pattern is expected");
George Rimar395281c2016-09-16 17:42:10 +00001274 }
George Rimar07171f22016-09-21 15:56:44 +00001275 return Ret;
George Rimar395281c2016-09-16 17:42:10 +00001276}
1277
George Rimar07171f22016-09-21 15:56:44 +00001278// Section pattern grammar can have complex expressions, for example:
1279// *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1280// Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1281// commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1282// This methods handles wrapping sequences of excluded files and section globs
1283// into SORT() if that needed and reads them all.
George Rimara2496cb2016-08-30 09:46:59 +00001284InputSectionDescription *
1285ScriptParser::readInputSectionRules(StringRef FilePattern) {
George Rimarc91930a2016-09-02 21:17:20 +00001286 auto *Cmd = new InputSectionDescription(FilePattern);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001287 expect("(");
Rui Ueyama83043f22016-10-17 16:01:53 +00001288 while (!HasError && !consume(")")) {
George Rimar07171f22016-09-21 15:56:44 +00001289 SortSectionPolicy Outer = readSortKind();
1290 SortSectionPolicy Inner = SortSectionPolicy::Default;
1291 std::vector<SectionPattern> V;
1292 if (Outer != SortSectionPolicy::Default) {
George Rimar350ece42016-08-03 08:35:59 +00001293 expect("(");
George Rimar07171f22016-09-21 15:56:44 +00001294 Inner = readSortKind();
1295 if (Inner != SortSectionPolicy::Default) {
1296 expect("(");
1297 V = readInputSectionsList();
1298 expect(")");
1299 } else {
1300 V = readInputSectionsList();
1301 }
George Rimar350ece42016-08-03 08:35:59 +00001302 expect(")");
1303 } else {
George Rimar07171f22016-09-21 15:56:44 +00001304 V = readInputSectionsList();
George Rimar350ece42016-08-03 08:35:59 +00001305 }
George Rimar0702c4e2016-07-29 15:32:46 +00001306
George Rimar07171f22016-09-21 15:56:44 +00001307 for (SectionPattern &Pat : V) {
1308 Pat.SortInner = Inner;
1309 Pat.SortOuter = Outer;
1310 }
1311
1312 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1313 }
Rui Ueyama10416562016-08-04 02:03:27 +00001314 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +00001315}
1316
George Rimara2496cb2016-08-30 09:46:59 +00001317InputSectionDescription *
1318ScriptParser::readInputSectionDescription(StringRef Tok) {
George Rimar06598002016-07-28 21:51:30 +00001319 // Input section wildcard can be surrounded by KEEP.
1320 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
George Rimara2496cb2016-08-30 09:46:59 +00001321 if (Tok == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +00001322 expect("(");
George Rimara2496cb2016-08-30 09:46:59 +00001323 StringRef FilePattern = next();
1324 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
George Rimar06598002016-07-28 21:51:30 +00001325 expect(")");
Eugene Leviantcf43f172016-10-05 09:36:59 +00001326 Opt.KeptSections.push_back(Cmd);
Rui Ueyama10416562016-08-04 02:03:27 +00001327 return Cmd;
George Rimar06598002016-07-28 21:51:30 +00001328 }
George Rimara2496cb2016-08-30 09:46:59 +00001329 return readInputSectionRules(Tok);
Davide Italiano0ed42b02016-07-25 21:47:13 +00001330}
1331
George Rimar03fc0102016-07-28 07:18:23 +00001332void ScriptParser::readSort() {
1333 expect("(");
1334 expect("CONSTRUCTORS");
1335 expect(")");
1336}
1337
George Rimareefa7582016-08-04 09:29:31 +00001338Expr ScriptParser::readAssert() {
1339 expect("(");
1340 Expr E = readExpr();
1341 expect(",");
George Rimarcd574a52016-09-09 14:35:36 +00001342 StringRef Msg = unquote(next());
George Rimareefa7582016-08-04 09:29:31 +00001343 expect(")");
1344 return [=](uint64_t Dot) {
1345 uint64_t V = E(Dot);
1346 if (!V)
1347 error(Msg);
1348 return V;
1349 };
1350}
1351
Rui Ueyama25150e82016-09-06 17:46:43 +00001352// Reads a FILL(expr) command. We handle the FILL command as an
1353// alias for =fillexp section attribute, which is different from
1354// what GNU linkers do.
1355// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
George Rimarff1f29e2016-09-06 13:51:57 +00001356std::vector<uint8_t> ScriptParser::readFill() {
1357 expect("(");
1358 std::vector<uint8_t> V = readOutputSectionFiller(next());
1359 expect(")");
1360 expect(";");
1361 return V;
1362}
1363
Rui Ueyama10416562016-08-04 02:03:27 +00001364OutputSectionCommand *
1365ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +00001366 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +00001367
1368 // Read an address expression.
1369 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1370 if (peek() != ":")
1371 Cmd->AddrExpr = readExpr();
1372
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001373 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +00001374
Rui Ueyama83043f22016-10-17 16:01:53 +00001375 if (consume("AT"))
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001376 Cmd->LMAExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001377 if (consume("ALIGN"))
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001378 Cmd->AlignExpr = readParenExpr();
Rui Ueyama83043f22016-10-17 16:01:53 +00001379 if (consume("SUBALIGN"))
George Rimardb24d9c2016-08-19 15:18:23 +00001380 Cmd->SubalignExpr = readParenExpr();
George Rimar630c6172016-07-26 18:06:29 +00001381
Davide Italiano246f6812016-07-22 03:36:24 +00001382 // Parse constraints.
Rui Ueyama83043f22016-10-17 16:01:53 +00001383 if (consume("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001384 Cmd->Constraint = ConstraintKind::ReadOnly;
Rui Ueyama83043f22016-10-17 16:01:53 +00001385 if (consume("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +00001386 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001387 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001388
Rui Ueyama83043f22016-10-17 16:01:53 +00001389 while (!Error && !consume("}")) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001390 StringRef Tok = next();
Rafael Espindolac96da112016-11-01 11:30:45 +00001391 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
Eugene Leviantceabe802016-08-11 07:56:43 +00001392 Cmd->Commands.emplace_back(Assignment);
George Rimare38cbab2016-09-26 19:22:50 +00001393 else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1394 Cmd->Commands.emplace_back(Data);
George Rimarff1f29e2016-09-06 13:51:57 +00001395 else if (Tok == "FILL")
1396 Cmd->Filler = readFill();
Eugene Leviantceabe802016-08-11 07:56:43 +00001397 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +00001398 readSort();
George Rimara2496cb2016-08-30 09:46:59 +00001399 else if (peek() == "(")
1400 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
Eugene Leviantceabe802016-08-11 07:56:43 +00001401 else
1402 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001403 }
George Rimar076fe152016-07-21 06:43:01 +00001404 Cmd->Phdrs = readOutputSectionPhdrs();
George Rimar4ebc5622016-09-23 13:29:20 +00001405
Rui Ueyama83043f22016-10-17 16:01:53 +00001406 if (consume("="))
George Rimar4ebc5622016-09-23 13:29:20 +00001407 Cmd->Filler = readOutputSectionFiller(next());
1408 else if (peek().startswith("="))
George Rimarff1f29e2016-09-06 13:51:57 +00001409 Cmd->Filler = readOutputSectionFiller(next().drop_front());
George Rimar4ebc5622016-09-23 13:29:20 +00001410
Rui Ueyama10416562016-08-04 02:03:27 +00001411 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001412}
Rui Ueyama8ec77e62016-04-21 22:00:51 +00001413
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001414// Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1415// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1416//
1417// ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1418// hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1419// as 32-bit big-endian values. We will do the same as ld.gold does
1420// because it's simpler than what ld.bfd does.
George Rimarff1f29e2016-09-06 13:51:57 +00001421std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001422 uint32_t V;
George Rimarff1f29e2016-09-06 13:51:57 +00001423 if (Tok.getAsInteger(0, V)) {
Rui Ueyama965827d2016-08-03 23:25:15 +00001424 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +00001425 return {};
George Rimare2ee72b2016-02-26 14:48:31 +00001426 }
Rui Ueyama2c8f1f02016-08-29 22:01:21 +00001427 return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001428}
1429
Petr Hoseka35e39c2016-08-16 01:11:16 +00001430SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +00001431 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +00001432 SymbolAssignment *Cmd = readAssignment(next());
Petr Hoseka35e39c2016-08-16 01:11:16 +00001433 Cmd->Provide = Provide;
Rui Ueyama174e0a12016-07-29 00:29:25 +00001434 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001435 expect(")");
1436 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +00001437 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +00001438}
1439
Rafael Espindolac96da112016-11-01 11:30:45 +00001440SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
Eugene Leviantceabe802016-08-11 07:56:43 +00001441 SymbolAssignment *Cmd = nullptr;
1442 if (peek() == "=" || peek() == "+=") {
1443 Cmd = readAssignment(Tok);
1444 expect(";");
1445 } else if (Tok == "PROVIDE") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001446 Cmd = readProvideHidden(true, false);
1447 } else if (Tok == "HIDDEN") {
1448 Cmd = readProvideHidden(false, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001449 } else if (Tok == "PROVIDE_HIDDEN") {
Petr Hoseka35e39c2016-08-16 01:11:16 +00001450 Cmd = readProvideHidden(true, true);
Eugene Leviantceabe802016-08-11 07:56:43 +00001451 }
1452 return Cmd;
1453}
1454
George Rimar30835ea2016-07-28 21:08:56 +00001455static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1456 if (S == ".")
1457 return Dot;
George Rimar884e7862016-09-08 08:19:13 +00001458 return ScriptBase->getSymbolValue(S);
George Rimare32a3592016-08-10 07:59:34 +00001459}
1460
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001461static bool isAbsolute(StringRef S) {
1462 if (S == ".")
1463 return false;
1464 return ScriptBase->isAbsolute(S);
1465}
1466
George Rimar30835ea2016-07-28 21:08:56 +00001467SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1468 StringRef Op = next();
Eugene Leviantdb741e72016-09-07 07:08:43 +00001469 Expr E;
George Rimar30835ea2016-07-28 21:08:56 +00001470 assert(Op == "=" || Op == "+=");
Rui Ueyama83043f22016-10-17 16:01:53 +00001471 if (consume("ABSOLUTE")) {
Rui Ueyama7c1381a2016-10-19 23:11:21 +00001472 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1473 // Call readExpr1 to read the whole expression.
1474 E = readExpr1(readParenExpr(), 0);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001475 E.IsAbsolute = []() { return true; };
Eugene Leviantdb741e72016-09-07 07:08:43 +00001476 } else {
1477 E = readExpr();
1478 }
George Rimar30835ea2016-07-28 21:08:56 +00001479 if (Op == "+=")
1480 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rafael Espindolaf6613932016-10-31 17:43:38 +00001481 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001482}
1483
1484// This is an operator-precedence parser to parse a linker
1485// script expression.
1486Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1487
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001488static Expr combine(StringRef Op, Expr L, Expr R) {
1489 if (Op == "*")
1490 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1491 if (Op == "/") {
1492 return [=](uint64_t Dot) -> uint64_t {
1493 uint64_t RHS = R(Dot);
1494 if (RHS == 0) {
1495 error("division by zero");
1496 return 0;
1497 }
1498 return L(Dot) / RHS;
1499 };
1500 }
1501 if (Op == "+")
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001502 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1503 [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001504 if (Op == "-")
1505 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
George Rimarc8ccd1f2016-09-23 13:13:55 +00001506 if (Op == "<<")
1507 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1508 if (Op == ">>")
1509 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001510 if (Op == "<")
1511 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1512 if (Op == ">")
1513 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1514 if (Op == ">=")
1515 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1516 if (Op == "<=")
1517 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1518 if (Op == "==")
1519 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1520 if (Op == "!=")
1521 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1522 if (Op == "&")
1523 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
Rafael Espindolacc3dd622016-08-22 21:33:35 +00001524 if (Op == "|")
1525 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001526 llvm_unreachable("invalid operator");
1527}
1528
Rui Ueyama708019c2016-07-24 18:19:40 +00001529// This is a part of the operator-precedence parser. This function
1530// assumes that the remaining token stream starts with an operator.
1531Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1532 while (!atEOF() && !Error) {
1533 // Read an operator and an expression.
1534 StringRef Op1 = peek();
1535 if (Op1 == "?")
1536 return readTernary(Lhs);
1537 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001538 break;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001539 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001540 Expr Rhs = readPrimary();
1541
1542 // Evaluate the remaining part of the expression first if the
1543 // next operator has greater precedence than the previous one.
1544 // For example, if we have read "+" and "3", and if the next
1545 // operator is "*", then we'll evaluate 3 * ... part first.
1546 while (!atEOF()) {
1547 StringRef Op2 = peek();
1548 if (precedence(Op2) <= precedence(Op1))
1549 break;
1550 Rhs = readExpr1(Rhs, precedence(Op2));
1551 }
1552
1553 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001554 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001555 return Lhs;
1556}
1557
1558uint64_t static getConstant(StringRef S) {
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001559 if (S == "COMMONPAGESIZE")
Rui Ueyama708019c2016-07-24 18:19:40 +00001560 return Target->PageSize;
Michael J. Spencere2cc07b2016-08-17 02:10:51 +00001561 if (S == "MAXPAGESIZE")
Petr Hosek997f8832016-09-28 15:20:47 +00001562 return Config->MaxPageSize;
Rui Ueyama708019c2016-07-24 18:19:40 +00001563 error("unknown constant: " + S);
1564 return 0;
1565}
1566
Rui Ueyama626e0b02016-09-02 18:19:00 +00001567// Parses Tok as an integer. Returns true if successful.
1568// It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1569// and decimal numbers. Decimal numbers may have "K" (kilo) or
1570// "M" (mega) prefixes.
George Rimar9f2f7ad2016-09-02 16:01:42 +00001571static bool readInteger(StringRef Tok, uint64_t &Result) {
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001572 if (Tok.startswith("-")) {
1573 if (!readInteger(Tok.substr(1), Result))
1574 return false;
1575 Result = -Result;
1576 return true;
1577 }
George Rimar9f2f7ad2016-09-02 16:01:42 +00001578 if (Tok.startswith_lower("0x"))
1579 return !Tok.substr(2).getAsInteger(16, Result);
1580 if (Tok.endswith_lower("H"))
1581 return !Tok.drop_back().getAsInteger(16, Result);
1582
1583 int Suffix = 1;
1584 if (Tok.endswith_lower("K")) {
1585 Suffix = 1024;
1586 Tok = Tok.drop_back();
1587 } else if (Tok.endswith_lower("M")) {
1588 Suffix = 1024 * 1024;
1589 Tok = Tok.drop_back();
1590 }
1591 if (Tok.getAsInteger(10, Result))
1592 return false;
1593 Result *= Suffix;
1594 return true;
1595}
1596
George Rimare38cbab2016-09-26 19:22:50 +00001597BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1598 int Size = StringSwitch<unsigned>(Tok)
1599 .Case("BYTE", 1)
1600 .Case("SHORT", 2)
1601 .Case("LONG", 4)
1602 .Case("QUAD", 8)
1603 .Default(-1);
1604 if (Size == -1)
1605 return nullptr;
1606
1607 expect("(");
1608 uint64_t Val = 0;
1609 StringRef S = next();
1610 if (!readInteger(S, Val))
1611 setError("unexpected value: " + S);
1612 expect(")");
1613 return new BytesDataCommand(Val, Size);
1614}
1615
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001616StringRef ScriptParser::readParenLiteral() {
1617 expect("(");
1618 StringRef Tok = next();
1619 expect(")");
1620 return Tok;
1621}
1622
Rui Ueyama708019c2016-07-24 18:19:40 +00001623Expr ScriptParser::readPrimary() {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001624 if (peek() == "(")
1625 return readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001626
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001627 StringRef Tok = next();
Rui Ueyama708019c2016-07-24 18:19:40 +00001628
Simon Atanasyaneaeafb22016-09-02 21:54:35 +00001629 if (Tok == "~") {
1630 Expr E = readPrimary();
1631 return [=](uint64_t Dot) { return ~E(Dot); };
1632 }
1633 if (Tok == "-") {
1634 Expr E = readPrimary();
1635 return [=](uint64_t Dot) { return -E(Dot); };
1636 }
1637
Rui Ueyama708019c2016-07-24 18:19:40 +00001638 // Built-in functions are parsed here.
1639 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimar96659df2016-08-30 09:54:01 +00001640 if (Tok == "ADDR") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001641 StringRef Name = readParenLiteral();
George Rimar884e7862016-09-08 08:19:13 +00001642 return
1643 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
George Rimar96659df2016-08-30 09:54:01 +00001644 }
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001645 if (Tok == "LOADADDR") {
1646 StringRef Name = readParenLiteral();
1647 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1648 }
George Rimareefa7582016-08-04 09:29:31 +00001649 if (Tok == "ASSERT")
1650 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001651 if (Tok == "ALIGN") {
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001652 Expr E = readParenExpr();
Rui Ueyama708019c2016-07-24 18:19:40 +00001653 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1654 }
1655 if (Tok == "CONSTANT") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001656 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001657 return [=](uint64_t Dot) { return getConstant(Name); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001658 }
George Rimarf34f45f2016-09-23 13:17:23 +00001659 if (Tok == "DEFINED") {
1660 expect("(");
1661 StringRef Tok = next();
1662 expect(")");
George Rimarf2821022016-09-26 11:00:48 +00001663 return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
George Rimarf34f45f2016-09-23 13:17:23 +00001664 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001665 if (Tok == "SEGMENT_START") {
1666 expect("(");
Justin Bogner5424e7c2016-10-17 06:21:13 +00001667 skip();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001668 expect(",");
George Rimar8c658bf2016-09-17 18:14:56 +00001669 Expr E = readExpr();
Rafael Espindola54c145c2016-07-28 18:16:24 +00001670 expect(")");
George Rimar8c658bf2016-09-17 18:14:56 +00001671 return [=](uint64_t Dot) { return E(Dot); };
Rafael Espindola54c145c2016-07-28 18:16:24 +00001672 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001673 if (Tok == "DATA_SEGMENT_ALIGN") {
1674 expect("(");
1675 Expr E = readExpr();
1676 expect(",");
1677 readExpr();
1678 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001679 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001680 }
1681 if (Tok == "DATA_SEGMENT_END") {
1682 expect("(");
1683 expect(".");
1684 expect(")");
1685 return [](uint64_t Dot) { return Dot; };
1686 }
George Rimar276b4e62016-07-26 17:58:44 +00001687 // GNU linkers implements more complicated logic to handle
1688 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1689 // the next page boundary for simplicity.
1690 if (Tok == "DATA_SEGMENT_RELRO_END") {
1691 expect("(");
Rafael Espindola97bdc722016-09-14 19:14:01 +00001692 readExpr();
George Rimar276b4e62016-07-26 17:58:44 +00001693 expect(",");
1694 readExpr();
1695 expect(")");
1696 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1697 }
George Rimar9e694502016-07-29 16:18:47 +00001698 if (Tok == "SIZEOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001699 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001700 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
George Rimar9e694502016-07-29 16:18:47 +00001701 }
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001702 if (Tok == "ALIGNOF") {
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001703 StringRef Name = readParenLiteral();
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001704 return
1705 [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
Eugene Leviant36fac7f2016-09-08 09:08:30 +00001706 }
George Rimare32a3592016-08-10 07:59:34 +00001707 if (Tok == "SIZEOF_HEADERS")
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001708 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001709
George Rimar9f2f7ad2016-09-02 16:01:42 +00001710 // Tok is a literal number.
1711 uint64_t V;
1712 if (readInteger(Tok, V))
Rafael Espindolab0de56b2016-10-31 21:36:23 +00001713 return [=](uint64_t Dot) { return V; };
George Rimar9f2f7ad2016-09-02 16:01:42 +00001714
1715 // Tok is a symbol name.
1716 if (Tok != "." && !isValidCIdentifier(Tok))
1717 setError("malformed number: " + Tok);
Rafael Espindola2f831dc2016-10-31 19:56:37 +00001718 return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1719 [=]() { return isAbsolute(Tok); }};
Rui Ueyama708019c2016-07-24 18:19:40 +00001720}
1721
1722Expr ScriptParser::readTernary(Expr Cond) {
Justin Bogner5424e7c2016-10-17 06:21:13 +00001723 skip();
Rui Ueyama708019c2016-07-24 18:19:40 +00001724 Expr L = readExpr();
1725 expect(":");
1726 Expr R = readExpr();
1727 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1728}
1729
Rui Ueyama6ad7dfc2016-08-17 18:59:16 +00001730Expr ScriptParser::readParenExpr() {
1731 expect("(");
1732 Expr E = readExpr();
1733 expect(")");
1734 return E;
1735}
1736
Eugene Leviantbbe38602016-07-19 09:25:43 +00001737std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1738 std::vector<StringRef> Phdrs;
1739 while (!Error && peek().startswith(":")) {
1740 StringRef Tok = next();
1741 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1742 if (Tok.empty()) {
1743 setError("section header name is empty");
1744 break;
1745 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001746 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001747 }
1748 return Phdrs;
1749}
1750
George Rimar95dd7182016-10-18 10:49:50 +00001751// Read a program header type name. The next token must be a
1752// name of a program header type or a constant (e.g. "0x3").
Eugene Leviantbbe38602016-07-19 09:25:43 +00001753unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001754 StringRef Tok = next();
George Rimar95dd7182016-10-18 10:49:50 +00001755 uint64_t Val;
1756 if (readInteger(Tok, Val))
1757 return Val;
1758
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001759 unsigned Ret = StringSwitch<unsigned>(Tok)
George Rimar6c55f0e2016-09-08 08:20:30 +00001760 .Case("PT_NULL", PT_NULL)
1761 .Case("PT_LOAD", PT_LOAD)
1762 .Case("PT_DYNAMIC", PT_DYNAMIC)
1763 .Case("PT_INTERP", PT_INTERP)
1764 .Case("PT_NOTE", PT_NOTE)
1765 .Case("PT_SHLIB", PT_SHLIB)
1766 .Case("PT_PHDR", PT_PHDR)
1767 .Case("PT_TLS", PT_TLS)
1768 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1769 .Case("PT_GNU_STACK", PT_GNU_STACK)
1770 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
George Rimar270173f2016-10-14 13:02:22 +00001771 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
George Rimarcc6e5672016-10-14 10:34:36 +00001772 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
George Rimar6c55f0e2016-09-08 08:20:30 +00001773 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001774
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001775 if (Ret == (unsigned)-1) {
1776 setError("invalid program header type: " + Tok);
1777 return PT_NULL;
1778 }
1779 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001780}
1781
Rui Ueyama95769b42016-08-31 20:03:54 +00001782void ScriptParser::readVersionDeclaration(StringRef VerStr) {
George Rimar20b65982016-08-31 09:08:26 +00001783 // Identifiers start at 2 because 0 and 1 are reserved
1784 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1785 size_t VersionId = Config->VersionDefinitions.size() + 2;
1786 Config->VersionDefinitions.push_back({VerStr, VersionId});
1787
Rui Ueyama83043f22016-10-17 16:01:53 +00001788 if (consume("global:") || peek() != "local:")
George Rimar20b65982016-08-31 09:08:26 +00001789 readGlobal(VerStr);
Rui Ueyama83043f22016-10-17 16:01:53 +00001790 if (consume("local:"))
George Rimar20b65982016-08-31 09:08:26 +00001791 readLocal();
1792 expect("}");
1793
1794 // Each version may have a parent version. For example, "Ver2" defined as
1795 // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1796 // version hierarchy is, probably against your instinct, purely for human; the
1797 // runtime doesn't care about them at all. In LLD, we simply skip the token.
1798 if (!VerStr.empty() && peek() != ";")
Justin Bogner5424e7c2016-10-17 06:21:13 +00001799 skip();
George Rimar20b65982016-08-31 09:08:26 +00001800 expect(";");
1801}
1802
1803void ScriptParser::readLocal() {
1804 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1805 expect("*");
1806 expect(";");
1807}
1808
1809void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
George Rimarcd574a52016-09-09 14:35:36 +00001810 expect("\"C++\"");
George Rimar20b65982016-08-31 09:08:26 +00001811 expect("{");
1812
1813 for (;;) {
1814 if (peek() == "}" || Error)
1815 break;
George Rimarcd574a52016-09-09 14:35:36 +00001816 bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1817 Globals->push_back({unquote(next()), true, HasWildcard});
George Rimar20b65982016-08-31 09:08:26 +00001818 expect(";");
1819 }
1820
1821 expect("}");
1822 expect(";");
1823}
1824
1825void ScriptParser::readGlobal(StringRef VerStr) {
1826 std::vector<SymbolVersion> *Globals;
1827 if (VerStr.empty())
1828 Globals = &Config->VersionScriptGlobals;
1829 else
1830 Globals = &Config->VersionDefinitions.back().Globals;
1831
1832 for (;;) {
Rui Ueyama83043f22016-10-17 16:01:53 +00001833 if (consume("extern"))
George Rimar20b65982016-08-31 09:08:26 +00001834 readExtern(Globals);
1835
1836 StringRef Cur = peek();
1837 if (Cur == "}" || Cur == "local:" || Error)
1838 return;
Justin Bogner5424e7c2016-10-17 06:21:13 +00001839 skip();
George Rimarcd574a52016-09-09 14:35:36 +00001840 Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
George Rimar20b65982016-08-31 09:08:26 +00001841 expect(";");
1842 }
1843}
1844
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001845static bool isUnderSysroot(StringRef Path) {
1846 if (Config->Sysroot == "")
1847 return false;
1848 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1849 if (sys::fs::equivalent(Config->Sysroot, Path))
1850 return true;
1851 return false;
1852}
1853
Rui Ueyama07320e42016-04-20 20:13:41 +00001854void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001855 StringRef Path = MB.getBufferIdentifier();
George Rimar20b65982016-08-31 09:08:26 +00001856 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1857}
1858
1859void elf::readVersionScript(MemoryBufferRef MB) {
1860 ScriptParser(MB.getBuffer(), false).readVersionScript();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001861}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001862
Rui Ueyama07320e42016-04-20 20:13:41 +00001863template class elf::LinkerScript<ELF32LE>;
1864template class elf::LinkerScript<ELF32BE>;
1865template class elf::LinkerScript<ELF64LE>;
1866template class elf::LinkerScript<ELF64BE>;