Coverage Report

Created: 2018-01-17 17:22

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/ScriptParser.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ScriptParser.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 a recursive-descendent parser for linker scripts.
11
// Parsed results are stored to Config and Script global objects.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "ScriptParser.h"
16
#include "Config.h"
17
#include "Driver.h"
18
#include "InputSection.h"
19
#include "LinkerScript.h"
20
#include "OutputSections.h"
21
#include "ScriptLexer.h"
22
#include "Symbols.h"
23
#include "Target.h"
24
#include "lld/Common/Memory.h"
25
#include "llvm/ADT/SmallString.h"
26
#include "llvm/ADT/StringRef.h"
27
#include "llvm/ADT/StringSet.h"
28
#include "llvm/ADT/StringSwitch.h"
29
#include "llvm/BinaryFormat/ELF.h"
30
#include "llvm/Support/Casting.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include "llvm/Support/FileSystem.h"
33
#include "llvm/Support/Path.h"
34
#include <cassert>
35
#include <limits>
36
#include <vector>
37
38
using namespace llvm;
39
using namespace llvm::ELF;
40
using namespace llvm::support::endian;
41
using namespace lld;
42
using namespace lld::elf;
43
44
static bool isUnderSysroot(StringRef Path);
45
46
namespace {
47
class ScriptParser final : ScriptLexer {
48
public:
49
  ScriptParser(MemoryBufferRef MB)
50
      : ScriptLexer(MB),
51
566
        IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
52
53
  void readLinkerScript();
54
  void readVersionScript();
55
  void readDynamicList();
56
  void readDefsym(StringRef Name);
57
58
private:
59
  void addFile(StringRef Path);
60
61
  void readAsNeeded();
62
  void readEntry();
63
  void readExtern();
64
  void readGroup();
65
  void readInclude();
66
  void readMemory();
67
  void readOutput();
68
  void readOutputArch();
69
  void readOutputFormat();
70
  void readPhdrs();
71
  void readRegionAlias();
72
  void readSearchDir();
73
  void readSections();
74
  void readVersion();
75
  void readVersionScriptCommand();
76
77
  SymbolAssignment *readAssignment(StringRef Name);
78
  ByteCommand *readByteCommand(StringRef Tok);
79
  uint32_t readFill();
80
  uint32_t parseFill(StringRef Tok);
81
  void readSectionAddressType(OutputSection *Cmd);
82
  OutputSection *readOutputSectionDescription(StringRef OutSec);
83
  std::vector<StringRef> readOutputSectionPhdrs();
84
  InputSectionDescription *readInputSectionDescription(StringRef Tok);
85
  StringMatcher readFilePatterns();
86
  std::vector<SectionPattern> readInputSectionsList();
87
  InputSectionDescription *readInputSectionRules(StringRef FilePattern);
88
  unsigned readPhdrType();
89
  SortSectionPolicy readSortKind();
90
  SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
91
  SymbolAssignment *readProvideOrAssignment(StringRef Tok);
92
  void readSort();
93
  AssertCommand *readAssert();
94
  Expr readAssertExpr();
95
  Expr readConstant();
96
  Expr getPageSize();
97
98
  uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
99
  std::pair<uint32_t, uint32_t> readMemoryAttributes();
100
101
  Expr readExpr();
102
  Expr readExpr1(Expr Lhs, int MinPrec);
103
  StringRef readParenLiteral();
104
  Expr readPrimary();
105
  Expr readTernary(Expr Cond);
106
  Expr readParenExpr();
107
108
  // For parsing version script.
109
  std::vector<SymbolVersion> readVersionExtern();
110
  void readAnonymousDeclaration();
111
  void readVersionDeclaration(StringRef VerStr);
112
113
  std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
114
  readSymbols();
115
116
  // True if a script being read is in a subdirectory specified by -sysroot.
117
  bool IsUnderSysroot;
118
119
  // A set to detect an INCLUDE() cycle.
120
  StringSet<> Seen;
121
};
122
} // namespace
123
124
236
static StringRef unquote(StringRef S) {
125
236
  if (S.startswith("\""))
126
69
    return S.substr(1, S.size() - 2);
127
167
  return S;
128
167
}
129
130
566
static bool isUnderSysroot(StringRef Path) {
131
566
  if (Config->Sysroot == "")
132
559
    return false;
133
40
  
for (; 7
!Path.empty();
Path = sys::path::parent_path(Path)33
)
134
34
    if (sys::fs::equivalent(Config->Sysroot, Path))
135
1
      return true;
136
7
  
return false6
;
137
7
}
138
139
// Some operations only support one non absolute value. Move the
140
// absolute one to the right hand side for convenience.
141
145
static void moveAbsRight(ExprValue &A, ExprValue &B) {
142
145
  if (A.Sec == nullptr || 
(71
A.ForceAbsolute71
&&
!B.isAbsolute()9
))
143
76
    std::swap(A, B);
144
145
  if (!B.isAbsolute())
145
1
    error(A.Loc + ": at least one side of the expression must be absolute");
146
145
}
147
148
128
static ExprValue add(ExprValue A, ExprValue B) {
149
128
  moveAbsRight(A, B);
150
128
  return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
151
128
}
152
153
37
static ExprValue sub(ExprValue A, ExprValue B) {
154
37
  // The distance between two symbols in sections is absolute.
155
37
  if (!A.isAbsolute() && 
!B.isAbsolute()24
)
156
2
    return A.getValue() - B.getValue();
157
35
  return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
158
35
}
159
160
14
static ExprValue mul(ExprValue A, ExprValue B) {
161
14
  return A.getValue() * B.getValue();
162
14
}
163
164
5
static ExprValue div(ExprValue A, ExprValue B) {
165
5
  if (uint64_t BV = B.getValue())
166
4
    return A.getValue() / BV;
167
1
  error("division by zero");
168
1
  return 0;
169
1
}
170
171
9
static ExprValue bitAnd(ExprValue A, ExprValue B) {
172
9
  moveAbsRight(A, B);
173
9
  return {A.Sec, A.ForceAbsolute,
174
9
          (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
175
9
}
176
177
8
static ExprValue bitOr(ExprValue A, ExprValue B) {
178
8
  moveAbsRight(A, B);
179
8
  return {A.Sec, A.ForceAbsolute,
180
8
          (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
181
8
}
182
183
20
void ScriptParser::readDynamicList() {
184
20
  Config->HasDynamicList = true;
185
20
  expect("{");
186
20
  std::vector<SymbolVersion> Locals;
187
20
  std::vector<SymbolVersion> Globals;
188
20
  std::tie(Locals, Globals) = readSymbols();
189
20
  expect(";");
190
20
191
20
  if (!atEOF()) {
192
0
    setError("EOF expected, but got " + next());
193
0
    return;
194
0
  }
195
20
  if (!Locals.empty()) {
196
0
    setError("\"local:\" scope not supported in --dynamic-list");
197
0
    return;
198
0
  }
199
20
200
20
  for (SymbolVersion V : Globals)
201
23
    Config->DynamicList.push_back(V);
202
20
}
203
204
71
void ScriptParser::readVersionScript() {
205
71
  readVersionScriptCommand();
206
71
  if (!atEOF())
207
1
    setError("EOF expected, but got " + next());
208
71
}
209
210
72
void ScriptParser::readVersionScriptCommand() {
211
72
  if (consume("{")) {
212
21
    readAnonymousDeclaration();
213
21
    return;
214
21
  }
215
51
216
126
  
while (51
!atEOF() &&
!errorCount()77
&&
peek() != "}"77
) {
217
76
    StringRef VerStr = next();
218
76
    if (VerStr == "{") {
219
1
      setError("anonymous version definition is used in "
220
1
               "combination with other version definitions");
221
1
      return;
222
1
    }
223
75
    expect("{");
224
75
    readVersionDeclaration(VerStr);
225
75
  }
226
51
}
227
228
1
void ScriptParser::readVersion() {
229
1
  expect("{");
230
1
  readVersionScriptCommand();
231
1
  expect("}");
232
1
}
233
234
464
void ScriptParser::readLinkerScript() {
235
1.01k
  while (!atEOF()) {
236
551
    StringRef Tok = next();
237
551
    if (Tok == ";")
238
25
      continue;
239
526
240
526
    if (Tok == "ASSERT") {
241
2
      Script->SectionCommands.push_back(readAssert());
242
524
    } else if (Tok == "ENTRY") {
243
5
      readEntry();
244
519
    } else if (Tok == "EXTERN") {
245
5
      readExtern();
246
514
    } else if (Tok == "GROUP" || 
Tok == "INPUT"495
) {
247
22
      readGroup();
248
492
    } else if (Tok == "INCLUDE") {
249
18
      readInclude();
250
474
    } else if (Tok == "MEMORY") {
251
25
      readMemory();
252
449
    } else if (Tok == "OUTPUT") {
253
7
      readOutput();
254
442
    } else if (Tok == "OUTPUT_ARCH") {
255
1
      readOutputArch();
256
441
    } else if (Tok == "OUTPUT_FORMAT") {
257
4
      readOutputFormat();
258
437
    } else if (Tok == "PHDRS") {
259
24
      readPhdrs();
260
413
    } else if (Tok == "REGION_ALIAS") {
261
8
      readRegionAlias();
262
405
    } else if (Tok == "SEARCH_DIR") {
263
6
      readSearchDir();
264
399
    } else if (Tok == "SECTIONS") {
265
366
      readSections();
266
366
    } else 
if (33
Tok == "VERSION"33
) {
267
1
      readVersion();
268
32
    } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
269
28
      Script->SectionCommands.push_back(Cmd);
270
28
    } else {
271
4
      setError("unknown directive: " + Tok);
272
4
    }
273
526
  }
274
464
}
275
276
11
void ScriptParser::readDefsym(StringRef Name) {
277
11
  Expr E = readExpr();
278
11
  if (!atEOF())
279
0
    setError("EOF expected, but got " + next());
280
11
  SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
281
11
  Script->SectionCommands.push_back(Cmd);
282
11
}
283
284
37
void ScriptParser::addFile(StringRef S) {
285
37
  if (IsUnderSysroot && 
S.startswith("/")2
) {
286
2
    SmallString<128> PathData;
287
2
    StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
288
2
    if (sys::fs::exists(Path)) {
289
1
      Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
290
1
      return;
291
1
    }
292
36
  }
293
36
294
36
  if (S.startswith("/")) {
295
28
    Driver->addFile(S, /*WithLOption=*/false);
296
28
  } else 
if (8
S.startswith("=")8
) {
297
2
    if (Config->Sysroot.empty())
298
1
      Driver->addFile(S.substr(1), /*WithLOption=*/false);
299
1
    else
300
1
      Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
301
1
                      /*WithLOption=*/false);
302
6
  } else if (S.startswith("-l")) {
303
2
    Driver->addLibrary(S.substr(2));
304
4
  } else if (sys::fs::exists(S)) {
305
0
    Driver->addFile(S, /*WithLOption=*/false);
306
4
  } else {
307
4
    if (Optional<std::string> Path = findFromSearchPaths(S))
308
2
      Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
309
2
    else
310
2
      setError("unable to find " + S);
311
4
  }
312
36
}
313
314
2
void ScriptParser::readAsNeeded() {
315
2
  expect("(");
316
2
  bool Orig = Config->AsNeeded;
317
2
  Config->AsNeeded = true;
318
6
  while (!errorCount() && !consume(")"))
319
4
    addFile(unquote(next()));
320
2
  Config->AsNeeded = Orig;
321
2
}
322
323
5
void ScriptParser::readEntry() {
324
5
  // -e <symbol> takes predecence over ENTRY(<symbol>).
325
5
  expect("(");
326
5
  StringRef Tok = next();
327
5
  if (Config->Entry.empty())
328
4
    Config->Entry = Tok;
329
5
  expect(")");
330
5
}
331
332
5
void ScriptParser::readExtern() {
333
5
  expect("(");
334
11
  while (!errorCount() && 
!consume(")")8
)
335
6
    Config->Undefined.push_back(next());
336
5
}
337
338
22
void ScriptParser::readGroup() {
339
22
  expect("(");
340
57
  while (!errorCount() && 
!consume(")")51
) {
341
35
    if (consume("AS_NEEDED"))
342
2
      readAsNeeded();
343
33
    else
344
33
      addFile(unquote(next()));
345
35
  }
346
22
}
347
348
18
void ScriptParser::readInclude() {
349
18
  StringRef Tok = unquote(next());
350
18
351
18
  if (!Seen.insert(Tok).second) {
352
2
    setError("there is a cycle in linker script INCLUDEs");
353
2
    return;
354
2
  }
355
16
356
16
  if (Optional<std::string> Path = searchLinkerScript(Tok)) {
357
14
    if (Optional<MemoryBufferRef> MB = readFile(*Path))
358
14
      tokenize(*MB);
359
14
    return;
360
14
  }
361
2
  setError("cannot find linker script " + Tok);
362
2
}
363
364
7
void ScriptParser::readOutput() {
365
7
  // -o <file> takes predecence over OUTPUT(<file>).
366
7
  expect("(");
367
7
  StringRef Tok = next();
368
7
  if (Config->OutputFile.empty())
369
7
    Config->OutputFile = unquote(Tok);
370
7
  expect(")");
371
7
}
372
373
1
void ScriptParser::readOutputArch() {
374
1
  // OUTPUT_ARCH is ignored for now.
375
1
  expect("(");
376
7
  while (!errorCount() && !consume(")"))
377
6
    skip();
378
1
}
379
380
4
void ScriptParser::readOutputFormat() {
381
4
  // Error checking only for now.
382
4
  expect("(");
383
4
  skip();
384
4
  if (consume(")"))
385
1
    return;
386
3
  expect(",");
387
3
  skip();
388
3
  expect(",");
389
3
  skip();
390
3
  expect(")");
391
3
}
392
393
24
void ScriptParser::readPhdrs() {
394
24
  expect("{");
395
24
396
56
  while (!errorCount() && !consume("}")) {
397
32
    PhdrsCommand Cmd;
398
32
    Cmd.Name = next();
399
32
    Cmd.Type = readPhdrType();
400
32
401
61
    while (!errorCount() && !consume(";")) {
402
29
      if (consume("FILEHDR"))
403
10
        Cmd.HasFilehdr = true;
404
19
      else if (consume("PHDRS"))
405
12
        Cmd.HasPhdrs = true;
406
7
      else if (consume("AT"))
407
1
        Cmd.LMAExpr = readParenExpr();
408
6
      else if (consume("FLAGS"))
409
6
        Cmd.Flags = readParenExpr()().getValue();
410
0
      else
411
0
        setError("unexpected header attribute: " + next());
412
29
    }
413
32
414
32
    Script->PhdrsCommands.push_back(Cmd);
415
32
  }
416
24
}
417
418
8
void ScriptParser::readRegionAlias() {
419
8
  expect("(");
420
8
  StringRef Alias = unquote(next());
421
8
  expect(",");
422
8
  StringRef Name = next();
423
8
  expect(")");
424
8
425
8
  if (Script->MemoryRegions.count(Alias))
426
2
    setError("redefinition of memory region '" + Alias + "'");
427
8
  if (!Script->MemoryRegions.count(Name))
428
1
    setError("memory region '" + Name + "' is not defined");
429
8
  Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
430
8
}
431
432
6
void ScriptParser::readSearchDir() {
433
6
  expect("(");
434
6
  StringRef Tok = next();
435
6
  if (!Config->Nostdlib)
436
5
    Config->SearchPaths.push_back(unquote(Tok));
437
6
  expect(")");
438
6
}
439
440
366
void ScriptParser::readSections() {
441
366
  Script->HasSectionsCommand = true;
442
366
443
366
  // -no-rosegment is used to avoid placing read only non-executable sections in
444
366
  // their own segment. We do the same if SECTIONS command is present in linker
445
366
  // script. See comment for computeFlags().
446
366
  Config->SingleRoRx = true;
447
366
448
366
  expect("{");
449
1.20k
  while (!errorCount() && 
!consume("}")1.18k
) {
450
835
    StringRef Tok = next();
451
835
    BaseCommand *Cmd = readProvideOrAssignment(Tok);
452
835
    if (!Cmd) {
453
567
      if (Tok == "ASSERT")
454
2
        Cmd = readAssert();
455
565
      else
456
565
        Cmd = readOutputSectionDescription(Tok);
457
567
    }
458
835
    Script->SectionCommands.push_back(Cmd);
459
835
  }
460
366
}
461
462
1.03k
static int precedence(StringRef Op) {
463
1.03k
  return StringSwitch<int>(Op)
464
1.03k
      .Cases("*", "/", 5)
465
1.03k
      .Cases("+", "-", 4)
466
1.03k
      .Cases("<<", ">>", 3)
467
1.03k
      .Cases("<", "<=", ">", ">=", "==", "!=", 2)
468
1.03k
      .Cases("&", "|", 1)
469
1.03k
      .Default(-1);
470
1.03k
}
471
472
7
StringMatcher ScriptParser::readFilePatterns() {
473
7
  std::vector<StringRef> V;
474
14
  while (!errorCount() && !consume(")"))
475
7
    V.push_back(next());
476
7
  return StringMatcher(V);
477
7
}
478
479
616
SortSectionPolicy ScriptParser::readSortKind() {
480
616
  if (consume("SORT") || 
consume("SORT_BY_NAME")611
)
481
11
    return SortSectionPolicy::Name;
482
605
  if (consume("SORT_BY_ALIGNMENT"))
483
4
    return SortSectionPolicy::Alignment;
484
601
  if (consume("SORT_BY_INIT_PRIORITY"))
485
1
    return SortSectionPolicy::Priority;
486
600
  if (consume("SORT_NONE"))
487
3
    return SortSectionPolicy::None;
488
597
  return SortSectionPolicy::Default;
489
597
}
490
491
// Reads SECTIONS command contents in the following form:
492
//
493
// <contents> ::= <elem>*
494
// <elem>     ::= <exclude>? <glob-pattern>
495
// <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
496
//
497
// For example,
498
//
499
// *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
500
//
501
// is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
502
// The semantics of that is section .foo in any file, section .bar in
503
// any file but a.o, and section .baz in any file but b.o.
504
600
std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
505
600
  std::vector<SectionPattern> Ret;
506
1.20k
  while (!errorCount() && 
peek() != ")"1.20k
) {
507
603
    StringMatcher ExcludeFilePat;
508
603
    if (consume("EXCLUDE_FILE")) {
509
7
      expect("(");
510
7
      ExcludeFilePat = readFilePatterns();
511
7
    }
512
603
513
603
    std::vector<StringRef> V;
514
1.21k
    while (!errorCount() && peek() != ")" && 
peek() != "EXCLUDE_FILE"614
)
515
610
      V.push_back(next());
516
603
517
603
    if (!V.empty())
518
601
      Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
519
2
    else
520
2
      setError("section pattern is expected");
521
603
  }
522
600
  return Ret;
523
600
}
524
525
// Reads contents of "SECTIONS" directive. That directive contains a
526
// list of glob patterns for input sections. The grammar is as follows.
527
//
528
// <patterns> ::= <section-list>
529
//              | <sort> "(" <section-list> ")"
530
//              | <sort> "(" <sort> "(" <section-list> ")" ")"
531
//
532
// <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
533
//              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
534
//
535
// <section-list> is parsed by readInputSectionsList().
536
InputSectionDescription *
537
598
ScriptParser::readInputSectionRules(StringRef FilePattern) {
538
598
  auto *Cmd = make<InputSectionDescription>(FilePattern);
539
598
  expect("(");
540
598
541
1.19k
  while (!errorCount() && 
!consume(")")1.19k
) {
542
600
    SortSectionPolicy Outer = readSortKind();
543
600
    SortSectionPolicy Inner = SortSectionPolicy::Default;
544
600
    std::vector<SectionPattern> V;
545
600
    if (Outer != SortSectionPolicy::Default) {
546
16
      expect("(");
547
16
      Inner = readSortKind();
548
16
      if (Inner != SortSectionPolicy::Default) {
549
3
        expect("(");
550
3
        V = readInputSectionsList();
551
3
        expect(")");
552
13
      } else {
553
13
        V = readInputSectionsList();
554
13
      }
555
16
      expect(")");
556
584
    } else {
557
584
      V = readInputSectionsList();
558
584
    }
559
600
560
601
    for (SectionPattern &Pat : V) {
561
601
      Pat.SortInner = Inner;
562
601
      Pat.SortOuter = Outer;
563
601
    }
564
600
565
600
    std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
566
600
  }
567
598
  return Cmd;
568
598
}
569
570
InputSectionDescription *
571
598
ScriptParser::readInputSectionDescription(StringRef Tok) {
572
598
  // Input section wildcard can be surrounded by KEEP.
573
598
  // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
574
598
  if (Tok == "KEEP") {
575
14
    expect("(");
576
14
    StringRef FilePattern = next();
577
14
    InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
578
14
    expect(")");
579
14
    Script->KeptSections.push_back(Cmd);
580
14
    return Cmd;
581
14
  }
582
584
  return readInputSectionRules(Tok);
583
584
}
584
585
1
void ScriptParser::readSort() {
586
1
  expect("(");
587
1
  expect("CONSTRUCTORS");
588
1
  expect(")");
589
1
}
590
591
6
AssertCommand *ScriptParser::readAssert() {
592
6
  return make<AssertCommand>(readAssertExpr());
593
6
}
594
595
8
Expr ScriptParser::readAssertExpr() {
596
8
  expect("(");
597
8
  Expr E = readExpr();
598
8
  expect(",");
599
8
  StringRef Msg = unquote(next());
600
8
  expect(")");
601
8
602
8
  return [=] {
603
7
    if (!E().getValue())
604
1
      error(Msg);
605
7
    return Script->getDot();
606
7
  };
607
8
}
608
609
// Reads a FILL(expr) command. We handle the FILL command as an
610
// alias for =fillexp section attribute, which is different from
611
// what GNU linkers do.
612
// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
613
4
uint32_t ScriptParser::readFill() {
614
4
  expect("(");
615
4
  uint32_t V = parseFill(next());
616
4
  expect(")");
617
4
  return V;
618
4
}
619
620
// Reads an expression and/or the special directive "(NOLOAD)" for an
621
// output section definition.
622
//
623
// An output section name can be followed by an address expression
624
// and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be
625
// interpreted as either the beginning of some expression or "(NOLOAD)".
626
//
627
// https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
628
// https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
629
60
void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
630
60
  if (consume("(")) {
631
3
    if (consume("NOLOAD")) {
632
2
      expect(")");
633
2
      Cmd->Noload = true;
634
2
      return;
635
2
    }
636
1
    Cmd->AddrExpr = readExpr();
637
1
    expect(")");
638
57
  } else {
639
57
    Cmd->AddrExpr = readExpr();
640
57
  }
641
60
642
60
  
if (58
consume("(")58
) {
643
1
    expect("NOLOAD");
644
1
    expect(")");
645
1
    Cmd->Noload = true;
646
1
  }
647
58
}
648
649
47
static Expr checkAlignment(Expr E, std::string &Loc) {
650
58
  return [=] {
651
58
    uint64_t Alignment = std::max((uint64_t)1, E().getValue());
652
58
    if (!isPowerOf2_64(Alignment)) {
653
3
      error(Loc + ": alignment must be power of 2");
654
3
      return (uint64_t)1; // Return a dummy value.
655
3
    }
656
55
    return Alignment;
657
55
  };
658
47
}
659
660
565
OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
661
565
  OutputSection *Cmd =
662
565
      Script->createOutputSection(OutSec, getCurrentLocation());
663
565
664
565
  if (peek() != ":")
665
60
    readSectionAddressType(Cmd);
666
565
  expect(":");
667
565
668
565
  std::string Location = getCurrentLocation();
669
565
  if (consume("AT"))
670
15
    Cmd->LMAExpr = readParenExpr();
671
565
  if (consume("ALIGN"))
672
11
    Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
673
565
  if (consume("SUBALIGN"))
674
4
    Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
675
565
676
565
  // Parse constraints.
677
565
  if (consume("ONLY_IF_RO"))
678
9
    Cmd->Constraint = ConstraintKind::ReadOnly;
679
565
  if (consume("ONLY_IF_RW"))
680
5
    Cmd->Constraint = ConstraintKind::ReadWrite;
681
565
  expect("{");
682
565
683
1.28k
  while (!errorCount() && 
!consume("}")1.28k
) {
684
723
    StringRef Tok = next();
685
723
    if (Tok == ";") {
686
15
      // Empty commands are allowed. Do nothing here.
687
708
    } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
688
74
      Cmd->SectionCommands.push_back(Assign);
689
634
    } else if (ByteCommand *Data = readByteCommand(Tok)) {
690
28
      Cmd->SectionCommands.push_back(Data);
691
606
    } else if (Tok == "ASSERT") {
692
2
      Cmd->SectionCommands.push_back(readAssert());
693
2
      expect(";");
694
604
    } else if (Tok == "CONSTRUCTORS") {
695
1
      // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
696
1
      // by name. This is for very old file formats such as ECOFF/XCOFF.
697
1
      // For ELF, we should ignore.
698
603
    } else if (Tok == "FILL") {
699
4
      Cmd->Filler = readFill();
700
599
    } else if (Tok == "SORT") {
701
1
      readSort();
702
598
    } else if (peek() == "(") {
703
598
      Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
704
598
    } else {
705
0
      setError("unknown command " + Tok);
706
0
    }
707
723
  }
708
565
709
565
  if (consume(">"))
710
24
    Cmd->MemoryRegionName = next();
711
565
712
565
  if (consume("AT")) {
713
5
    expect(">");
714
5
    Cmd->LMARegionName = next();
715
5
  }
716
565
717
565
  if (Cmd->LMAExpr && 
!Cmd->LMARegionName.empty()15
)
718
1
    error("section can't have both LMA and a load region");
719
565
720
565
  Cmd->Phdrs = readOutputSectionPhdrs();
721
565
722
565
  if (consume("="))
723
1
    Cmd->Filler = parseFill(next());
724
564
  else if (peek().startswith("="))
725
8
    Cmd->Filler = parseFill(next().drop_front());
726
565
727
565
  // Consume optional comma following output section command.
728
565
  consume(",");
729
565
730
565
  return Cmd;
731
565
}
732
733
// Parses a given string as a octal/decimal/hexadecimal number and
734
// returns it as a big-endian number. Used for `=<fillexp>`.
735
// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
736
//
737
// When reading a hexstring, ld.bfd handles it as a blob of arbitrary
738
// size, while ld.gold always handles it as a 32-bit big-endian number.
739
// We are compatible with ld.gold because it's easier to implement.
740
13
uint32_t ScriptParser::parseFill(StringRef Tok) {
741
13
  uint32_t V = 0;
742
13
  if (!to_integer(Tok, V))
743
1
    setError("invalid filler expression: " + Tok);
744
13
745
13
  uint32_t Buf;
746
13
  write32be(&Buf, V);
747
13
  return Buf;
748
13
}
749
750
39
SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
751
39
  expect("(");
752
39
  SymbolAssignment *Cmd = readAssignment(next());
753
39
  Cmd->Provide = Provide;
754
39
  Cmd->Hidden = Hidden;
755
39
  expect(")");
756
39
  expect(";");
757
39
  return Cmd;
758
39
}
759
760
1.57k
SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
761
1.57k
  SymbolAssignment *Cmd = nullptr;
762
1.57k
  if (peek() == "=" || 
peek() == "+="1.25k
) {
763
331
    Cmd = readAssignment(Tok);
764
331
    expect(";");
765
1.24k
  } else if (Tok == "PROVIDE") {
766
13
    Cmd = readProvideHidden(true, false);
767
1.23k
  } else if (Tok == "HIDDEN") {
768
2
    Cmd = readProvideHidden(false, true);
769
1.22k
  } else if (Tok == "PROVIDE_HIDDEN") {
770
24
    Cmd = readProvideHidden(true, true);
771
24
  }
772
1.57k
  return Cmd;
773
1.57k
}
774
775
370
SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
776
370
  StringRef Op = next();
777
370
  assert(Op == "=" || Op == "+=");
778
370
  Expr E = readExpr();
779
370
  if (Op == "+=") {
780
14
    std::string Loc = getCurrentLocation();
781
16
    E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
782
14
  }
783
370
  return make<SymbolAssignment>(Name, E, getCurrentLocation());
784
370
}
785
786
// This is an operator-precedence parser to parse a linker
787
// script expression.
788
704
Expr ScriptParser::readExpr() {
789
704
  // Our lexer is context-aware. Set the in-expression bit so that
790
704
  // they apply different tokenization rules.
791
704
  bool Orig = InExpr;
792
704
  InExpr = true;
793
704
  Expr E = readExpr1(readPrimary(), 0);
794
704
  InExpr = Orig;
795
704
  return E;
796
704
}
797
798
119
static Expr combine(StringRef Op, Expr L, Expr R) {
799
119
  if (Op == "+")
800
112
    
return [=] 64
{ return add(L(), R()); };
801
55
  if (Op == "-")
802
37
    
return [=] 18
{ return sub(L(), R()); };
803
37
  if (Op == "*")
804
14
    
return [=] 11
{ return mul(L(), R()); };
805
26
  if (Op == "/")
806
5
    
return [=] 3
{ return div(L(), R()); };
807
23
  if (Op == "<<")
808
2
    
return [=] 1
{ return L().getValue() << R().getValue(); };
809
22
  if (Op == ">>")
810
2
    
return [=] 1
{ return L().getValue() >> R().getValue(); };
811
21
  if (Op == "<")
812
2
    
return [=] 1
{ return L().getValue() < R().getValue(); };
813
20
  if (Op == ">")
814
2
    
return [=] 1
{ return L().getValue() > R().getValue(); };
815
19
  if (Op == ">=")
816
2
    
return [=] 1
{ return L().getValue() >= R().getValue(); };
817
18
  if (Op == "<=")
818
2
    
return [=] 1
{ return L().getValue() <= R().getValue(); };
819
17
  if (Op == "==")
820
5
    
return [=] 4
{ return L().getValue() == R().getValue(); };
821
13
  if (Op == "!=")
822
4
    
return [=] 2
{ return L().getValue() != R().getValue(); };
823
11
  if (Op == "&")
824
9
    
return [=] 5
{ return bitAnd(L(), R()); };
825
6
  if (Op == "|")
826
8
    
return [=] 6
{ return bitOr(L(), R()); };
827
0
  llvm_unreachable("invalid operator");
828
0
}
829
830
// This is a part of the operator-precedence parser. This function
831
// assumes that the remaining token stream starts with an operator.
832
708
Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
833
827
  while (!atEOF() && 
!errorCount()800
) {
834
800
    // Read an operator and an expression.
835
800
    if (consume("?"))
836
14
      return readTernary(Lhs);
837
786
    StringRef Op1 = peek();
838
786
    if (precedence(Op1) < MinPrec)
839
667
      break;
840
119
    skip();
841
119
    Expr Rhs = readPrimary();
842
119
843
119
    // Evaluate the remaining part of the expression first if the
844
119
    // next operator has greater precedence than the previous one.
845
119
    // For example, if we have read "+" and "3", and if the next
846
119
    // operator is "*", then we'll evaluate 3 * ... part first.
847
123
    while (!atEOF()) {
848
122
      StringRef Op2 = peek();
849
122
      if (precedence(Op2) <= precedence(Op1))
850
118
        break;
851
4
      Rhs = readExpr1(Rhs, precedence(Op2));
852
4
    }
853
119
854
119
    Lhs = combine(Op1, Lhs, Rhs);
855
119
  }
856
708
  
return Lhs694
;
857
708
}
858
859
7
Expr ScriptParser::getPageSize() {
860
7
  std::string Location = getCurrentLocation();
861
7
  return [=]() -> uint64_t {
862
6
    if (Target)
863
4
      return Target->PageSize;
864
2
    error(Location + ": unable to calculate page size");
865
2
    return 4096; // Return a dummy value.
866
2
  };
867
7
}
868
869
19
Expr ScriptParser::readConstant() {
870
19
  StringRef S = readParenLiteral();
871
19
  if (S == "COMMONPAGESIZE")
872
4
    return getPageSize();
873
15
  if (S == "MAXPAGESIZE")
874
21
    
return [] 15
{ return Config->MaxPageSize; };
875
0
  setError("unknown constant: " + S);
876
0
  return {};
877
0
}
878
879
// Parses Tok as an integer. It recognizes hexadecimal (prefixed with
880
// "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
881
// have "K" (Ki) or "M" (Mi) suffixes.
882
581
static Optional<uint64_t> parseInt(StringRef Tok) {
883
581
  // Hexadecimal
884
581
  uint64_t Val;
885
581
  if (Tok.startswith_lower("0x")) {
886
260
    if (!to_integer(Tok.substr(2), Val, 16))
887
4
      return None;
888
256
    return Val;
889
256
  }
890
321
  if (Tok.endswith_lower("H")) {
891
2
    if (!to_integer(Tok.drop_back(), Val, 16))
892
0
      return None;
893
2
    return Val;
894
2
  }
895
319
896
319
  // Decimal
897
319
  if (Tok.endswith_lower("K")) {
898
14
    if (!to_integer(Tok.drop_back(), Val, 10))
899
0
      return None;
900
14
    return Val * 1024;
901
14
  }
902
305
  if (Tok.endswith_lower("M")) {
903
8
    if (!to_integer(Tok.drop_back(), Val, 10))
904
0
      return None;
905
8
    return Val * 1024 * 1024;
906
8
  }
907
297
  if (!to_integer(Tok, Val, 10))
908
103
    return None;
909
194
  return Val;
910
194
}
911
912
634
ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
913
634
  int Size = StringSwitch<int>(Tok)
914
634
                 .Case("BYTE", 1)
915
634
                 .Case("SHORT", 2)
916
634
                 .Case("LONG", 4)
917
634
                 .Case("QUAD", 8)
918
634
                 .Default(-1);
919
634
  if (Size == -1)
920
606
    return nullptr;
921
28
  return make<ByteCommand>(readParenExpr(), Size);
922
28
}
923
924
73
StringRef ScriptParser::readParenLiteral() {
925
73
  expect("(");
926
73
  StringRef Tok = next();
927
73
  expect(")");
928
73
  return Tok;
929
73
}
930
931
66
static void checkIfExists(OutputSection *Cmd, StringRef Location) {
932
66
  if (Cmd->Location.empty() && 
Script->ErrorOnMissingSection10
)
933
2
    error(Location + ": undefined section " + Cmd->Name);
934
66
}
935
936
834
Expr ScriptParser::readPrimary() {
937
834
  if (peek() == "(")
938
10
    return readParenExpr();
939
824
940
824
  if (consume("~")) {
941
5
    Expr E = readPrimary();
942
10
    return [=] { return ~E().getValue(); };
943
5
  }
944
819
  if (consume("!")) {
945
2
    Expr E = readPrimary();
946
4
    return [=] { return !E().getValue(); };
947
2
  }
948
817
  if (consume("-")) {
949
4
    Expr E = readPrimary();
950
8
    return [=] { return -E().getValue(); };
951
4
  }
952
813
953
813
  StringRef Tok = next();
954
813
  std::string Location = getCurrentLocation();
955
813
956
813
  // Built-in functions are parsed here.
957
813
  // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
958
813
  if (Tok == "ABSOLUTE") {
959
15
    Expr Inner = readParenExpr();
960
32
    return [=] {
961
32
      ExprValue I = Inner();
962
32
      I.ForceAbsolute = true;
963
32
      return I;
964
32
    };
965
15
  }
966
798
  if (Tok == "ADDR") {
967
21
    StringRef Name = readParenLiteral();
968
21
    OutputSection *Sec = Script->getOrCreateOutputSection(Name);
969
44
    return [=]() -> ExprValue {
970
44
      checkIfExists(Sec, Location);
971
44
      return {Sec, false, 0, Location};
972
44
    };
973
21
  }
974
777
  if (Tok == "ALIGN") {
975
32
    expect("(");
976
32
    Expr E = readExpr();
977
32
    if (consume(")")) {
978
16
      E = checkAlignment(E, Location);
979
18
      return [=] { return alignTo(Script->getDot(), E().getValue()); };
980
16
    }
981
16
    expect(",");
982
16
    Expr E2 = checkAlignment(readExpr(), Location);
983
16
    expect(")");
984
26
    return [=] {
985
26
      ExprValue V = E();
986
26
      V.Alignment = E2().getValue();
987
26
      return V;
988
26
    };
989
16
  }
990
745
  if (Tok == "ALIGNOF") {
991
5
    StringRef Name = readParenLiteral();
992
5
    OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
993
10
    return [=] {
994
10
      checkIfExists(Cmd, Location);
995
10
      return Cmd->Alignment;
996
10
    };
997
5
  }
998
740
  if (Tok == "ASSERT")
999
2
    return readAssertExpr();
1000
738
  if (Tok == "CONSTANT")
1001
19
    return readConstant();
1002
719
  if (Tok == "DATA_SEGMENT_ALIGN") {
1003
4
    expect("(");
1004
4
    Expr E = readExpr();
1005
4
    expect(",");
1006
4
    readExpr();
1007
4
    expect(")");
1008
6
    return [=] {
1009
6
      return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
1010
6
    };
1011
4
  }
1012
715
  if (Tok == "DATA_SEGMENT_END") {
1013
2
    expect("(");
1014
2
    expect(".");
1015
2
    expect(")");
1016
2
    return [] { return Script->getDot(); };
1017
2
  }
1018
713
  if (Tok == "DATA_SEGMENT_RELRO_END") {
1019
3
    // GNU linkers implements more complicated logic to handle
1020
3
    // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1021
3
    // just align to the next page boundary for simplicity.
1022
3
    expect("(");
1023
3
    readExpr();
1024
3
    expect(",");
1025
3
    readExpr();
1026
3
    expect(")");
1027
3
    Expr E = getPageSize();
1028
3
    return [=] { return alignTo(Script->getDot(), E().getValue()); };
1029
3
  }
1030
710
  if (Tok == "DEFINED") {
1031
2
    StringRef Name = readParenLiteral();
1032
2
    return [=] { return Symtab->find(Name) ? 
11
:
01
; };
1033
2
  }
1034
708
  if (Tok == "LENGTH") {
1035
2
    StringRef Name = readParenLiteral();
1036
2
    if (Script->MemoryRegions.count(Name) == 0)
1037
0
      setError("memory region not defined: " + Name);
1038
4
    return [=] { return Script->MemoryRegions[Name]->Length; };
1039
2
  }
1040
706
  if (Tok == "LOADADDR") {
1041
6
    StringRef Name = readParenLiteral();
1042
6
    OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1043
12
    return [=] {
1044
12
      checkIfExists(Cmd, Location);
1045
12
      return Cmd->getLMA();
1046
12
    };
1047
6
  }
1048
700
  if (Tok == "ORIGIN") {
1049
3
    StringRef Name = readParenLiteral();
1050
3
    if (Script->MemoryRegions.count(Name) == 0)
1051
1
      setError("memory region not defined: " + Name);
1052
4
    return [=] { return Script->MemoryRegions[Name]->Origin; };
1053
3
  }
1054
697
  if (Tok == "SEGMENT_START") {
1055
5
    expect("(");
1056
5
    skip();
1057
5
    expect(",");
1058
5
    Expr E = readExpr();
1059
5
    expect(")");
1060
9
    return [=] { return E(); };
1061
5
  }
1062
692
  if (Tok == "SIZEOF") {
1063
15
    StringRef Name = readParenLiteral();
1064
15
    OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1065
15
    // Linker script does not create an output section if its content is empty.
1066
15
    // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1067
15
    // be empty.
1068
27
    return [=] { return Cmd->Size; };
1069
15
  }
1070
677
  if (Tok == "SIZEOF_HEADERS")
1071
62
    
return [=] 47
{ return elf::getHeaderSize(); };
1072
630
1073
630
  // Tok is the dot.
1074
630
  if (Tok == ".")
1075
145
    
return [=] 81
{ return Script->getSymbolValue(Tok, Location); };
1076
549
1077
549
  // Tok is a literal number.
1078
549
  if (Optional<uint64_t> Val = parseInt(Tok))
1079
664
    
return [=] 472
{ return *Val; };
1080
77
1081
77
  // Tok is a symbol name.
1082
77
  if (!isValidCIdentifier(Tok))
1083
13
    setError("malformed number: " + Tok);
1084
77
  Script->ReferencedSymbols.push_back(Tok);
1085
111
  return [=] { return Script->getSymbolValue(Tok, Location); };
1086
77
}
1087
1088
14
Expr ScriptParser::readTernary(Expr Cond) {
1089
14
  Expr L = readExpr();
1090
14
  expect(":");
1091
14
  Expr R = readExpr();
1092
19
  return [=] { return Cond().getValue() ? 
L()10
:
R()9
; };
1093
14
}
1094
1095
90
Expr ScriptParser::readParenExpr() {
1096
90
  expect("(");
1097
90
  Expr E = readExpr();
1098
90
  expect(")");
1099
90
  return E;
1100
90
}
1101
1102
565
std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1103
565
  std::vector<StringRef> Phdrs;
1104
600
  while (!errorCount() && 
peek().startswith(":")591
) {
1105
35
    StringRef Tok = next();
1106
35
    Phdrs.push_back((Tok.size() == 1) ? 
next()12
:
Tok.substr(1)23
);
1107
35
  }
1108
565
  return Phdrs;
1109
565
}
1110
1111
// Read a program header type name. The next token must be a
1112
// name of a program header type or a constant (e.g. "0x3").
1113
32
unsigned ScriptParser::readPhdrType() {
1114
32
  StringRef Tok = next();
1115
32
  if (Optional<uint64_t> Val = parseInt(Tok))
1116
2
    return *Val;
1117
30
1118
30
  unsigned Ret = StringSwitch<unsigned>(Tok)
1119
30
                     .Case("PT_NULL", PT_NULL)
1120
30
                     .Case("PT_LOAD", PT_LOAD)
1121
30
                     .Case("PT_DYNAMIC", PT_DYNAMIC)
1122
30
                     .Case("PT_INTERP", PT_INTERP)
1123
30
                     .Case("PT_NOTE", PT_NOTE)
1124
30
                     .Case("PT_SHLIB", PT_SHLIB)
1125
30
                     .Case("PT_PHDR", PT_PHDR)
1126
30
                     .Case("PT_TLS", PT_TLS)
1127
30
                     .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1128
30
                     .Case("PT_GNU_STACK", PT_GNU_STACK)
1129
30
                     .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1130
30
                     .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1131
30
                     .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1132
30
                     .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1133
30
                     .Default(-1);
1134
30
1135
30
  if (Ret == (unsigned)-1) {
1136
0
    setError("invalid program header type: " + Tok);
1137
0
    return PT_NULL;
1138
0
  }
1139
30
  return Ret;
1140
30
}
1141
1142
// Reads an anonymous version declaration.
1143
21
void ScriptParser::readAnonymousDeclaration() {
1144
21
  std::vector<SymbolVersion> Locals;
1145
21
  std::vector<SymbolVersion> Globals;
1146
21
  std::tie(Locals, Globals) = readSymbols();
1147
21
1148
21
  for (SymbolVersion V : Locals) {
1149
18
    if (V.Name == "*")
1150
17
      Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1151
1
    else
1152
1
      Config->VersionScriptLocals.push_back(V);
1153
18
  }
1154
21
1155
21
  for (SymbolVersion V : Globals)
1156
21
    Config->VersionScriptGlobals.push_back(V);
1157
21
1158
21
  expect(";");
1159
21
}
1160
1161
// Reads a non-anonymous version definition,
1162
// e.g. "VerStr { global: foo; bar; local: *; };".
1163
75
void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1164
75
  // Read a symbol list.
1165
75
  std::vector<SymbolVersion> Locals;
1166
75
  std::vector<SymbolVersion> Globals;
1167
75
  std::tie(Locals, Globals) = readSymbols();
1168
75
1169
75
  for (SymbolVersion V : Locals) {
1170
35
    if (V.Name == "*")
1171
28
      Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1172
7
    else
1173
7
      Config->VersionScriptLocals.push_back(V);
1174
35
  }
1175
75
1176
75
  // Create a new version definition and add that to the global symbols.
1177
75
  VersionDefinition Ver;
1178
75
  Ver.Name = VerStr;
1179
75
  Ver.Globals = Globals;
1180
75
1181
75
  // User-defined version number starts from 2 because 0 and 1 are
1182
75
  // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1183
75
  Ver.Id = Config->VersionDefinitions.size() + 2;
1184
75
  Config->VersionDefinitions.push_back(Ver);
1185
75
1186
75
  // Each version may have a parent version. For example, "Ver2"
1187
75
  // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1188
75
  // as a parent. This version hierarchy is, probably against your
1189
75
  // instinct, purely for hint; the runtime doesn't care about it
1190
75
  // at all. In LLD, we simply ignore it.
1191
75
  if (peek() != ";")
1192
3
    skip();
1193
75
  expect(";");
1194
75
}
1195
1196
146
static bool hasWildcard(StringRef S) {
1197
146
  return S.find_first_of("?*[") != StringRef::npos;
1198
146
}
1199
1200
// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1201
std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1202
116
ScriptParser::readSymbols() {
1203
116
  std::vector<SymbolVersion> Locals;
1204
116
  std::vector<SymbolVersion> Globals;
1205
116
  std::vector<SymbolVersion> *V = &Globals;
1206
116
1207
379
  while (!errorCount()) {
1208
374
    if (consume("}"))
1209
111
      break;
1210
263
    if (consumeLabel("local")) {
1211
53
      V = &Locals;
1212
53
      continue;
1213
53
    }
1214
210
    if (consumeLabel("global")) {
1215
62
      V = &Globals;
1216
62
      continue;
1217
62
    }
1218
148
1219
148
    if (consume("extern")) {
1220
23
      std::vector<SymbolVersion> Ext = readVersionExtern();
1221
23
      V->insert(V->end(), Ext.begin(), Ext.end());
1222
125
    } else {
1223
125
      StringRef Tok = next();
1224
125
      V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1225
125
    }
1226
148
    expect(";");
1227
148
  }
1228
116
  return {Locals, Globals};
1229
116
}
1230
1231
// Reads an "extern C++" directive, e.g.,
1232
// "extern "C++" { ns::*; "f(int, double)"; };"
1233
23
std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1234
23
  StringRef Tok = next();
1235
23
  bool IsCXX = Tok == "\"C++\"";
1236
23
  if (!IsCXX && 
Tok != "\"C\""3
)
1237
1
    setError("Unknown language");
1238
23
  expect("{");
1239
23
1240
23
  std::vector<SymbolVersion> Ret;
1241
51
  while (!errorCount() && 
peek() != "}"50
) {
1242
28
    StringRef Tok = next();
1243
28
    bool HasWildcard = !Tok.startswith("\"") && 
hasWildcard(Tok)21
;
1244
28
    Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1245
28
    expect(";");
1246
28
  }
1247
23
1248
23
  expect("}");
1249
23
  return Ret;
1250
23
}
1251
1252
uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1253
80
                                            StringRef S3) {
1254
80
  if (!consume(S1) && 
!consume(S2)16
&&
!consume(S3)14
) {
1255
8
    setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1256
8
    return 0;
1257
8
  }
1258
72
  expect("=");
1259
72
  return readExpr()().getValue();
1260
72
}
1261
1262
// Parse the MEMORY command as specified in:
1263
// https://sourceware.org/binutils/docs/ld/MEMORY.html
1264
//
1265
// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1266
25
void ScriptParser::readMemory() {
1267
25
  expect("{");
1268
65
  while (!errorCount() && 
!consume("}")58
) {
1269
40
    StringRef Name = next();
1270
40
1271
40
    uint32_t Flags = 0;
1272
40
    uint32_t NegFlags = 0;
1273
40
    if (consume("(")) {
1274
37
      std::tie(Flags, NegFlags) = readMemoryAttributes();
1275
37
      expect(")");
1276
37
    }
1277
40
    expect(":");
1278
40
1279
40
    uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1280
40
    expect(",");
1281
40
    uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1282
40
1283
40
    // Add the memory region to the region map.
1284
40
    if (Script->MemoryRegions.count(Name))
1285
1
      setError("region '" + Name + "' already defined");
1286
40
    MemoryRegion *MR = make<MemoryRegion>();
1287
40
    *MR = {Name, Origin, Length, Flags, NegFlags};
1288
40
    Script->MemoryRegions[Name] = MR;
1289
40
  }
1290
25
}
1291
1292
// This function parses the attributes used to match against section
1293
// flags when placing output sections in a memory region. These flags
1294
// are only used when an explicit memory region name is not used.
1295
37
std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1296
37
  uint32_t Flags = 0;
1297
37
  uint32_t NegFlags = 0;
1298
37
  bool Invert = false;
1299
37
1300
97
  for (char C : next().lower()) {
1301
97
    uint32_t Flag = 0;
1302
97
    if (C == '!')
1303
2
      Invert = !Invert;
1304
95
    else if (C == 'w')
1305
23
      Flag = SHF_WRITE;
1306
72
    else if (C == 'x')
1307
33
      Flag = SHF_EXECINSTR;
1308
39
    else if (C == 'a')
1309
11
      Flag = SHF_ALLOC;
1310
28
    else if (C != 'r')
1311
2
      setError("invalid memory region attribute");
1312
97
1313
97
    if (Invert)
1314
6
      NegFlags |= Flag;
1315
91
    else
1316
91
      Flags |= Flag;
1317
97
  }
1318
37
  return {Flags, NegFlags};
1319
37
}
1320
1321
464
void elf::readLinkerScript(MemoryBufferRef MB) {
1322
464
  ScriptParser(MB).readLinkerScript();
1323
464
}
1324
1325
71
void elf::readVersionScript(MemoryBufferRef MB) {
1326
71
  ScriptParser(MB).readVersionScript();
1327
71
}
1328
1329
20
void elf::readDynamicList(MemoryBufferRef MB) {
1330
20
  ScriptParser(MB).readDynamicList();
1331
20
}
1332
1333
11
void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
1334
11
  ScriptParser(MB).readDefsym(Name);
1335
11
}