blob: 980d27e61f330f7ca2cd115cfb29ab8824586ade [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"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
Eugene Leviantceabe802016-08-11 07:56:43 +000046template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000047static void addRegular(SymbolAssignment *Cmd) {
48 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000051}
52
53template <class ELFT>
Rui Ueyama16024212016-08-11 23:22:52 +000054static void addSynthetic(SymbolAssignment *Cmd,
55 OutputSectionBase<ELFT> *Section) {
56 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(Cmd->Name, Section, 0);
57 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
58 Cmd->Sym = Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000059}
60
Rui Ueyama16024212016-08-11 23:22:52 +000061// If a symbol was in PROVIDE(), we need to define it only when
62// it is an undefined symbol.
63template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
64 if (Cmd->Name == ".")
Eugene Leviantceabe802016-08-11 07:56:43 +000065 return false;
Rui Ueyama16024212016-08-11 23:22:52 +000066 if (!Cmd->Provide)
67 return true;
68 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
69 return B && B->isUndefined();
Eugene Leviantceabe802016-08-11 07:56:43 +000070}
71
George Rimar076fe152016-07-21 06:43:01 +000072bool SymbolAssignment::classof(const BaseCommand *C) {
73 return C->Kind == AssignmentKind;
74}
75
76bool OutputSectionCommand::classof(const BaseCommand *C) {
77 return C->Kind == OutputSectionKind;
78}
79
George Rimareea31142016-07-21 14:26:59 +000080bool InputSectionDescription::classof(const BaseCommand *C) {
81 return C->Kind == InputSectionKind;
82}
83
George Rimareefa7582016-08-04 09:29:31 +000084bool AssertCommand::classof(const BaseCommand *C) {
85 return C->Kind == AssertKind;
86}
87
Rui Ueyama36a153c2016-07-23 14:09:58 +000088template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000089 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000090}
91
Rui Ueyamaf34d0e02016-08-12 01:24:53 +000092template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
93template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
94
Rui Ueyama07320e42016-04-20 20:13:41 +000095template <class ELFT>
96bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000097 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000098 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000099 return true;
100 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000101}
102
Rui Ueyama63dc6502016-07-25 22:41:42 +0000103static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
104 for (StringRef Pat : Patterns)
105 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +0000106 return true;
107 return false;
108}
109
George Rimar06598002016-07-28 21:51:30 +0000110static bool fileMatches(const InputSectionDescription *Desc,
111 StringRef Filename) {
112 if (!globMatch(Desc->FilePattern, Filename))
113 return false;
114 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
115}
116
Rui Ueyama6b274812016-07-25 22:51:07 +0000117// Returns input sections filtered by given glob patterns.
118template <class ELFT>
119std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000120LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000121 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000122 std::vector<InputSectionBase<ELFT> *> Ret;
123 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000124 Symtab<ELFT>::X->getObjectFiles()) {
125 if (fileMatches(I, sys::path::filename(F->getName())))
126 for (InputSectionBase<ELFT> *S : F->getSections())
127 if (!isDiscarded(S) && !S->OutSec &&
128 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000129 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000130 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000131
132 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000133 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000134
Rui Ueyama6b274812016-07-25 22:51:07 +0000135 return Ret;
136}
137
Rui Ueyamadd81fe32016-08-11 21:00:02 +0000138// You can define new symbols using linker scripts. For example,
139// ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
140// foo just after abc.o's text section contents. This class is to
141// handle such symbol definitions.
142//
143// In order to handle scripts like the above one, we want to
144// keep symbol definitions in output sections. Because output sections
145// can contain only input sections, we wrap symbol definitions
146// with dummy input sections. This class serves that purpose.
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000147template <class ELFT>
148class elf::LayoutInputSection : public InputSectionBase<ELFT> {
Eugene Leviantceabe802016-08-11 07:56:43 +0000149public:
Rui Ueyamaf34d0e02016-08-12 01:24:53 +0000150 explicit LayoutInputSection(SymbolAssignment *Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000151 static bool classof(const InputSectionBase<ELFT> *S);
152 SymbolAssignment *Cmd;
153
154private:
155 typename ELFT::Shdr Hdr;
156};
157
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000158template <class ELFT>
159static InputSectionBase<ELFT> *
160getNonLayoutSection(std::vector<InputSectionBase<ELFT> *> &Vec) {
161 for (InputSectionBase<ELFT> *S : Vec)
162 if (!isa<LayoutInputSection<ELFT>>(S))
163 return S;
164 return nullptr;
165}
Eugene Leviantceabe802016-08-11 07:56:43 +0000166
167template <class T> static T *zero(T *Val) {
168 memset(Val, 0, sizeof(*Val));
169 return Val;
170}
171
172template <class ELFT>
173LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
Rui Ueyama2c3f5012016-08-11 22:06:55 +0000174 : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
175 InputSectionBase<ELFT>::Layout),
176 Cmd(Cmd) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000177 this->Live = true;
Eugene Leviantceabe802016-08-11 07:56:43 +0000178 Hdr.sh_type = SHT_NOBITS;
179}
180
181template <class ELFT>
182bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
183 return S->SectionKind == InputSectionBase<ELFT>::Layout;
184}
185
186template <class ELFT>
Rui Ueyama742c3832016-08-04 22:27:00 +0000187static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
188 return A->getSectionName() < B->getSectionName();
189}
George Rimar350ece42016-08-03 08:35:59 +0000190
Rui Ueyama742c3832016-08-04 22:27:00 +0000191template <class ELFT>
192static bool compareAlignment(InputSectionBase<ELFT> *A,
193 InputSectionBase<ELFT> *B) {
194 // ">" is not a mistake. Larger alignments are placed before smaller
195 // alignments in order to reduce the amount of padding necessary.
196 // This is compatible with GNU.
197 return A->Alignment > B->Alignment;
198}
George Rimar350ece42016-08-03 08:35:59 +0000199
Rui Ueyama742c3832016-08-04 22:27:00 +0000200template <class ELFT>
201static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
202getComparator(SortKind K) {
203 if (K == SortByName)
204 return compareName<ELFT>;
205 return compareAlignment<ELFT>;
206}
George Rimar0702c4e2016-07-29 15:32:46 +0000207
208template <class ELFT>
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000209void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
210 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
211 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
212 for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
213 S->Live = false;
214 reportDiscarded(S);
215 }
216 }
217 }
218}
219
220template <class ELFT>
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000221std::vector<InputSectionBase<ELFT> *>
222LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &Cmd) {
223 std::vector<InputSectionBase<ELFT> *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000224
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000225 for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
226 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
227 Ret.push_back(new (LAlloc.Allocate()) LayoutInputSection<ELFT>(Cmd));
228 continue;
229 }
230
231 auto *Cmd = cast<InputSectionDescription>(Base.get());
232 std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
233 if (Cmd->SortInner)
234 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
235 if (Cmd->SortOuter)
236 std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
237 Ret.insert(Ret.end(), V.begin(), V.end());
238 }
239 return Ret;
240}
241
242template <class ELFT>
243void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000244 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000245 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000246 if (Cmd->Name == "/DISCARD/") {
247 discard(*Cmd);
248 continue;
249 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000250
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000251 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
252 InputSectionBase<ELFT> *Head = getNonLayoutSection<ELFT>(V);
253 if (!Head)
254 continue;
255
256 OutputSectionBase<ELFT> *OutSec;
257 bool IsNew;
258 std::tie(OutSec, IsNew) = Factory.create(Head, Cmd->Name);
259 if (IsNew)
260 OutputSections->push_back(OutSec);
261
262 for (InputSectionBase<ELFT> *Sec : V) {
263 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(Sec)) {
264 if (shouldDefine<ELFT>(L->Cmd))
265 addSynthetic<ELFT>(L->Cmd, OutSec);
266 else if (L->Cmd->Name != ".")
267 continue;
268 }
269 OutSec->addSection(Sec);
270 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000271 } else if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base1.get())) {
Rui Ueyama16024212016-08-11 23:22:52 +0000272 if (shouldDefine<ELFT>(Cmd2))
273 addRegular<ELFT>(Cmd2);
Eugene Leviantceabe802016-08-11 07:56:43 +0000274 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000275 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000276
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000277 // Add orphan sections.
Rui Ueyama6b274812016-07-25 22:51:07 +0000278 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000279 Symtab<ELFT>::X->getObjectFiles()) {
280 for (InputSectionBase<ELFT> *S : F->getSections()) {
281 if (!isDiscarded(S) && !S->OutSec) {
282 OutputSectionBase<ELFT> *OutSec;
283 bool IsNew;
284 std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
285 if (IsNew)
286 OutputSections->push_back(OutSec);
287 OutSec->addSection(S);
288 }
289 }
290 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000291
Rui Ueyama3c291e12016-07-25 21:30:00 +0000292 // Remove from the output all the sections which did not meet
293 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000294 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000295}
296
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000297template <class R, class T>
298static inline void removeElementsIf(R &Range, const T &Pred) {
299 Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
300}
301
Rui Ueyama3c291e12016-07-25 21:30:00 +0000302// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000303template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000304 // In this loop, we remove output sections if they don't satisfy
305 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000306 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
307 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
308 if (!Cmd || Cmd->Name == "/DISCARD/")
309 continue;
310
George Rimarbfc4a4b2016-07-26 10:47:09 +0000311 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000312 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000313
Rui Ueyama808d13e2016-08-05 01:05:01 +0000314 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
315 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
316
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000317 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
318 bool Writable = (S->getFlags() & SHF_WRITE);
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000319 return S->getName() == Cmd->Name &&
320 ((RO && Writable) || (RW && !Writable));
George Rimarbfc4a4b2016-07-26 10:47:09 +0000321 });
Rui Ueyama3c291e12016-07-25 21:30:00 +0000322 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000323}
324
Eugene Leviantceabe802016-08-11 07:56:43 +0000325template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
Eugene Leviantceabe802016-08-11 07:56:43 +0000326 auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
Rui Ueyama2de509c2016-08-12 00:55:08 +0000327 if (!OutSec) {
328 Sec->assignOffsets();
Eugene Leviantceabe802016-08-11 07:56:43 +0000329 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000330 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000331
332 typedef typename ELFT::uint uintX_t;
333 uintX_t Off = 0;
334
335 for (InputSection<ELFT> *I : OutSec->Sections) {
336 if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
337 uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
338 if (L->Cmd->Name == ".")
339 Off = Value;
340 else
341 cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym)->Value = Value;
342 } else {
343 Off = alignTo(Off, I->Alignment);
344 I->OutSecOff = Off;
345 Off += I->getSize();
346 }
Rui Ueyamaf4a30a52016-08-11 21:30:42 +0000347 // Update section size inside for-loop, so that SIZEOF
Eugene Leviantceabe802016-08-11 07:56:43 +0000348 // works correctly in the case below:
349 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
350 Sec->setSize(Off);
351 }
352}
353
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000354template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
George Rimar652852c2016-04-16 10:10:32 +0000355 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000356 // are not explicitly placed into the output file by the linker script.
357 // We place orphan sections at end of file.
358 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000359 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000360 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar652852c2016-04-16 10:10:32 +0000361 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000362 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000363 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000364 }
George Rimar652852c2016-04-16 10:10:32 +0000365
Rui Ueyama7c18c282016-04-18 21:00:40 +0000366 // Assign addresses as instructed by linker script SECTIONS sub-commands.
George Rimare32a3592016-08-10 07:59:34 +0000367 Dot = getSizeOfHeaders();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000368 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000369 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000370
George Rimar076fe152016-07-21 06:43:01 +0000371 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
372 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000373 if (Cmd->Name == ".") {
374 Dot = Cmd->Expression(Dot);
375 } else if (Cmd->Sym) {
376 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
377 }
George Rimar652852c2016-04-16 10:10:32 +0000378 continue;
379 }
380
George Rimareefa7582016-08-04 09:29:31 +0000381 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
382 Cmd->Expression(Dot);
383 continue;
384 }
385
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000386 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000387 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000388 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000389 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Rui Ueyamae5cc6682016-08-12 00:36:56 +0000390 for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
George Rimar076fe152016-07-21 06:43:01 +0000391 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000392 continue;
George Rimar652852c2016-04-16 10:10:32 +0000393
George Rimar58e5c4d2016-07-25 08:29:46 +0000394 if (Cmd->AddrExpr)
395 Dot = Cmd->AddrExpr(Dot);
396
George Rimar630c6172016-07-26 18:06:29 +0000397 if (Cmd->AlignExpr)
398 Sec->updateAlignment(Cmd->AlignExpr(Dot));
399
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000400 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
401 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000402 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000403 Sec->setVA(TVA);
Eugene Leviantceabe802016-08-11 07:56:43 +0000404 assignOffsets(Sec);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000405 ThreadBssOffset = TVA - Dot + Sec->getSize();
406 continue;
407 }
George Rimar652852c2016-04-16 10:10:32 +0000408
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000409 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000410 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000411 Sec->setVA(Dot);
Eugene Leviantceabe802016-08-11 07:56:43 +0000412 assignOffsets(Sec);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000413 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000414 Dot += Sec->getSize();
415 continue;
416 }
Rui Ueyama2de509c2016-08-12 00:55:08 +0000417 Sec->assignOffsets();
George Rimar652852c2016-04-16 10:10:32 +0000418 }
419 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000420
Rafael Espindola64c32d62016-07-07 14:28:47 +0000421 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000422 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000423 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
424 Out<ELFT>::ProgramHeaders->getSize(),
425 Target->PageSize);
426 Out<ELFT>::ElfHeader->setVA(MinVA);
427 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000428}
429
Rui Ueyama07320e42016-04-20 20:13:41 +0000430template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000431std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
432 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000433 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000434
435 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000436 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
437 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000438
439 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000440 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000441 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000442 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000443
444 switch (Cmd.Type) {
445 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000446 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000447 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000448 break;
449 case PT_DYNAMIC:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000450 if (Out<ELFT>::DynSymTab) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000451 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000452 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000453 }
454 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000455 case PT_GNU_EH_FRAME:
456 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000457 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000458 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000459 }
460 break;
461 }
462 }
463
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000464 PhdrEntry<ELFT> *Load = nullptr;
465 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000466 for (OutputSectionBase<ELFT> *Sec : Sections) {
467 if (!(Sec->getFlags() & SHF_ALLOC))
468 break;
469
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000470 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 if (!PhdrIds.empty()) {
472 // Assign headers specified by linker script
473 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000474 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000475 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000476 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 }
478 } else {
479 // If we have no load segment or flags've changed then we want new load
480 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000481 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000483 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000484 Flags = NewFlags;
485 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000486 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000488 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000489 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000490}
491
492template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000493ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000494 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
495 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
496 if (Cmd->Name == Name)
497 return Cmd->Filler;
498 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000499}
500
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000501// Returns the index of the given section name in linker script
502// SECTIONS commands. Sections are laid out as the same order as they
503// were in the script. If a given name did not appear in the script,
504// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000505template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000506 int I = 0;
507 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
508 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
509 if (Cmd->Name == Name)
510 return I;
511 ++I;
512 }
513 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000514}
515
516// A compartor to sort output sections. Returns -1 or 1 if
517// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000518template <class ELFT>
519int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000520 int I = getSectionIndex(A);
521 int J = getSectionIndex(B);
522 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000523 return 0;
524 return I < J ? -1 : 1;
525}
526
Eugene Leviantbbe38602016-07-19 09:25:43 +0000527template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
528 return !Opt.PhdrsCommands.empty();
529}
530
George Rimar9e694502016-07-29 16:18:47 +0000531template <class ELFT>
532typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
533 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
534 if (Sec->getName() == Name)
535 return Sec->getSize();
536 error("undefined section " + Name);
537 return 0;
538}
539
George Rimare32a3592016-08-10 07:59:34 +0000540template <class ELFT>
541typename ELFT::uint LinkerScript<ELFT>::getSizeOfHeaders() {
542 return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
543}
544
Eugene Leviantbbe38602016-07-19 09:25:43 +0000545// Returns indices of ELF headers containing specific section, identified
546// by Name. Each index is a zero based number of ELF header listed within
547// PHDRS {} script block.
548template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000549std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000550 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
551 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000552 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000553 continue;
554
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000555 std::vector<size_t> Ret;
556 for (StringRef PhdrName : Cmd->Phdrs)
557 Ret.push_back(getPhdrIndex(PhdrName));
558 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000559 }
George Rimar31d842f2016-07-20 16:43:03 +0000560 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000561}
562
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000563template <class ELFT>
564size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
565 size_t I = 0;
566 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
567 if (Cmd.Name == PhdrName)
568 return I;
569 ++I;
570 }
571 error("section header '" + PhdrName + "' is not listed in PHDRS");
572 return 0;
573}
574
Rui Ueyama07320e42016-04-20 20:13:41 +0000575class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000576 typedef void (ScriptParser::*Handler)();
577
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000578public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000579 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000580
Rui Ueyama4a465392016-04-22 22:59:24 +0000581 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000582
583private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000584 void addFile(StringRef Path);
585
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000586 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000587 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000588 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000589 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000590 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000591 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000592 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000593 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000594 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000595 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000596 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000597 void readSections();
598
Rui Ueyama113cdec2016-07-24 23:05:57 +0000599 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000600 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000601 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000602 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000603 InputSectionDescription *readInputSectionDescription();
604 std::vector<StringRef> readInputFilePatterns();
605 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000606 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000607 SortKind readSortKind();
Rui Ueyama10416562016-08-04 02:03:27 +0000608 SymbolAssignment *readProvide(bool Hidden);
Eugene Leviantceabe802016-08-11 07:56:43 +0000609 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
Rui Ueyama10416562016-08-04 02:03:27 +0000610 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000611 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000612 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000613
614 Expr readExpr();
615 Expr readExpr1(Expr Lhs, int MinPrec);
616 Expr readPrimary();
617 Expr readTernary(Expr Cond);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000618
George Rimarc3794e52016-02-24 09:21:47 +0000619 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000620 ScriptConfiguration &Opt = *ScriptConfig;
621 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000622 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000623};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000624
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000625const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000626 {"ENTRY", &ScriptParser::readEntry},
627 {"EXTERN", &ScriptParser::readExtern},
628 {"GROUP", &ScriptParser::readGroup},
629 {"INCLUDE", &ScriptParser::readInclude},
630 {"INPUT", &ScriptParser::readGroup},
631 {"OUTPUT", &ScriptParser::readOutput},
632 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
633 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000634 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000635 {"SEARCH_DIR", &ScriptParser::readSearchDir},
636 {"SECTIONS", &ScriptParser::readSections},
637 {";", &ScriptParser::readNothing}};
638
Rui Ueyama717677a2016-02-11 21:17:59 +0000639void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000640 while (!atEOF()) {
641 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000642 if (Handler Fn = Cmd.lookup(Tok))
643 (this->*Fn)();
644 else
George Rimar57610422016-03-11 14:43:02 +0000645 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000646 }
647}
648
Rui Ueyama717677a2016-02-11 21:17:59 +0000649void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000650 if (IsUnderSysroot && S.startswith("/")) {
651 SmallString<128> Path;
652 (Config->Sysroot + S).toStringRef(Path);
653 if (sys::fs::exists(Path)) {
654 Driver->addFile(Saver.save(Path.str()));
655 return;
656 }
657 }
658
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000659 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000660 Driver->addFile(S);
661 } else if (S.startswith("=")) {
662 if (Config->Sysroot.empty())
663 Driver->addFile(S.substr(1));
664 else
665 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
666 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000667 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000668 } else if (sys::fs::exists(S)) {
669 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000670 } else {
671 std::string Path = findFromSearchPaths(S);
672 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000673 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000674 else
675 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000676 }
677}
678
Rui Ueyama717677a2016-02-11 21:17:59 +0000679void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000680 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000681 bool Orig = Config->AsNeeded;
682 Config->AsNeeded = true;
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000683 while (!Error && !skip(")"))
684 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000685 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000686}
687
Rui Ueyama717677a2016-02-11 21:17:59 +0000688void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000689 // -e <symbol> takes predecence over ENTRY(<symbol>).
690 expect("(");
691 StringRef Tok = next();
692 if (Config->Entry.empty())
693 Config->Entry = Tok;
694 expect(")");
695}
696
Rui Ueyama717677a2016-02-11 21:17:59 +0000697void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000698 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000699 while (!Error && !skip(")"))
700 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000701}
702
Rui Ueyama717677a2016-02-11 21:17:59 +0000703void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000704 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000705 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000706 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000707 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000708 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000709 else
710 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000711 }
712}
713
Rui Ueyama717677a2016-02-11 21:17:59 +0000714void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000715 StringRef Tok = next();
716 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000717 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000718 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000719 return;
720 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000721 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000722 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
723 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000724 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000725}
726
Rui Ueyama717677a2016-02-11 21:17:59 +0000727void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000728 // -o <file> takes predecence over OUTPUT(<file>).
729 expect("(");
730 StringRef Tok = next();
731 if (Config->OutputFile.empty())
732 Config->OutputFile = Tok;
733 expect(")");
734}
735
Rui Ueyama717677a2016-02-11 21:17:59 +0000736void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000737 // Error checking only for now.
738 expect("(");
739 next();
740 expect(")");
741}
742
Rui Ueyama717677a2016-02-11 21:17:59 +0000743void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000744 // Error checking only for now.
745 expect("(");
746 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000747 StringRef Tok = next();
748 if (Tok == ")")
749 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000750 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000751 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000752 return;
753 }
Davide Italiano6836c612015-10-12 21:08:41 +0000754 next();
755 expect(",");
756 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000757 expect(")");
758}
759
Eugene Leviantbbe38602016-07-19 09:25:43 +0000760void ScriptParser::readPhdrs() {
761 expect("{");
762 while (!Error && !skip("}")) {
763 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000764 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000765 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
766
767 PhdrCmd.Type = readPhdrType();
768 do {
769 Tok = next();
770 if (Tok == ";")
771 break;
772 if (Tok == "FILEHDR")
773 PhdrCmd.HasFilehdr = true;
774 else if (Tok == "PHDRS")
775 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000776 else if (Tok == "FLAGS") {
777 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000778 // Passing 0 for the value of dot is a bit of a hack. It means that
779 // we accept expressions like ".|1".
780 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000781 expect(")");
782 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000783 setError("unexpected header attribute: " + Tok);
784 } while (!Error);
785 }
786}
787
Rui Ueyama717677a2016-02-11 21:17:59 +0000788void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000789 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000790 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000791 expect(")");
792}
793
Rui Ueyama717677a2016-02-11 21:17:59 +0000794void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000795 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000796 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000797 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000798 StringRef Tok = next();
Eugene Leviantceabe802016-08-11 07:56:43 +0000799 BaseCommand *Cmd = readProvideOrAssignment(Tok);
800 if (!Cmd) {
801 if (Tok == "ASSERT")
802 Cmd = new AssertCommand(readAssert());
803 else
804 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000805 }
Rui Ueyama10416562016-08-04 02:03:27 +0000806 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000807 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000808}
809
Rui Ueyama708019c2016-07-24 18:19:40 +0000810static int precedence(StringRef Op) {
811 return StringSwitch<int>(Op)
812 .Case("*", 4)
813 .Case("/", 4)
814 .Case("+", 3)
815 .Case("-", 3)
816 .Case("<", 2)
817 .Case(">", 2)
818 .Case(">=", 2)
819 .Case("<=", 2)
820 .Case("==", 2)
821 .Case("!=", 2)
822 .Case("&", 1)
823 .Default(-1);
824}
825
Rui Ueyama10416562016-08-04 02:03:27 +0000826std::vector<StringRef> ScriptParser::readInputFilePatterns() {
827 std::vector<StringRef> V;
828 while (!Error && !skip(")"))
829 V.push_back(next());
830 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000831}
832
Rui Ueyama742c3832016-08-04 22:27:00 +0000833SortKind ScriptParser::readSortKind() {
834 if (skip("SORT") || skip("SORT_BY_NAME"))
835 return SortByName;
836 if (skip("SORT_BY_ALIGNMENT"))
837 return SortByAlignment;
838 return SortNone;
839}
840
Rui Ueyama10416562016-08-04 02:03:27 +0000841InputSectionDescription *ScriptParser::readInputSectionRules() {
842 auto *Cmd = new InputSectionDescription;
843 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000844 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000845
Rui Ueyama742c3832016-08-04 22:27:00 +0000846 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000847 if (skip("EXCLUDE_FILE")) {
848 expect("(");
849 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000850 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000851 }
George Rimar06598002016-07-28 21:51:30 +0000852
Rui Ueyama742c3832016-08-04 22:27:00 +0000853 // Read SORT().
854 if (SortKind K1 = readSortKind()) {
855 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000856 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000857 if (SortKind K2 = readSortKind()) {
858 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000859 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000860 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000861 expect(")");
862 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000863 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000864 }
George Rimar0702c4e2016-07-29 15:32:46 +0000865 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000866 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000867 }
George Rimar0702c4e2016-07-29 15:32:46 +0000868
Rui Ueyama10416562016-08-04 02:03:27 +0000869 Cmd->SectionPatterns = readInputFilePatterns();
870 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000871}
872
Rui Ueyama10416562016-08-04 02:03:27 +0000873InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000874 // Input section wildcard can be surrounded by KEEP.
875 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
876 if (skip("KEEP")) {
877 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000878 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000879 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000880 Opt.KeptSections.insert(Opt.KeptSections.end(),
881 Cmd->SectionPatterns.begin(),
882 Cmd->SectionPatterns.end());
883 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000884 }
Rui Ueyama10416562016-08-04 02:03:27 +0000885 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000886}
887
Rui Ueyama10416562016-08-04 02:03:27 +0000888Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000889 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000890 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000891 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000892 return E;
George Rimar630c6172016-07-26 18:06:29 +0000893}
894
George Rimar03fc0102016-07-28 07:18:23 +0000895void ScriptParser::readSort() {
896 expect("(");
897 expect("CONSTRUCTORS");
898 expect(")");
899}
900
George Rimareefa7582016-08-04 09:29:31 +0000901Expr ScriptParser::readAssert() {
902 expect("(");
903 Expr E = readExpr();
904 expect(",");
905 StringRef Msg = next();
906 expect(")");
907 return [=](uint64_t Dot) {
908 uint64_t V = E(Dot);
909 if (!V)
910 error(Msg);
911 return V;
912 };
913}
914
Rui Ueyama10416562016-08-04 02:03:27 +0000915OutputSectionCommand *
916ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000917 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000918
919 // Read an address expression.
920 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
921 if (peek() != ":")
922 Cmd->AddrExpr = readExpr();
923
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000924 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000925
George Rimar630c6172016-07-26 18:06:29 +0000926 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000927 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000928
Davide Italiano246f6812016-07-22 03:36:24 +0000929 // Parse constraints.
930 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000931 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000932 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000933 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000934 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000935
Rui Ueyama025d59b2016-02-02 20:27:59 +0000936 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000937 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000938 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000939 continue;
940 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000941
942 StringRef Tok = next();
943 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
944 Cmd->Commands.emplace_back(Assignment);
945 else if (Tok == "SORT")
George Rimar03fc0102016-07-28 07:18:23 +0000946 readSort();
Eugene Leviantceabe802016-08-11 07:56:43 +0000947 else
948 setError("unknown command " + Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000949 }
George Rimar076fe152016-07-21 06:43:01 +0000950 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000951 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000952 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000953}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000954
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000955std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000956 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000957 if (!Tok.startswith("="))
958 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000959 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000960
961 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000962 if (Tok.startswith("=0x"))
963 return parseHex(Tok.substr(3));
964
Rui Ueyama965827d2016-08-03 23:25:15 +0000965 // Read a decimal or octal value as a big-endian 32 bit value.
966 // Why do this? I don't know, but that's what gold does.
967 uint32_t V;
968 if (Tok.substr(1).getAsInteger(0, V)) {
969 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000970 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000971 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000972 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000973}
974
Rui Ueyama10416562016-08-04 02:03:27 +0000975SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000976 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000977 SymbolAssignment *Cmd = readAssignment(next());
978 Cmd->Provide = true;
979 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000980 expect(")");
981 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000982 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000983}
984
Eugene Leviantceabe802016-08-11 07:56:43 +0000985SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
986 SymbolAssignment *Cmd = nullptr;
987 if (peek() == "=" || peek() == "+=") {
988 Cmd = readAssignment(Tok);
989 expect(";");
990 } else if (Tok == "PROVIDE") {
991 Cmd = readProvide(false);
992 } else if (Tok == "PROVIDE_HIDDEN") {
993 Cmd = readProvide(true);
994 }
995 return Cmd;
996}
997
George Rimar30835ea2016-07-28 21:08:56 +0000998static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
999 if (S == ".")
1000 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +00001001
George Rimara9c5a522016-07-26 18:18:58 +00001002 switch (Config->EKind) {
1003 case ELF32LEKind:
1004 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1005 return B->getVA<ELF32LE>();
1006 break;
1007 case ELF32BEKind:
1008 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1009 return B->getVA<ELF32BE>();
1010 break;
1011 case ELF64LEKind:
1012 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1013 return B->getVA<ELF64LE>();
1014 break;
1015 case ELF64BEKind:
1016 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1017 return B->getVA<ELF64BE>();
1018 break;
George Rimar6930a6d2016-07-26 18:41:06 +00001019 default:
George Rimarb567b622016-07-26 18:46:13 +00001020 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +00001021 }
1022 error("symbol not found: " + S);
1023 return 0;
1024}
1025
George Rimar9e694502016-07-29 16:18:47 +00001026static uint64_t getSectionSize(StringRef Name) {
1027 switch (Config->EKind) {
1028 case ELF32LEKind:
1029 return Script<ELF32LE>::X->getOutputSectionSize(Name);
1030 case ELF32BEKind:
1031 return Script<ELF32BE>::X->getOutputSectionSize(Name);
1032 case ELF64LEKind:
1033 return Script<ELF64LE>::X->getOutputSectionSize(Name);
1034 case ELF64BEKind:
1035 return Script<ELF64BE>::X->getOutputSectionSize(Name);
1036 default:
1037 llvm_unreachable("unsupported target");
1038 }
George Rimar9e694502016-07-29 16:18:47 +00001039}
1040
George Rimare32a3592016-08-10 07:59:34 +00001041static uint64_t getSizeOfHeaders() {
1042 switch (Config->EKind) {
1043 case ELF32LEKind:
1044 return Script<ELF32LE>::X->getSizeOfHeaders();
1045 case ELF32BEKind:
1046 return Script<ELF32BE>::X->getSizeOfHeaders();
1047 case ELF64LEKind:
1048 return Script<ELF64LE>::X->getSizeOfHeaders();
1049 case ELF64BEKind:
1050 return Script<ELF64BE>::X->getSizeOfHeaders();
1051 default:
1052 llvm_unreachable("unsupported target");
1053 }
1054}
1055
George Rimar30835ea2016-07-28 21:08:56 +00001056SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1057 StringRef Op = next();
1058 assert(Op == "=" || Op == "+=");
1059 Expr E = readExpr();
1060 if (Op == "+=")
1061 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +00001062 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +00001063}
1064
1065// This is an operator-precedence parser to parse a linker
1066// script expression.
1067Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1068
Rui Ueyama36c1cd22016-08-05 01:04:59 +00001069static Expr combine(StringRef Op, Expr L, Expr R) {
1070 if (Op == "*")
1071 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1072 if (Op == "/") {
1073 return [=](uint64_t Dot) -> uint64_t {
1074 uint64_t RHS = R(Dot);
1075 if (RHS == 0) {
1076 error("division by zero");
1077 return 0;
1078 }
1079 return L(Dot) / RHS;
1080 };
1081 }
1082 if (Op == "+")
1083 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1084 if (Op == "-")
1085 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1086 if (Op == "<")
1087 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1088 if (Op == ">")
1089 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1090 if (Op == ">=")
1091 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1092 if (Op == "<=")
1093 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1094 if (Op == "==")
1095 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1096 if (Op == "!=")
1097 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1098 if (Op == "&")
1099 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1100 llvm_unreachable("invalid operator");
1101}
1102
Rui Ueyama708019c2016-07-24 18:19:40 +00001103// This is a part of the operator-precedence parser. This function
1104// assumes that the remaining token stream starts with an operator.
1105Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1106 while (!atEOF() && !Error) {
1107 // Read an operator and an expression.
1108 StringRef Op1 = peek();
1109 if (Op1 == "?")
1110 return readTernary(Lhs);
1111 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +00001112 break;
Rui Ueyama708019c2016-07-24 18:19:40 +00001113 next();
1114 Expr Rhs = readPrimary();
1115
1116 // Evaluate the remaining part of the expression first if the
1117 // next operator has greater precedence than the previous one.
1118 // For example, if we have read "+" and "3", and if the next
1119 // operator is "*", then we'll evaluate 3 * ... part first.
1120 while (!atEOF()) {
1121 StringRef Op2 = peek();
1122 if (precedence(Op2) <= precedence(Op1))
1123 break;
1124 Rhs = readExpr1(Rhs, precedence(Op2));
1125 }
1126
1127 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001128 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001129 return Lhs;
1130}
1131
1132uint64_t static getConstant(StringRef S) {
1133 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1134 return Target->PageSize;
1135 error("unknown constant: " + S);
1136 return 0;
1137}
1138
1139Expr ScriptParser::readPrimary() {
1140 StringRef Tok = next();
1141
Rui Ueyama708019c2016-07-24 18:19:40 +00001142 if (Tok == "(") {
1143 Expr E = readExpr();
1144 expect(")");
1145 return E;
1146 }
1147
1148 // Built-in functions are parsed here.
1149 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001150 if (Tok == "ASSERT")
1151 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001152 if (Tok == "ALIGN") {
1153 expect("(");
1154 Expr E = readExpr();
1155 expect(")");
1156 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1157 }
1158 if (Tok == "CONSTANT") {
1159 expect("(");
1160 StringRef Tok = next();
1161 expect(")");
1162 return [=](uint64_t Dot) { return getConstant(Tok); };
1163 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001164 if (Tok == "SEGMENT_START") {
1165 expect("(");
1166 next();
1167 expect(",");
1168 uint64_t Val;
1169 next().getAsInteger(0, Val);
1170 expect(")");
1171 return [=](uint64_t Dot) { return Val; };
1172 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001173 if (Tok == "DATA_SEGMENT_ALIGN") {
1174 expect("(");
1175 Expr E = readExpr();
1176 expect(",");
1177 readExpr();
1178 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001179 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001180 }
1181 if (Tok == "DATA_SEGMENT_END") {
1182 expect("(");
1183 expect(".");
1184 expect(")");
1185 return [](uint64_t Dot) { return Dot; };
1186 }
George Rimar276b4e62016-07-26 17:58:44 +00001187 // GNU linkers implements more complicated logic to handle
1188 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1189 // the next page boundary for simplicity.
1190 if (Tok == "DATA_SEGMENT_RELRO_END") {
1191 expect("(");
1192 next();
1193 expect(",");
1194 readExpr();
1195 expect(")");
1196 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1197 }
George Rimar9e694502016-07-29 16:18:47 +00001198 if (Tok == "SIZEOF") {
1199 expect("(");
1200 StringRef Name = next();
1201 expect(")");
1202 return [=](uint64_t Dot) { return getSectionSize(Name); };
1203 }
George Rimare32a3592016-08-10 07:59:34 +00001204 if (Tok == "SIZEOF_HEADERS")
1205 return [=](uint64_t Dot) { return getSizeOfHeaders(); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001206
George Rimara9c5a522016-07-26 18:18:58 +00001207 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001208 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001209 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001210 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001211 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001212 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001213 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001214 return [=](uint64_t Dot) { return V; };
1215}
1216
1217Expr ScriptParser::readTernary(Expr Cond) {
1218 next();
1219 Expr L = readExpr();
1220 expect(":");
1221 Expr R = readExpr();
1222 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1223}
1224
Eugene Leviantbbe38602016-07-19 09:25:43 +00001225std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1226 std::vector<StringRef> Phdrs;
1227 while (!Error && peek().startswith(":")) {
1228 StringRef Tok = next();
1229 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1230 if (Tok.empty()) {
1231 setError("section header name is empty");
1232 break;
1233 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001234 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001235 }
1236 return Phdrs;
1237}
1238
1239unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001240 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001241 unsigned Ret = StringSwitch<unsigned>(Tok)
1242 .Case("PT_NULL", PT_NULL)
1243 .Case("PT_LOAD", PT_LOAD)
1244 .Case("PT_DYNAMIC", PT_DYNAMIC)
1245 .Case("PT_INTERP", PT_INTERP)
1246 .Case("PT_NOTE", PT_NOTE)
1247 .Case("PT_SHLIB", PT_SHLIB)
1248 .Case("PT_PHDR", PT_PHDR)
1249 .Case("PT_TLS", PT_TLS)
1250 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1251 .Case("PT_GNU_STACK", PT_GNU_STACK)
1252 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1253 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001254
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001255 if (Ret == (unsigned)-1) {
1256 setError("invalid program header type: " + Tok);
1257 return PT_NULL;
1258 }
1259 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001260}
1261
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001262static bool isUnderSysroot(StringRef Path) {
1263 if (Config->Sysroot == "")
1264 return false;
1265 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1266 if (sys::fs::equivalent(Config->Sysroot, Path))
1267 return true;
1268 return false;
1269}
1270
Rui Ueyama07320e42016-04-20 20:13:41 +00001271// Entry point.
1272void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001273 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001274 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001275}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001276
Rui Ueyama07320e42016-04-20 20:13:41 +00001277template class elf::LinkerScript<ELF32LE>;
1278template class elf::LinkerScript<ELF32BE>;
1279template class elf::LinkerScript<ELF64LE>;
1280template class elf::LinkerScript<ELF64BE>;