blob: 1f6fbbcfca8ca192cfc1771e996630554937d0dd [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
George Rimar076fe152016-07-21 06:43:01 +000046bool SymbolAssignment::classof(const BaseCommand *C) {
47 return C->Kind == AssignmentKind;
48}
49
50bool OutputSectionCommand::classof(const BaseCommand *C) {
51 return C->Kind == OutputSectionKind;
52}
53
George Rimareea31142016-07-21 14:26:59 +000054bool InputSectionDescription::classof(const BaseCommand *C) {
55 return C->Kind == InputSectionKind;
56}
57
Rui Ueyama9c1112d2016-04-23 00:04:03 +000058// This is an operator-precedence parser to parse and evaluate
59// a linker script expression. For each linker script arithmetic
60// expression (e.g. ". = . + 0x1000"), a new instance of ExprParser
61// is created and ran.
62namespace {
63class ExprParser : public ScriptParserBase {
64public:
65 ExprParser(std::vector<StringRef> &Tokens, uint64_t Dot)
66 : ScriptParserBase(Tokens), Dot(Dot) {}
67
68 uint64_t run();
69
70private:
71 uint64_t parsePrimary();
72 uint64_t parseTernary(uint64_t Cond);
73 uint64_t apply(StringRef Op, uint64_t L, uint64_t R);
74 uint64_t parseExpr1(uint64_t Lhs, int MinPrec);
75 uint64_t parseExpr();
76
77 uint64_t Dot;
78};
79}
80
Rui Ueyama960504b2016-04-19 18:58:11 +000081static int precedence(StringRef Op) {
82 return StringSwitch<int>(Op)
83 .Case("*", 4)
George Rimarab939062016-04-25 08:14:41 +000084 .Case("/", 4)
85 .Case("+", 3)
86 .Case("-", 3)
87 .Case("<", 2)
88 .Case(">", 2)
89 .Case(">=", 2)
90 .Case("<=", 2)
91 .Case("==", 2)
92 .Case("!=", 2)
Rui Ueyama960504b2016-04-19 18:58:11 +000093 .Case("&", 1)
94 .Default(-1);
95}
96
Rui Ueyama9c1112d2016-04-23 00:04:03 +000097static uint64_t evalExpr(std::vector<StringRef> &Tokens, uint64_t Dot) {
98 return ExprParser(Tokens, Dot).run();
Rui Ueyama960504b2016-04-19 18:58:11 +000099}
100
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000101uint64_t ExprParser::run() {
102 uint64_t V = parseExpr();
103 if (!atEOF() && !Error)
104 setError("stray token: " + peek());
105 return V;
Rui Ueyama60118112016-04-20 20:54:13 +0000106}
107
George Rimar92e93fb2016-07-21 19:48:00 +0000108uint64_t static getConstantValue(StringRef C) {
109 if (C == "COMMONPAGESIZE" || C == "MAXPAGESIZE")
110 return Target->PageSize;
111 error("unknown constant: " + C);
112 return 0;
113}
114
Rui Ueyama960504b2016-04-19 18:58:11 +0000115// This is a part of the operator-precedence parser to evaluate
116// arithmetic expressions in SECTIONS command. This function evaluates an
Rui Ueyamae29a9752016-04-22 21:02:27 +0000117// integer literal, a parenthesized expression, the ALIGN function,
118// or the special variable ".".
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000119uint64_t ExprParser::parsePrimary() {
120 StringRef Tok = next();
Rui Ueyama960504b2016-04-19 18:58:11 +0000121 if (Tok == ".")
122 return Dot;
123 if (Tok == "(") {
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000124 uint64_t V = parseExpr();
125 expect(")");
Rui Ueyama960504b2016-04-19 18:58:11 +0000126 return V;
127 }
George Rimardffc1412016-04-22 11:40:53 +0000128 if (Tok == "ALIGN") {
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000129 expect("(");
130 uint64_t V = parseExpr();
131 expect(")");
George Rimardffc1412016-04-22 11:40:53 +0000132 return alignTo(Dot, V);
133 }
George Rimar92e93fb2016-07-21 19:48:00 +0000134 if (Tok == "CONSTANT") {
135 expect("(");
136 uint64_t V = getConstantValue(next());
137 expect(")");
138 return V;
139 }
140 // Documentations says there are two ways to compute
141 // the value of DATA_SEGMENT_ALIGN command, depending on whether the second
142 // uses fewer COMMONPAGESIZE sized pages for the data segment(area between the
143 // result of this expression and `DATA_SEGMENT_END') than the first or not.
144 // That is possible optimization, that we do not support, so we compute that
145 // function always as (ALIGN(MAXPAGESIZE) + (. & (MAXPAGESIZE - 1))) now.
146 if (Tok == "DATA_SEGMENT_ALIGN") {
147 expect("(");
148 uint64_t L = parseExpr();
149 expect(",");
150 parseExpr();
151 expect(")");
152 return alignTo(Dot, L) + (Dot & (L - 1));
153 }
154 // Since we do not support the optimization from comment above,
155 // we can just ignore that command.
156 if (Tok == "DATA_SEGMENT_END") {
157 expect("(");
158 expect(".");
159 expect(")");
160 return Dot;
161 }
Rui Ueyama5fa60982016-04-22 21:05:04 +0000162 uint64_t V = 0;
163 if (Tok.getAsInteger(0, V))
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000164 setError("malformed number: " + Tok);
Rui Ueyama5fa60982016-04-22 21:05:04 +0000165 return V;
Rui Ueyama960504b2016-04-19 18:58:11 +0000166}
167
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000168uint64_t ExprParser::parseTernary(uint64_t Cond) {
169 next();
170 uint64_t V = parseExpr();
171 expect(":");
172 uint64_t W = parseExpr();
George Rimarfba45c42016-04-22 11:28:54 +0000173 return Cond ? V : W;
174}
175
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000176uint64_t ExprParser::apply(StringRef Op, uint64_t L, uint64_t R) {
Rui Ueyama960504b2016-04-19 18:58:11 +0000177 if (Op == "*")
178 return L * R;
179 if (Op == "/") {
180 if (R == 0) {
181 error("division by zero");
George Rimar652852c2016-04-16 10:10:32 +0000182 return 0;
183 }
Rui Ueyama960504b2016-04-19 18:58:11 +0000184 return L / R;
George Rimar652852c2016-04-16 10:10:32 +0000185 }
George Rimarab939062016-04-25 08:14:41 +0000186 if (Op == "+")
187 return L + R;
188 if (Op == "-")
189 return L - R;
190 if (Op == "<")
191 return L < R;
192 if (Op == ">")
193 return L > R;
194 if (Op == ">=")
195 return L >= R;
196 if (Op == "<=")
197 return L <= R;
198 if (Op == "==")
199 return L == R;
200 if (Op == "!=")
201 return L != R;
Rui Ueyama960504b2016-04-19 18:58:11 +0000202 if (Op == "&")
203 return L & R;
Rui Ueyama7a81d672016-04-19 19:04:03 +0000204 llvm_unreachable("invalid operator");
Rui Ueyama960504b2016-04-19 18:58:11 +0000205}
206
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000207// This is a part of the operator-precedence parser.
208// This function assumes that the remaining token stream starts
209// with an operator.
210uint64_t ExprParser::parseExpr1(uint64_t Lhs, int MinPrec) {
211 while (!atEOF()) {
Rui Ueyama960504b2016-04-19 18:58:11 +0000212 // Read an operator and an expression.
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000213 StringRef Op1 = peek();
George Rimarfba45c42016-04-22 11:28:54 +0000214 if (Op1 == "?")
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000215 return parseTernary(Lhs);
Rui Ueyama960504b2016-04-19 18:58:11 +0000216 if (precedence(Op1) < MinPrec)
217 return Lhs;
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000218 next();
219 uint64_t Rhs = parsePrimary();
Rui Ueyama960504b2016-04-19 18:58:11 +0000220
221 // Evaluate the remaining part of the expression first if the
222 // next operator has greater precedence than the previous one.
223 // For example, if we have read "+" and "3", and if the next
224 // operator is "*", then we'll evaluate 3 * ... part first.
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000225 while (!atEOF()) {
226 StringRef Op2 = peek();
Rui Ueyama960504b2016-04-19 18:58:11 +0000227 if (precedence(Op2) <= precedence(Op1))
228 break;
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000229 Rhs = parseExpr1(Rhs, precedence(Op2));
Rui Ueyama960504b2016-04-19 18:58:11 +0000230 }
231
232 Lhs = apply(Op1, Lhs, Rhs);
233 }
234 return Lhs;
235}
236
Rui Ueyama9c1112d2016-04-23 00:04:03 +0000237// Reads and evaluates an arithmetic expression.
238uint64_t ExprParser::parseExpr() { return parseExpr1(parsePrimary(), 0); }
George Rimar652852c2016-04-16 10:10:32 +0000239
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000240template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000241bool LinkerScript<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +0000242 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +0000243}
244
Rui Ueyama07320e42016-04-20 20:13:41 +0000245template <class ELFT>
246bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000247 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +0000248 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000249 return true;
250 return false;
George Rimar481c2ce2016-02-23 07:47:54 +0000251}
252
George Rimareea31142016-07-21 14:26:59 +0000253static bool match(StringRef Pattern, ArrayRef<StringRef> Arr) {
254 for (StringRef S : Arr)
255 if (globMatch(S, Pattern))
256 return true;
257 return false;
258}
259
George Rimar652852c2016-04-16 10:10:32 +0000260template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000261std::vector<OutputSectionBase<ELFT> *>
Eugene Leviante63d81b2016-07-20 14:43:20 +0000262LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
George Rimareea31142016-07-21 14:26:59 +0000263 typedef const std::unique_ptr<ObjectFile<ELFT>> ObjectFile;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000264 std::vector<OutputSectionBase<ELFT> *> Result;
265
Eugene Leviante63d81b2016-07-20 14:43:20 +0000266 // Add input section to output section. If there is no output section yet,
267 // then create it and add to output section list.
268 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name) {
269 OutputSectionBase<ELFT> *Sec;
270 bool IsNew;
271 std::tie(Sec, IsNew) = Factory.create(C, Name);
272 if (IsNew)
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000273 Result.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000274 Sec->addSection(C);
275 };
276
277 // Select input sections matching rule and add them to corresponding
278 // output section. Section rules are processed in order they're listed
279 // in script, so correct input section order is maintained by design.
George Rimareea31142016-07-21 14:26:59 +0000280 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
281 auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
282 if (!OutCmd)
283 continue;
284
285 for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
286 auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
287 if (!InCmd)
288 continue;
289
290 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
291 for (InputSectionBase<ELFT> *S : F->getSections()) {
292 if (isDiscarded(S) || S->OutSec)
293 continue;
294
295 if (match(S->getSectionName(), InCmd->Patterns)) {
296 if (OutCmd->Name == "/DISCARD/")
297 S->Live = false;
298 else
299 AddInputSec(S, OutCmd->Name);
300 }
301 }
302 }
303 }
304 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000305
306 // Add all other input sections, which are not listed in script.
George Rimareea31142016-07-21 14:26:59 +0000307 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000308 for (InputSectionBase<ELFT> *S : F->getSections()) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000309 if (!isDiscarded(S)) {
310 if (!S->OutSec)
311 AddInputSec(S, getOutputSectionName(S));
312 } else
313 reportDiscarded(S, F);
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000314 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000315
316 return Result;
317}
318
319template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000320void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
321 uint64_t Val = evalExpr(Cmd->Expr, Dot);
322 if (Cmd->Name == ".") {
323 Dot = Val;
324 } else {
325 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
326 D->Value = Val;
327 }
328}
329
330template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000331void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000332 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000333 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000334 // are not explicitly placed into the output file by the linker script.
335 // We place orphan sections at end of file.
336 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000337 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000338 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000339 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000340 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000341 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000342 }
George Rimar652852c2016-04-16 10:10:32 +0000343
Rui Ueyama7c18c282016-04-18 21:00:40 +0000344 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000345 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000346 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000347 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000348
George Rimar076fe152016-07-21 06:43:01 +0000349 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
350 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000351 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000352 continue;
353 }
354
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000355 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000356 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000357 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000358 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000359 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000360 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000361 continue;
George Rimar652852c2016-04-16 10:10:32 +0000362
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000363 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
364 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000365 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000366 Sec->setVA(TVA);
367 ThreadBssOffset = TVA - Dot + Sec->getSize();
368 continue;
369 }
George Rimar652852c2016-04-16 10:10:32 +0000370
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000371 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000372 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000373 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000374 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000375 Dot += Sec->getSize();
376 continue;
377 }
George Rimar652852c2016-04-16 10:10:32 +0000378 }
379 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000380
Rafael Espindola64c32d62016-07-07 14:28:47 +0000381 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000382 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000383 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
384 Out<ELFT>::ProgramHeaders->getSize(),
385 Target->PageSize);
386 Out<ELFT>::ElfHeader->setVA(MinVA);
387 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000388}
389
Rui Ueyama07320e42016-04-20 20:13:41 +0000390template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000391std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000392LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
393 int TlsNum = -1;
394 int NoteNum = -1;
395 int RelroNum = -1;
396 Phdr *Load = nullptr;
397 uintX_t Flags = PF_R;
398 std::vector<Phdr> Phdrs;
399
400 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Eugene Leviant865bf862016-07-21 10:43:25 +0000401 Phdrs.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000402 Phdr &Added = Phdrs.back();
403
404 if (Cmd.HasFilehdr)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000405 Added.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000406 if (Cmd.HasPhdrs)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000407 Added.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000408
409 switch (Cmd.Type) {
410 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000411 if (Out<ELFT>::Interp)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000412 Added.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000413 break;
414 case PT_DYNAMIC:
415 if (isOutputDynamic<ELFT>()) {
416 Added.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
Rui Ueyama18f084f2016-07-20 19:36:41 +0000417 Added.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000418 }
419 break;
420 case PT_TLS:
421 TlsNum = Phdrs.size() - 1;
422 break;
423 case PT_NOTE:
424 NoteNum = Phdrs.size() - 1;
425 break;
426 case PT_GNU_RELRO:
427 RelroNum = Phdrs.size() - 1;
428 break;
429 case PT_GNU_EH_FRAME:
430 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
431 Added.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
Rui Ueyama18f084f2016-07-20 19:36:41 +0000432 Added.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000433 }
434 break;
435 }
436 }
437
438 for (OutputSectionBase<ELFT> *Sec : Sections) {
439 if (!(Sec->getFlags() & SHF_ALLOC))
440 break;
441
442 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000443 Phdrs[TlsNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000444
445 if (!needsPtLoad<ELFT>(Sec))
446 continue;
447
448 const std::vector<size_t> &PhdrIds =
449 getPhdrIndicesForSection(Sec->getName());
450 if (!PhdrIds.empty()) {
451 // Assign headers specified by linker script
452 for (size_t Id : PhdrIds) {
Rui Ueyama18f084f2016-07-20 19:36:41 +0000453 Phdrs[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000454 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
455 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000456 }
457 } else {
458 // If we have no load segment or flags've changed then we want new load
459 // segment.
460 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
461 if (Load == nullptr || Flags != NewFlags) {
462 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
463 Flags = NewFlags;
464 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000465 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000466 }
467
468 if (RelroNum != -1 && isRelroSection(Sec))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000469 Phdrs[RelroNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000470 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000471 Phdrs[NoteNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000472 }
473 return Phdrs;
474}
475
476template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000477ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000478 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
479 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
480 if (Cmd->Name == Name)
481 return Cmd->Filler;
482 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000483}
484
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000485// Returns the index of the given section name in linker script
486// SECTIONS commands. Sections are laid out as the same order as they
487// were in the script. If a given name did not appear in the script,
488// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000489template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000490 auto Begin = Opt.Commands.begin();
491 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000492 auto I =
493 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
494 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
495 if (Cmd->Name == Name)
496 return true;
497 return false;
498 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000499 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000500}
501
502// A compartor to sort output sections. Returns -1 or 1 if
503// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000504template <class ELFT>
505int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000506 int I = getSectionIndex(A);
507 int J = getSectionIndex(B);
508 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000509 return 0;
510 return I < J ? -1 : 1;
511}
512
George Rimar076fe152016-07-21 06:43:01 +0000513template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
514 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
515 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
516 if (Cmd->Name != "." && Symtab<ELFT>::X->find(Cmd->Name) == nullptr)
517 Symtab<ELFT>::X->addAbsolute(Cmd->Name, STV_DEFAULT);
Eugene Levianteda81a12016-07-12 06:39:48 +0000518}
519
Eugene Leviantbbe38602016-07-19 09:25:43 +0000520template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
521 return !Opt.PhdrsCommands.empty();
522}
523
524// Returns indices of ELF headers containing specific section, identified
525// by Name. Each index is a zero based number of ELF header listed within
526// PHDRS {} script block.
527template <class ELFT>
528std::vector<size_t>
529LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
George Rimar076fe152016-07-21 06:43:01 +0000530 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
531 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
532 if (!Cmd || Cmd->Name != Name)
George Rimar31d842f2016-07-20 16:43:03 +0000533 continue;
534
535 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000536 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000537 auto ItPhdr =
538 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000539 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000540 if (ItPhdr == Opt.PhdrsCommands.rend())
541 error("section header '" + PhdrName + "' is not listed in PHDRS");
542 else
543 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
544 }
George Rimar31d842f2016-07-20 16:43:03 +0000545 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000546 }
George Rimar31d842f2016-07-20 16:43:03 +0000547 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000548}
549
Rui Ueyama07320e42016-04-20 20:13:41 +0000550class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000551 typedef void (ScriptParser::*Handler)();
552
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000553public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000554 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000555
Rui Ueyama4a465392016-04-22 22:59:24 +0000556 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000557
558private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000559 void addFile(StringRef Path);
560
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000561 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000562 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000563 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000564 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000565 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000566 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000567 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000568 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000569 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000570 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000571 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000572 void readSections();
573
George Rimar652852c2016-04-16 10:10:32 +0000574 void readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000575 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000576 std::vector<StringRef> readOutputSectionPhdrs();
577 unsigned readPhdrType();
Eugene Levianteda81a12016-07-12 06:39:48 +0000578 void readSymbolAssignment(StringRef Name);
579 std::vector<StringRef> readSectionsCommandExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000580
George Rimarc3794e52016-02-24 09:21:47 +0000581 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000582 ScriptConfiguration &Opt = *ScriptConfig;
583 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000584 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000585};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000586
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000587const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000588 {"ENTRY", &ScriptParser::readEntry},
589 {"EXTERN", &ScriptParser::readExtern},
590 {"GROUP", &ScriptParser::readGroup},
591 {"INCLUDE", &ScriptParser::readInclude},
592 {"INPUT", &ScriptParser::readGroup},
593 {"OUTPUT", &ScriptParser::readOutput},
594 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
595 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000596 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000597 {"SEARCH_DIR", &ScriptParser::readSearchDir},
598 {"SECTIONS", &ScriptParser::readSections},
599 {";", &ScriptParser::readNothing}};
600
Rui Ueyama717677a2016-02-11 21:17:59 +0000601void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000602 while (!atEOF()) {
603 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000604 if (Handler Fn = Cmd.lookup(Tok))
605 (this->*Fn)();
606 else
George Rimar57610422016-03-11 14:43:02 +0000607 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000608 }
609}
610
Rui Ueyama717677a2016-02-11 21:17:59 +0000611void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000612 if (IsUnderSysroot && S.startswith("/")) {
613 SmallString<128> Path;
614 (Config->Sysroot + S).toStringRef(Path);
615 if (sys::fs::exists(Path)) {
616 Driver->addFile(Saver.save(Path.str()));
617 return;
618 }
619 }
620
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000621 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000622 Driver->addFile(S);
623 } else if (S.startswith("=")) {
624 if (Config->Sysroot.empty())
625 Driver->addFile(S.substr(1));
626 else
627 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
628 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000629 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000630 } else if (sys::fs::exists(S)) {
631 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000632 } else {
633 std::string Path = findFromSearchPaths(S);
634 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000635 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000636 else
637 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000638 }
639}
640
Rui Ueyama717677a2016-02-11 21:17:59 +0000641void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000642 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000643 bool Orig = Config->AsNeeded;
644 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000645 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000646 StringRef Tok = next();
647 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000648 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000649 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000650 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000651 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000652}
653
Rui Ueyama717677a2016-02-11 21:17:59 +0000654void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000655 // -e <symbol> takes predecence over ENTRY(<symbol>).
656 expect("(");
657 StringRef Tok = next();
658 if (Config->Entry.empty())
659 Config->Entry = Tok;
660 expect(")");
661}
662
Rui Ueyama717677a2016-02-11 21:17:59 +0000663void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000664 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000665 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000666 StringRef Tok = next();
667 if (Tok == ")")
668 return;
669 Config->Undefined.push_back(Tok);
670 }
671}
672
Rui Ueyama717677a2016-02-11 21:17:59 +0000673void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000674 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000675 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000676 StringRef Tok = next();
677 if (Tok == ")")
678 return;
679 if (Tok == "AS_NEEDED") {
680 readAsNeeded();
681 continue;
682 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000683 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000684 }
685}
686
Rui Ueyama717677a2016-02-11 21:17:59 +0000687void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000688 StringRef Tok = next();
689 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000690 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000691 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000692 return;
693 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000694 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000695 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
696 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000697 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000698}
699
Rui Ueyama717677a2016-02-11 21:17:59 +0000700void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000701 // -o <file> takes predecence over OUTPUT(<file>).
702 expect("(");
703 StringRef Tok = next();
704 if (Config->OutputFile.empty())
705 Config->OutputFile = Tok;
706 expect(")");
707}
708
Rui Ueyama717677a2016-02-11 21:17:59 +0000709void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000710 // Error checking only for now.
711 expect("(");
712 next();
713 expect(")");
714}
715
Rui Ueyama717677a2016-02-11 21:17:59 +0000716void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000717 // Error checking only for now.
718 expect("(");
719 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000720 StringRef Tok = next();
721 if (Tok == ")")
722 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000723 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000724 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000725 return;
726 }
Davide Italiano6836c612015-10-12 21:08:41 +0000727 next();
728 expect(",");
729 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000730 expect(")");
731}
732
Eugene Leviantbbe38602016-07-19 09:25:43 +0000733void ScriptParser::readPhdrs() {
734 expect("{");
735 while (!Error && !skip("}")) {
736 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000737 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000738 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
739
740 PhdrCmd.Type = readPhdrType();
741 do {
742 Tok = next();
743 if (Tok == ";")
744 break;
745 if (Tok == "FILEHDR")
746 PhdrCmd.HasFilehdr = true;
747 else if (Tok == "PHDRS")
748 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000749 else if (Tok == "FLAGS") {
750 expect("(");
751 next().getAsInteger(0, PhdrCmd.Flags);
752 expect(")");
753 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000754 setError("unexpected header attribute: " + Tok);
755 } while (!Error);
756 }
757}
758
Rui Ueyama717677a2016-02-11 21:17:59 +0000759void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000760 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000761 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000762 expect(")");
763}
764
Rui Ueyama717677a2016-02-11 21:17:59 +0000765void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000766 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000767 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000768 while (!Error && !skip("}")) {
769 StringRef Tok = peek();
Eugene Levianteda81a12016-07-12 06:39:48 +0000770 if (Tok == ".") {
George Rimar652852c2016-04-16 10:10:32 +0000771 readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000772 continue;
773 }
774 next();
775 if (peek() == "=")
776 readSymbolAssignment(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000777 else
Eugene Levianteda81a12016-07-12 06:39:48 +0000778 readOutputSectionDescription(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000779 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000780}
781
George Rimar652852c2016-04-16 10:10:32 +0000782void ScriptParser::readLocationCounterValue() {
783 expect(".");
784 expect("=");
Eugene Levianteda81a12016-07-12 06:39:48 +0000785 std::vector<StringRef> Expr = readSectionsCommandExpr();
786 if (Expr.empty())
George Rimar652852c2016-04-16 10:10:32 +0000787 error("error in location counter expression");
Eugene Levianteda81a12016-07-12 06:39:48 +0000788 else
George Rimar076fe152016-07-21 06:43:01 +0000789 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(".", Expr));
George Rimar652852c2016-04-16 10:10:32 +0000790}
791
Eugene Levianteda81a12016-07-12 06:39:48 +0000792void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000793 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
794 Opt.Commands.emplace_back(Cmd);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000795 expect(":");
796 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000797
Rui Ueyama025d59b2016-02-02 20:27:59 +0000798 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000799 StringRef Tok = next();
800 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000801 auto *InCmd = new InputSectionDescription();
802 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000803 expect("(");
804 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000805 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000806 } else if (Tok == "KEEP") {
807 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000808 expect("*");
809 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000810 auto *InCmd = new InputSectionDescription();
811 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000812 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000813 Opt.KeptSections.push_back(peek());
814 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000815 }
George Rimar481c2ce2016-02-23 07:47:54 +0000816 expect(")");
817 } else {
George Rimar777f9632016-03-12 08:31:34 +0000818 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000819 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000820 }
George Rimar076fe152016-07-21 06:43:01 +0000821 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000822
George Rimare2ee72b2016-02-26 14:48:31 +0000823 StringRef Tok = peek();
824 if (Tok.startswith("=")) {
825 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000826 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000827 return;
828 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000829 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000830 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000831 next();
832 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000833}
834
Eugene Levianteda81a12016-07-12 06:39:48 +0000835void ScriptParser::readSymbolAssignment(StringRef Name) {
836 expect("=");
837 std::vector<StringRef> Expr = readSectionsCommandExpr();
838 if (Expr.empty())
839 error("error in symbol assignment expression");
840 else
George Rimar076fe152016-07-21 06:43:01 +0000841 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(Name, Expr));
Eugene Levianteda81a12016-07-12 06:39:48 +0000842}
843
844std::vector<StringRef> ScriptParser::readSectionsCommandExpr() {
845 std::vector<StringRef> Expr;
846 while (!Error) {
847 StringRef Tok = next();
848 if (Tok == ";")
849 break;
850 Expr.push_back(Tok);
851 }
852 return Expr;
853}
854
Eugene Leviantbbe38602016-07-19 09:25:43 +0000855std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
856 std::vector<StringRef> Phdrs;
857 while (!Error && peek().startswith(":")) {
858 StringRef Tok = next();
859 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
860 if (Tok.empty()) {
861 setError("section header name is empty");
862 break;
863 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000864 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000865 }
866 return Phdrs;
867}
868
869unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000870 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000871 unsigned Ret = StringSwitch<unsigned>(Tok)
872 .Case("PT_NULL", PT_NULL)
873 .Case("PT_LOAD", PT_LOAD)
874 .Case("PT_DYNAMIC", PT_DYNAMIC)
875 .Case("PT_INTERP", PT_INTERP)
876 .Case("PT_NOTE", PT_NOTE)
877 .Case("PT_SHLIB", PT_SHLIB)
878 .Case("PT_PHDR", PT_PHDR)
879 .Case("PT_TLS", PT_TLS)
880 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
881 .Case("PT_GNU_STACK", PT_GNU_STACK)
882 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
883 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000884
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000885 if (Ret == (unsigned)-1) {
886 setError("invalid program header type: " + Tok);
887 return PT_NULL;
888 }
889 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000890}
891
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000892static bool isUnderSysroot(StringRef Path) {
893 if (Config->Sysroot == "")
894 return false;
895 for (; !Path.empty(); Path = sys::path::parent_path(Path))
896 if (sys::fs::equivalent(Config->Sysroot, Path))
897 return true;
898 return false;
899}
900
Rui Ueyama07320e42016-04-20 20:13:41 +0000901// Entry point.
902void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000903 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000904 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000905}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000906
Rui Ueyama07320e42016-04-20 20:13:41 +0000907template class elf::LinkerScript<ELF32LE>;
908template class elf::LinkerScript<ELF32BE>;
909template class elf::LinkerScript<ELF64LE>;
910template class elf::LinkerScript<ELF64BE>;