blob: 7c1a0ca3ff1c3524e48556a26d6a8761e4aff000 [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;
Davide Italiano246f6812016-07-22 03:36:24 +0000265 DenseSet<OutputSectionBase<ELFT> *> Removed;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000266
Eugene Leviante63d81b2016-07-20 14:43:20 +0000267 // Add input section to output section. If there is no output section yet,
268 // then create it and add to output section list.
Davide Italiano246f6812016-07-22 03:36:24 +0000269 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name,
270 ConstraintKind Constraint) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000271 OutputSectionBase<ELFT> *Sec;
272 bool IsNew;
273 std::tie(Sec, IsNew) = Factory.create(C, Name);
274 if (IsNew)
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000275 Result.push_back(Sec);
Davide Italiano246f6812016-07-22 03:36:24 +0000276 if ((!(C->getSectionHdr()->sh_flags & SHF_WRITE)) &&
277 Constraint == ReadWrite) {
278 Removed.insert(Sec);
279 return;
280 }
281 if ((C->getSectionHdr()->sh_flags & SHF_WRITE) && Constraint == ReadOnly) {
282 Removed.insert(Sec);
283 return;
284 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000285 Sec->addSection(C);
286 };
287
288 // Select input sections matching rule and add them to corresponding
289 // output section. Section rules are processed in order they're listed
290 // in script, so correct input section order is maintained by design.
George Rimareea31142016-07-21 14:26:59 +0000291 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
292 auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
293 if (!OutCmd)
294 continue;
295
296 for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
297 auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
298 if (!InCmd)
299 continue;
300
301 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
302 for (InputSectionBase<ELFT> *S : F->getSections()) {
303 if (isDiscarded(S) || S->OutSec)
304 continue;
305
306 if (match(S->getSectionName(), InCmd->Patterns)) {
307 if (OutCmd->Name == "/DISCARD/")
308 S->Live = false;
309 else
Davide Italiano246f6812016-07-22 03:36:24 +0000310 AddInputSec(S, OutCmd->Name, OutCmd->Constraint);
George Rimareea31142016-07-21 14:26:59 +0000311 }
312 }
313 }
314 }
315 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000316
317 // Add all other input sections, which are not listed in script.
George Rimareea31142016-07-21 14:26:59 +0000318 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000319 for (InputSectionBase<ELFT> *S : F->getSections()) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000320 if (!isDiscarded(S)) {
321 if (!S->OutSec)
Davide Italiano246f6812016-07-22 03:36:24 +0000322 AddInputSec(S, getOutputSectionName(S), NoConstraint);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000323 } else
324 reportDiscarded(S, F);
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000325 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000326
Davide Italiano246f6812016-07-22 03:36:24 +0000327 // Remove from the output all the sections which did not met the constraints.
328 Result.erase(std::remove_if(Result.begin(), Result.end(),
329 [&](OutputSectionBase<ELFT> *Sec) {
330 return Removed.count(Sec);
331 }),
332 Result.end());
Eugene Leviante63d81b2016-07-20 14:43:20 +0000333 return Result;
334}
335
336template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000337void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
338 uint64_t Val = evalExpr(Cmd->Expr, Dot);
339 if (Cmd->Name == ".") {
340 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000341 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000342 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
343 D->Value = Val;
344 }
345}
346
347template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000348void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000349 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000350 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000351 // are not explicitly placed into the output file by the linker script.
352 // We place orphan sections at end of file.
353 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000354 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000355 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000356 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000357 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000358 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000359 }
George Rimar652852c2016-04-16 10:10:32 +0000360
Rui Ueyama7c18c282016-04-18 21:00:40 +0000361 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000362 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000363 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000364 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000365
George Rimar076fe152016-07-21 06:43:01 +0000366 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
367 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000368 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000369 continue;
370 }
371
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000372 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000373 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000374 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000375 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000376 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000377 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000378 continue;
George Rimar652852c2016-04-16 10:10:32 +0000379
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000380 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
381 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000382 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000383 Sec->setVA(TVA);
384 ThreadBssOffset = TVA - Dot + Sec->getSize();
385 continue;
386 }
George Rimar652852c2016-04-16 10:10:32 +0000387
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000388 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000389 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000390 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000391 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000392 Dot += Sec->getSize();
393 continue;
394 }
George Rimar652852c2016-04-16 10:10:32 +0000395 }
396 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000397
Rafael Espindola64c32d62016-07-07 14:28:47 +0000398 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000399 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000400 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
401 Out<ELFT>::ProgramHeaders->getSize(),
402 Target->PageSize);
403 Out<ELFT>::ElfHeader->setVA(MinVA);
404 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000405}
406
Rui Ueyama07320e42016-04-20 20:13:41 +0000407template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000408std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000409LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
410 int TlsNum = -1;
411 int NoteNum = -1;
412 int RelroNum = -1;
413 Phdr *Load = nullptr;
414 uintX_t Flags = PF_R;
415 std::vector<Phdr> Phdrs;
416
417 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Eugene Leviant865bf862016-07-21 10:43:25 +0000418 Phdrs.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000419 Phdr &Added = Phdrs.back();
420
421 if (Cmd.HasFilehdr)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000422 Added.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000423 if (Cmd.HasPhdrs)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000424 Added.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000425
426 switch (Cmd.Type) {
427 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000428 if (Out<ELFT>::Interp)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000429 Added.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000430 break;
431 case PT_DYNAMIC:
432 if (isOutputDynamic<ELFT>()) {
433 Added.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
Rui Ueyama18f084f2016-07-20 19:36:41 +0000434 Added.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000435 }
436 break;
437 case PT_TLS:
438 TlsNum = Phdrs.size() - 1;
439 break;
440 case PT_NOTE:
441 NoteNum = Phdrs.size() - 1;
442 break;
443 case PT_GNU_RELRO:
444 RelroNum = Phdrs.size() - 1;
445 break;
446 case PT_GNU_EH_FRAME:
447 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
448 Added.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
Rui Ueyama18f084f2016-07-20 19:36:41 +0000449 Added.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000450 }
451 break;
452 }
453 }
454
455 for (OutputSectionBase<ELFT> *Sec : Sections) {
456 if (!(Sec->getFlags() & SHF_ALLOC))
457 break;
458
459 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000460 Phdrs[TlsNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000461
462 if (!needsPtLoad<ELFT>(Sec))
463 continue;
464
465 const std::vector<size_t> &PhdrIds =
466 getPhdrIndicesForSection(Sec->getName());
467 if (!PhdrIds.empty()) {
468 // Assign headers specified by linker script
469 for (size_t Id : PhdrIds) {
Rui Ueyama18f084f2016-07-20 19:36:41 +0000470 Phdrs[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000471 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
472 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000473 }
474 } else {
475 // If we have no load segment or flags've changed then we want new load
476 // segment.
477 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
478 if (Load == nullptr || Flags != NewFlags) {
479 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
480 Flags = NewFlags;
481 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000482 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000483 }
484
485 if (RelroNum != -1 && isRelroSection(Sec))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000486 Phdrs[RelroNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000488 Phdrs[NoteNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000489 }
490 return Phdrs;
491}
492
493template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000494ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000495 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
496 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
497 if (Cmd->Name == Name)
498 return Cmd->Filler;
499 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000500}
501
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000502// Returns the index of the given section name in linker script
503// SECTIONS commands. Sections are laid out as the same order as they
504// were in the script. If a given name did not appear in the script,
505// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000506template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000507 auto Begin = Opt.Commands.begin();
508 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000509 auto I =
510 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
511 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
512 if (Cmd->Name == Name)
513 return true;
514 return false;
515 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000516 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000517}
518
519// A compartor to sort output sections. Returns -1 or 1 if
520// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000521template <class ELFT>
522int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000523 int I = getSectionIndex(A);
524 int J = getSectionIndex(B);
525 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000526 return 0;
527 return I < J ? -1 : 1;
528}
529
George Rimar076fe152016-07-21 06:43:01 +0000530template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000531 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
532 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
533 if (!Cmd || Cmd->Name == ".")
534 continue;
535
536 if (Symtab<ELFT>::X->find(Cmd->Name) == nullptr)
537 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
538 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
539 else
540 // Symbol already exists in symbol table. If it is provided
541 // then we can't override its value.
542 Cmd->Ignore = Cmd->Provide;
543 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000544}
545
Eugene Leviantbbe38602016-07-19 09:25:43 +0000546template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
547 return !Opt.PhdrsCommands.empty();
548}
549
550// Returns indices of ELF headers containing specific section, identified
551// by Name. Each index is a zero based number of ELF header listed within
552// PHDRS {} script block.
553template <class ELFT>
554std::vector<size_t>
555LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
George Rimar076fe152016-07-21 06:43:01 +0000556 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
557 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
558 if (!Cmd || Cmd->Name != Name)
George Rimar31d842f2016-07-20 16:43:03 +0000559 continue;
560
561 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000562 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000563 auto ItPhdr =
564 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000565 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000566 if (ItPhdr == Opt.PhdrsCommands.rend())
567 error("section header '" + PhdrName + "' is not listed in PHDRS");
568 else
569 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
570 }
George Rimar31d842f2016-07-20 16:43:03 +0000571 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000572 }
George Rimar31d842f2016-07-20 16:43:03 +0000573 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000574}
575
Rui Ueyama07320e42016-04-20 20:13:41 +0000576class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000577 typedef void (ScriptParser::*Handler)();
578
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000579public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000580 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000581
Rui Ueyama4a465392016-04-22 22:59:24 +0000582 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000583
584private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000585 void addFile(StringRef Path);
586
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000587 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000588 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000589 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000590 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000591 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000592 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000593 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000594 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000595 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000596 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000597 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000598 void readSections();
599
George Rimar652852c2016-04-16 10:10:32 +0000600 void readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000601 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000602 std::vector<StringRef> readOutputSectionPhdrs();
603 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000604 void readProvide(bool Hidden);
605 SymbolAssignment *readSymbolAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000606 std::vector<StringRef> readSectionsCommandExpr();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000607
George Rimarc3794e52016-02-24 09:21:47 +0000608 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000609 ScriptConfiguration &Opt = *ScriptConfig;
610 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000611 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000612};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000613
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000614const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000615 {"ENTRY", &ScriptParser::readEntry},
616 {"EXTERN", &ScriptParser::readExtern},
617 {"GROUP", &ScriptParser::readGroup},
618 {"INCLUDE", &ScriptParser::readInclude},
619 {"INPUT", &ScriptParser::readGroup},
620 {"OUTPUT", &ScriptParser::readOutput},
621 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
622 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000623 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000624 {"SEARCH_DIR", &ScriptParser::readSearchDir},
625 {"SECTIONS", &ScriptParser::readSections},
626 {";", &ScriptParser::readNothing}};
627
Rui Ueyama717677a2016-02-11 21:17:59 +0000628void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000629 while (!atEOF()) {
630 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000631 if (Handler Fn = Cmd.lookup(Tok))
632 (this->*Fn)();
633 else
George Rimar57610422016-03-11 14:43:02 +0000634 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000635 }
636}
637
Rui Ueyama717677a2016-02-11 21:17:59 +0000638void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000639 if (IsUnderSysroot && S.startswith("/")) {
640 SmallString<128> Path;
641 (Config->Sysroot + S).toStringRef(Path);
642 if (sys::fs::exists(Path)) {
643 Driver->addFile(Saver.save(Path.str()));
644 return;
645 }
646 }
647
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000648 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000649 Driver->addFile(S);
650 } else if (S.startswith("=")) {
651 if (Config->Sysroot.empty())
652 Driver->addFile(S.substr(1));
653 else
654 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
655 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000656 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000657 } else if (sys::fs::exists(S)) {
658 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000659 } else {
660 std::string Path = findFromSearchPaths(S);
661 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000662 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000663 else
664 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000665 }
666}
667
Rui Ueyama717677a2016-02-11 21:17:59 +0000668void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000669 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000670 bool Orig = Config->AsNeeded;
671 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000672 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000673 StringRef Tok = next();
674 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000675 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000676 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000677 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000678 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000679}
680
Rui Ueyama717677a2016-02-11 21:17:59 +0000681void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000682 // -e <symbol> takes predecence over ENTRY(<symbol>).
683 expect("(");
684 StringRef Tok = next();
685 if (Config->Entry.empty())
686 Config->Entry = Tok;
687 expect(")");
688}
689
Rui Ueyama717677a2016-02-11 21:17:59 +0000690void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000691 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000692 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000693 StringRef Tok = next();
694 if (Tok == ")")
695 return;
696 Config->Undefined.push_back(Tok);
697 }
698}
699
Rui Ueyama717677a2016-02-11 21:17:59 +0000700void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000701 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000702 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000703 StringRef Tok = next();
704 if (Tok == ")")
705 return;
706 if (Tok == "AS_NEEDED") {
707 readAsNeeded();
708 continue;
709 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000710 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("(");
778 next().getAsInteger(0, PhdrCmd.Flags);
779 expect(")");
780 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000781 setError("unexpected header attribute: " + Tok);
782 } while (!Error);
783 }
784}
785
Rui Ueyama717677a2016-02-11 21:17:59 +0000786void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000787 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000788 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000789 expect(")");
790}
791
Rui Ueyama717677a2016-02-11 21:17:59 +0000792void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000793 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000794 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000795 while (!Error && !skip("}")) {
796 StringRef Tok = peek();
Eugene Levianteda81a12016-07-12 06:39:48 +0000797 if (Tok == ".") {
George Rimar652852c2016-04-16 10:10:32 +0000798 readLocationCounterValue();
Eugene Levianteda81a12016-07-12 06:39:48 +0000799 continue;
800 }
801 next();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000802 if (Tok == "PROVIDE")
803 readProvide(false);
804 else if (Tok == "PROVIDE_HIDDEN")
805 readProvide(true);
806 else if (peek() == "=")
Eugene Levianteda81a12016-07-12 06:39:48 +0000807 readSymbolAssignment(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000808 else
Eugene Levianteda81a12016-07-12 06:39:48 +0000809 readOutputSectionDescription(Tok);
George Rimar652852c2016-04-16 10:10:32 +0000810 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000811}
812
George Rimar652852c2016-04-16 10:10:32 +0000813void ScriptParser::readLocationCounterValue() {
814 expect(".");
815 expect("=");
Eugene Levianteda81a12016-07-12 06:39:48 +0000816 std::vector<StringRef> Expr = readSectionsCommandExpr();
817 if (Expr.empty())
George Rimar652852c2016-04-16 10:10:32 +0000818 error("error in location counter expression");
Eugene Levianteda81a12016-07-12 06:39:48 +0000819 else
George Rimar076fe152016-07-21 06:43:01 +0000820 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(".", Expr));
George Rimar652852c2016-04-16 10:10:32 +0000821}
822
Eugene Levianteda81a12016-07-12 06:39:48 +0000823void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000824 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
825 Opt.Commands.emplace_back(Cmd);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000826 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000827
828 // Parse constraints.
829 if (skip("ONLY_IF_RO"))
830 Cmd->Constraint = ReadOnly;
831 if (skip("ONLY_IF_RW"))
832 Cmd->Constraint = ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000833 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000834
Rui Ueyama025d59b2016-02-02 20:27:59 +0000835 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000836 StringRef Tok = next();
837 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000838 auto *InCmd = new InputSectionDescription();
839 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000840 expect("(");
841 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000842 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000843 } else if (Tok == "KEEP") {
844 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000845 expect("*");
846 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000847 auto *InCmd = new InputSectionDescription();
848 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000849 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000850 Opt.KeptSections.push_back(peek());
851 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000852 }
George Rimar481c2ce2016-02-23 07:47:54 +0000853 expect(")");
854 } else {
George Rimar777f9632016-03-12 08:31:34 +0000855 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000856 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000857 }
George Rimar076fe152016-07-21 06:43:01 +0000858 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000859
George Rimare2ee72b2016-02-26 14:48:31 +0000860 StringRef Tok = peek();
861 if (Tok.startswith("=")) {
862 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000863 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000864 return;
865 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000866 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000867 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000868 next();
869 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000870}
871
Eugene Levianta31c91b2016-07-22 07:38:40 +0000872void ScriptParser::readProvide(bool Hidden) {
873 expect("(");
874 if (SymbolAssignment *Assignment = readSymbolAssignment(next())) {
875 Assignment->Provide = true;
876 Assignment->Hidden = Hidden;
877 }
878 expect(")");
879 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000880}
881
Eugene Levianta31c91b2016-07-22 07:38:40 +0000882SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) {
883 expect("=");
884 std::vector<StringRef> Expr = readSectionsCommandExpr();
885 if (Expr.empty()) {
886 error("error in symbol assignment expression");
887 } else {
888 Opt.Commands.push_back(llvm::make_unique<SymbolAssignment>(Name, Expr));
889 return static_cast<SymbolAssignment *>(Opt.Commands.back().get());
890 }
891 return nullptr;
892}
893
894// This function reads balanced expression until semicolon is seen.
Eugene Levianteda81a12016-07-12 06:39:48 +0000895std::vector<StringRef> ScriptParser::readSectionsCommandExpr() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000896 int Braces = 0;
Eugene Levianteda81a12016-07-12 06:39:48 +0000897 std::vector<StringRef> Expr;
898 while (!Error) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000899 StringRef Tok = peek();
900
901 if (Tok == "(")
902 Braces++;
903 else if (Tok == ")")
904 if (--Braces < 0)
905 break;
906
907 next();
Eugene Levianteda81a12016-07-12 06:39:48 +0000908 if (Tok == ";")
909 break;
910 Expr.push_back(Tok);
911 }
912 return Expr;
913}
914
Eugene Leviantbbe38602016-07-19 09:25:43 +0000915std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
916 std::vector<StringRef> Phdrs;
917 while (!Error && peek().startswith(":")) {
918 StringRef Tok = next();
919 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
920 if (Tok.empty()) {
921 setError("section header name is empty");
922 break;
923 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000924 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000925 }
926 return Phdrs;
927}
928
929unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000930 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000931 unsigned Ret = StringSwitch<unsigned>(Tok)
932 .Case("PT_NULL", PT_NULL)
933 .Case("PT_LOAD", PT_LOAD)
934 .Case("PT_DYNAMIC", PT_DYNAMIC)
935 .Case("PT_INTERP", PT_INTERP)
936 .Case("PT_NOTE", PT_NOTE)
937 .Case("PT_SHLIB", PT_SHLIB)
938 .Case("PT_PHDR", PT_PHDR)
939 .Case("PT_TLS", PT_TLS)
940 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
941 .Case("PT_GNU_STACK", PT_GNU_STACK)
942 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
943 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000944
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000945 if (Ret == (unsigned)-1) {
946 setError("invalid program header type: " + Tok);
947 return PT_NULL;
948 }
949 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000950}
951
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000952static bool isUnderSysroot(StringRef Path) {
953 if (Config->Sysroot == "")
954 return false;
955 for (; !Path.empty(); Path = sys::path::parent_path(Path))
956 if (sys::fs::equivalent(Config->Sysroot, Path))
957 return true;
958 return false;
959}
960
Rui Ueyama07320e42016-04-20 20:13:41 +0000961// Entry point.
962void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000963 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000964 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000965}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000966
Rui Ueyama07320e42016-04-20 20:13:41 +0000967template class elf::LinkerScript<ELF32LE>;
968template class elf::LinkerScript<ELF32BE>;
969template class elf::LinkerScript<ELF64LE>;
970template class elf::LinkerScript<ELF64BE>;