Coverage Report

Created: 2017-09-19 22:28

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