-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathScriptParser.cpp
More file actions
1624 lines (1510 loc) · 50.3 KB
/
ScriptParser.cpp
File metadata and controls
1624 lines (1510 loc) · 50.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- ScriptParser.cpp----------------------------------------------------===//
// Part of the eld Project, under the BSD License
// See https://github.com/qualcomm/eld/LICENSE.txt for license information.
// SPDX-License-Identifier: BSD-3-Clause
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This file contains a recursive-descendent parser for linker scripts.
// Parsed results are stored to Config and Script global objects.
//
//===----------------------------------------------------------------------===//
#include "eld/ScriptParser/ScriptParser.h"
#include "eld/Config/GeneralOptions.h"
#include "eld/Config/LinkerConfig.h"
#include "eld/Core/Module.h"
#include "eld/Diagnostics/DiagnosticEngine.h"
#include "eld/Input/InputFile.h"
#include "eld/Input/LinkerScriptFile.h"
#include "eld/PluginAPI/DiagnosticEntry.h"
#include "eld/Script/Assignment.h"
#include "eld/Script/ExcludeFiles.h"
#include "eld/Script/Expression.h"
#include "eld/Script/InputSectDesc.h"
#include "eld/Script/OutputSectDesc.h"
#include "eld/Script/OverlayDesc.h"
#include "eld/Script/PhdrDesc.h"
#include "eld/Script/ScriptFile.h"
#include "eld/Script/StrToken.h"
#include "eld/Script/WildcardPattern.h"
#include "eld/ScriptParser/ScriptLexer.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBufferRef.h"
#include "llvm/Support/SaveAndRestore.h"
#include <optional>
#include <utility>
using namespace llvm;
using namespace eld::v2;
using namespace eld;
ScriptParser::ScriptParser(eld::LinkerConfig &Config, eld::ScriptFile &File)
: ScriptLexer(Config, File) {}
void ScriptParser::readLinkerScript() {
while (!atEOF()) {
StringRef Tok = next();
if (atEOF())
break;
if (Tok == ";") {
continue;
}
if (Tok == "ENTRY") {
readEntry();
} else if (Tok == "SECTIONS") {
readSections();
} else if (Tok == "INPUT" || Tok == "GROUP") {
bool IsInputCmd = (Tok == "INPUT");
readInputOrGroup(IsInputCmd);
} else if (Tok == "OUTPUT") {
readOutput();
} else if (Tok == "PHDRS") {
readPhdrs();
} else if (Tok == "NOCROSSREFS") {
readNoCrossRefs();
} else if (Tok == "SEARCH_DIR") {
readSearchDir();
} else if (Tok == "OUTPUT_ARCH") {
readOutputArch();
} else if (Tok == "MEMORY") {
readMemory();
} else if (Tok == "EXTERN") {
readExtern();
} else if (Tok == "REGION_ALIAS") {
readRegionAlias();
} else if (Tok == "OUTPUT_FORMAT") {
readOutputFormat();
} else if (Tok == "VERSION") {
readVersion();
} else if (readInclude(Tok)) {
} else if (readAssignment(Tok)) {
} else if (readPluginDirective(Tok)) {
} else {
setError("unknown directive: " + Tok);
}
}
}
bool ScriptParser::readAssignment(llvm::StringRef Tok) {
if (Tok == "ASSERT") {
readAssert();
// Read optional semi-colon at the end of ASSERT.
consume(";");
return true;
}
if (Tok == "PRINT") {
readPrint();
// Read optional semi-colon at the end of PRINT.
consume(";");
return true;
}
bool Ret = false;
StringRef Op = peek(LexState::Expr);
if (Op.starts_with("=") ||
(Op.size() == 2 && Op[1] == '=' && strchr("*/+-&|^", Op[0])) ||
Op == "<<=" || Op == ">>=") {
Ret = readSymbolAssignment(Tok);
} else if (Tok == "PROVIDE" || Tok == "HIDDEN" || Tok == "PROVIDE_HIDDEN") {
readProvideHidden(Tok);
Ret = true;
}
if (Ret)
expectButContinue(";");
return Ret;
}
void ScriptParser::readEntry() {
expect("(");
StringRef Tok = next();
StringRef EntrySymbol = unquote(Tok);
expect(")");
auto *EntryCmd = ThisScriptFile.addEntryPoint(EntrySymbol.str());
EntryCmd->setLineNumberInContext(PrevTokLine);
if (ThisConfig.options().shouldTraceLinkerScript())
EntryCmd->dump(llvm::outs());
}
eld::Expression *ScriptParser::readExpr() {
if (atEOF()) {
Module &Module = ThisScriptFile.module();
// We do not return nullptr here because the returned expression is
// dereferenced at many places. We can add a null-pointer check everywhere,
// but that would impose issues if we want to extend the parser to continue
// parsing despite errors (the way we do with --no-inhibit-exec for overall
// linking). Adding checks everywhere would also violate the parser design
// to be able to continue parsing even after errors have occurred.
return make<NullExpression>(Module);
}
// Our lexer is context-aware. Set the in-expression bit so that
// they apply different tokenization rules.
enum LexState Orig = LexState;
LexState = LexState::Expr;
eld::Expression *E = readExpr1(readPrimary(), /*minPrec=*/0);
LexState = Orig;
return E;
}
eld::Expression *ScriptParser::readExpr1(eld::Expression *Lhs, int MinPrec) {
while (!atEOF() && diagnose()) {
// Read an operator and an expression.
StringRef Op1 = peek();
if (precedence(Op1) < MinPrec)
break;
if (consume("?"))
return readTernary(Lhs);
skip();
eld::Expression *Rhs = readPrimary();
// Evaluate the remaining part of the expression first if the
// next operator has greater precedence than the previous one.
// For example, if we have read "+" and "3", and if the next
// operator is "*", then we'll evaluate 3 * ... part first.
while (!atEOF()) {
StringRef Op2 = peek();
if (precedence(Op2) <= precedence(Op1))
break;
Rhs = readExpr1(Rhs, precedence(Op2));
}
Lhs = &combine(Op1, *Lhs, *Rhs);
}
return Lhs;
}
int ScriptParser::precedence(StringRef Op) {
return StringSwitch<int>(Op)
.Cases({"*", "/", "%"}, 11)
.Cases({"+", "-"}, 10)
.Cases({"<<", ">>"}, 9)
.Cases({"<", "<=", ">", ">="}, 8)
.Cases({"==", "!="}, 7)
.Case("&", 6)
.Case("^", 5)
.Case("|", 4)
.Case("&&", 3)
.Case("||", 2)
.Case("?", 1)
.Default(-1);
}
eld::Expression &ScriptParser::combine(llvm::StringRef Op, eld::Expression &L,
eld::Expression &R) {
Module &Module = ThisScriptFile.module();
if (Op == "+")
return *(make<Add>(Module, L, R));
if (Op == "-")
return *(make<Subtract>(Module, L, R));
if (Op == "*")
return *(make<Multiply>(Module, L, R));
if (Op == "/") {
// FIXME: It be useful to pass current location for reporting
// division by zero error!
return *(make<Divide>(Module, L, R));
}
if (Op == "%") {
// FIXME: It be useful to pass current location for reporting
// modulo by zero error!
return *(make<Modulo>(Module, L, R));
}
if (Op == "<<")
return *(make<LeftShift>(Module, L, R));
if (Op == ">>")
return *(make<RightShift>(Module, L, R));
if (Op == "<")
return *(make<ConditionLT>(Module, L, R));
if (Op == ">")
return *(make<ConditionGT>(Module, L, R));
if (Op == ">=")
return *(make<ConditionGTE>(Module, L, R));
if (Op == "<=")
return *(make<ConditionLTE>(Module, L, R));
if (Op == "==")
return *(make<ConditionEQ>(Module, L, R));
if (Op == "!=")
return *(make<ConditionNEQ>(Module, L, R));
if (Op == "||")
return *(make<LogicalOp>(Expression::LOGICAL_OR, Module, L, R));
if (Op == "&&")
return *(make<LogicalOp>(Expression::LOGICAL_AND, Module, L, R));
if (Op == "&")
return *(make<BitwiseAnd>(Module, L, R));
if (Op == "^")
return *(make<BitwiseXor>(Module, L, R));
if (Op == "|")
return *(make<BitwiseOr>(Module, L, R));
llvm_unreachable("invalid operator");
}
eld::Expression *ScriptParser::readPrimary() {
if (peek() == "(")
return readParenExpr(/*setParen=*/true);
Module &Module = ThisScriptFile.module();
if (consume("~")) {
Expression *E = readPrimary();
return make<Complement>(Module, *E);
}
if (consume("!")) {
Expression *E = readPrimary();
return make<UnaryNot>(Module, *E);
}
if (consume("-")) {
Expression *E = readPrimary();
return make<UnaryMinus>(Module, *E);
}
if (consume("+")) {
Expression *E = readPrimary();
return make<UnaryPlus>(Module, *E);
}
StringRef Tok = next();
std::string Location = getCurrentLocation();
// Built-in functions are parsed here.
// https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
if (Tok == "ABSOLUTE") {
Expression *E = readParenExpr(/*setParen=*/true);
return make<Absolute>(Module, *E);
}
if (Tok == "ADDR") {
StringRef Name = unquote(readParenLiteral());
if (Name == "NEXT_SECTION") {
setError(
"NEXT_SECTION is only supported as an argument to ALIGNOF or SIZEOF");
return make<Integer>(Module, "", 0);
}
// FIXME: Location might be handly for 'undefined section' error.
return make<Addr>(Module, Name.str());
}
if (Tok == "ALIGN") {
expect("(");
Expression *E = readExpr();
if (consume(")")) {
// FIXME: Location given here may be overwritten for outermost ALIGN
// expressions.
return make<AlignExpr>(Module, Location, *E, *make<Symbol>(Module, "."));
}
expect(",");
Expression *E2 = readExpr();
expect(")");
// FIXME: Location given here may be overwritten for outermost ALIGN
// expressions.
return make<AlignExpr>(Module, Location, *E2, *E);
}
if (Tok == "ALIGNOF") {
StringRef Name = unquote(readParenLiteral());
// FIXME: Location might be useful for undefined section related errors.
return make<AlignOf>(Module, Name.str());
}
if (Tok == "ASSERT")
return readAssert();
if (Tok == "CONSTANT")
return readConstant();
if (Tok == "DATA_SEGMENT_ALIGN") {
expect("(");
Expression *E1 = readExpr();
expect(",");
Expression *E2 = readExpr();
expect(")");
return make<DataSegmentAlign>(Module, *E1, *E2);
}
if (Tok == "DATA_SEGMENT_END") {
expect("(");
Expression *E = readExpr();
expect(")");
return make<DataSegmentEnd>(Module, *E);
}
if (Tok == "DATA_SEGMENT_RELRO_END") {
expect("(");
Expression *E1 = readExpr();
expect(",");
Expression *E2 = readExpr();
expect(")");
return make<DataSegmentRelRoEnd>(Module, *E1, *E2);
}
if (Tok == "DEFINED") {
StringRef Name = unquote(readParenLiteral());
return make<Defined>(Module, Name.str());
}
if (Tok == "LENGTH") {
StringRef Name = readParenLiteral();
return make<QueryMemory>(Expression::LENGTH, Module, Name.str());
}
if (Tok == "LOADADDR") {
StringRef Name = unquote(readParenLiteral());
if (Name == "NEXT_SECTION") {
setError(
"NEXT_SECTION is only supported as an argument to ALIGNOF or SIZEOF");
return make<Integer>(Module, "", 0);
}
return make<LoadAddr>(Module, Name.str());
}
if (Tok == "LOG2CEIL") {
expect("(");
Expression *E = readExpr();
expect(")");
return make<Log2Ceil>(Module, *E);
}
if (Tok == "MAX" || Tok == "MIN") {
expect("(");
Expression *E1 = readExpr();
expect(",");
Expression *E2 = readExpr();
expect(")");
if (Tok == "MIN")
return make<Min>(Module, *E1, *E2);
return make<Max>(Module, *E1, *E2);
}
if (Tok == "ORIGIN") {
StringRef Name = readParenLiteral();
return make<QueryMemory>(Expression::ORIGIN, Module, Name.str());
}
if (Tok == "SEGMENT_START") {
expect("(");
StringRef Name = unquote(next());
expect(",");
Expression *E = readExpr();
expect(")");
return make<SegmentStart>(Module, Name.str(), *E);
}
if (Tok == "SIZEOF") {
StringRef Name = readParenName();
return make<SizeOf>(Module, Name.str());
}
if (Tok == "SIZEOF_HEADERS")
return make<SizeOfHeaders>(Module, &ThisScriptFile);
// Tok is a literal number.
if (std::optional<uint64_t> Val = parseInt(Tok))
return make<Integer>(Module, Tok.str(), Val.value());
// Tok is a symbol name.
if (Tok.starts_with("\""))
Tok = unquote(Tok);
if (Tok == "NEXT_SECTION") {
setError(
"NEXT_SECTION is only supported as an argument to ALIGNOF or SIZEOF");
return make<Integer>(Module, "", 0);
}
if (!isValidSymbolName(Tok))
setError("malformed number: " + Tok);
return make<Symbol>(Module, Tok.str());
}
Expression *ScriptParser::readParenExpr(bool SetParen) {
expect("(");
Expression *E = readExpr();
expect(")");
if (SetParen)
E->setParen();
return E;
}
StringRef ScriptParser::readParenLiteral() {
expect("(");
enum LexState Orig = LexState;
LexState = LexState::Expr;
StringRef Tok = next();
LexState = Orig;
expect(")");
return Tok;
}
Expression *ScriptParser::readConstant() {
StringRef S = readParenLiteral();
Module &Module = ThisScriptFile.module();
if (S == "COMMONPAGESIZE")
return make<Constant>(Module, "COMMONPAGESIZE", Expression::COMMONPAGESIZE);
if (S == "MAXPAGESIZE")
return make<Constant>(Module, "MAXPAGESIZE", Expression::MAXPAGESIZE);
setError("unknown constant: " + S);
return make<Integer>(Module, "", 0);
}
std::optional<uint64_t> ScriptParser::parseInt(StringRef Tok) const {
// Hexadecimal
uint64_t Val = 0;
if (Tok.starts_with_insensitive("0x")) {
if (!to_integer(Tok.substr(2), Val, 16))
return std::nullopt;
return Val;
}
if (Tok.ends_with_insensitive("H")) {
if (!to_integer(Tok.drop_back(), Val, 16))
return std::nullopt;
return Val;
}
// Decimal
if (Tok.ends_with_insensitive("K")) {
if (!to_integer(Tok.drop_back(), Val, 10))
return std::nullopt;
return Val * 1024;
}
if (Tok.ends_with_insensitive("M")) {
if (!to_integer(Tok.drop_back(), Val, 10))
return std::nullopt;
return Val * 1024 * 1024;
}
if (!to_integer(Tok, Val, 10))
return std::nullopt;
return Val;
}
bool ScriptParser::isValidSymbolName(StringRef S) {
auto Valid = [](char C) {
return isAlnum(C) || C == '$' || C == '.' || C == '_';
};
return !S.empty() && !isDigit(S[0]) && llvm::all_of(S, Valid);
}
bool ScriptParser::readSymbolAssignment(StringRef Tok,
Assignment::Type AssignType) {
StringRef Name = unquote(Tok);
StringRef Op = next(LexState::Expr);
assert(Op == "=" || Op == "*=" || Op == "/=" || Op == "+=" || Op == "-=" ||
Op == "&=" || Op == "|=" || Op == "^=" || Op == "<<=" || Op == ">>=");
// Note: GNU ld does not support %=.
Expression *E = readExpr();
Module &Module = ThisScriptFile.module();
if (Op != "=") {
Symbol *S = make<Symbol>(Module, Name.str());
std::string Loc = getCurrentLocation();
char SubOp = Op[0];
switch (SubOp) {
case '*':
E = make<Multiply>(Module, *S, *E);
break;
case '/':
E = make<Divide>(Module, *S, *E);
break;
case '+':
E = make<Add>(Module, *S, *E);
break;
case '-':
E = make<Subtract>(Module, *S, *E);
break;
case '<':
E = make<LeftShift>(Module, *S, *E);
break;
case '>':
E = make<RightShift>(Module, *S, *E);
break;
case '&':
E = make<BitwiseAnd>(Module, *S, *E);
break;
case '|':
E = make<BitwiseOr>(Module, *S, *E);
break;
case '^':
E = make<BitwiseXor>(Module, *S, *E);
break;
default:
llvm_unreachable("");
}
E->setAssign();
}
ThisScriptFile.addAssignment(Name.str(), E, AssignType);
return true;
}
Expression *ScriptParser::readTernary(Expression *Cond) {
Expression *L = readExpr();
expect(":");
Expression *R = readExpr();
return make<Ternary>(ThisScriptFile.module(), *Cond, *L, *R);
}
void ScriptParser::readProvideHidden(StringRef Tok) {
Assignment::Type AssignType;
if (Tok == "PROVIDE")
AssignType = Assignment::Type::PROVIDE;
else if (Tok == "HIDDEN")
AssignType = Assignment::Type::HIDDEN;
else if (Tok == "PROVIDE_HIDDEN")
AssignType = Assignment::Type::PROVIDE_HIDDEN;
else
llvm_unreachable("Expected PROVIDE/HIDDEN/PROVIDE_HIDDEN assignments!");
expect("(");
llvm::SaveAndRestore SaveLexState(LexState, LexState::Expr);
Tok = next();
if (peek() != "=") {
setError("= expected, but got " + next());
while (!atEOF() && next() != ")")
;
}
readSymbolAssignment(Tok, AssignType);
expect(")");
}
void ScriptParser::readSections() {
expect("{");
ThisScriptFile.enterSectionsCmd();
while (peek() != "}" && !atEOF()) {
llvm::StringRef Tok = next();
if (readInclude(Tok)) {
} else if (readAssignment(Tok)) {
} else if (Tok == "OVERLAY") {
readOverlay();
} else {
readOutputSectionDescription(Tok);
}
}
expect("}");
ThisScriptFile.leaveSectionsCmd();
}
void ScriptParser::readOverlay() {
const uint32_t OverlayID = ++OverlayCounter;
// OVERLAY [start] :
Expression *Start = nullptr;
bool HasStart = false;
if (peek(LexState::Expr) != ":") {
Start = readExpr();
HasStart = true;
}
expect(LexState::Expr, ":");
// GNU ld supports optional header tokens like NOCROSSREFS and AT(...).
bool NoCrossRefs = false;
Expression *LMA = nullptr;
while (true) {
if (consume("NOCROSSREFS")) {
NoCrossRefs = true;
continue;
}
if (consume("AT")) {
LMA = readParenExpr(/*setParen=*/false);
continue;
}
break;
}
llvm::SmallVector<const StrToken *, 4> Members;
expect("{");
while (peek() != "}" && !atEOF()) {
llvm::StringRef Tok = next();
if (Tok == ";") {
continue;
}
if (readInclude(Tok)) {
} else if (readAssignment(Tok)) {
} else {
Members.push_back(ThisScriptFile.createParserStr(unquote(Tok)));
readOverlayMemberOutputSectionDescription(Tok);
}
}
expect("}");
OutputSectDesc::Epilog Epilog = readOutputSectDescEpilogue();
OverlayDesc *O = ThisScriptFile.createOverlayDesc(OverlayID, Start, HasStart,
NoCrossRefs, LMA, Epilog);
for (const StrToken *M : Members)
O->addPendingMemberName(M);
}
void ScriptParser::readOverlayMemberOutputSectionDescription(
llvm::StringRef Tok) {
llvm::StringRef OutSectName = unquote(Tok);
OutputSectDesc::Prolog Prologue;
Prologue.init();
// Overlay members are just `OutputSectionName { InputSectDesc... }`.
// They do not support the regular output-section prologue/epilogue syntax.
if (peek() != "{") {
setError("overlay member output sections do not support output section "
"prologue");
// Recovery: Skip tokens until we reach the section body.
while (!atEOF() && peek() != "{" && peek() != "}")
next();
}
ThisScriptFile.enterOutputSectDesc(OutSectName.str(), Prologue);
expect("{");
while (peek() != "}" && !atEOF()) {
StringRef Tok = next();
if (Tok == ";") {
// Empty commands are allowed. Do nothing.
} else if (Tok == "FILL") {
readFill();
} else if (readInclude(Tok)) {
} else if (readOutputSectionData(Tok)) {
} else if (readAssignment(Tok)) {
} else if (readSortConstructors(Tok)) {
} else {
readInputSectionDescription(Tok);
}
}
expect("}");
// Disallow output-section epilogue tokens after the member body and consume
// them for recovery so parsing can continue.
if (peek() == ">" || peek() == "AT" || peek().starts_with(":") ||
peek() == "=" || peek().starts_with("=") || peek() == "INSERT") {
if (peek() != "INSERT") {
setError("overlay member output sections do not support output section "
"epilogue");
}
bool WasInOverlayMemberEpilogue = MInOverlayMemberEpilogue;
MInOverlayMemberEpilogue = true;
(void)readOutputSectDescEpilogue();
MInOverlayMemberEpilogue = WasInOverlayMemberEpilogue;
}
OutputSectDesc::Epilog Epilogue;
ThisScriptFile.leavingOutputSectDesc();
ThisScriptFile.leaveOutputSectDesc(Epilogue);
}
Expression *ScriptParser::readAssert() {
expect("(");
Expression *E = readExpr();
expect(",");
StringRef Msg = unquote(next());
expect(")");
Expression *AssertCmd =
make<eld::AssertCmd>(ThisScriptFile.module(), Msg.str(), *E);
ThisScriptFile.addAssignment("ASSERT", AssertCmd, Assignment::ASSERT);
return AssertCmd;
}
Expression *ScriptParser::readPrint() {
expect("(");
StringRef FormatTok = next();
std::string Format = unquote(FormatTok).str();
std::vector<Expression *> Args;
if (consume(",")) {
while (peek() != ")" && !atEOF()) {
Args.push_back(readExpr());
if (!consume(","))
break;
}
}
expect(")");
Expression *PrintCmd = make<eld::PrintCmd>(
ThisScriptFile.module(), std::move(Format), std::move(Args));
ThisScriptFile.addAssignment("PRINT", PrintCmd, Assignment::PRINT);
return PrintCmd;
}
void ScriptParser::readInputOrGroup(bool IsInputCmd) {
expect("(");
ThisScriptFile.createStringList();
while (peek() != ")" && !atEOF()) {
if (consume("AS_NEEDED")) {
readAsNeeded();
} else
addFile(unquote(next()));
consume(",");
}
expect(")");
StringList *Inputs = ThisScriptFile.getCurrentStringList();
if (IsInputCmd)
ThisScriptFile.addInputCmd(
*Inputs,
ThisScriptFile.getLinkerScriptFile().getInput()->getAttribute());
else
ThisScriptFile.addGroupCmd(
*Inputs,
ThisScriptFile.getLinkerScriptFile().getInput()->getAttribute());
}
void ScriptParser::readAsNeeded() {
expect("(");
ThisScriptFile.setAsNeeded(true);
while (peek() != ")" && !atEOF()) {
addFile(unquote(next()));
consume(",");
}
expect(")");
ThisScriptFile.setAsNeeded(false);
}
std::string ScriptParser::expandSysrootMarkers(StringRef Name) const {
StringRef Suffix;
if (Name.starts_with("="))
Suffix = Name.substr(1);
else if (Name.starts_with("$SYSROOT"))
Suffix = Name.substr(8); // strlen("$SYSROOT") == 8
else
return Name.str();
auto &SearchDirs = ThisConfig.directories();
if (SearchDirs.hasSysRoot())
return (SearchDirs.sysroot().native() + Suffix).str();
return Suffix.str();
}
void ScriptParser::addFile(StringRef Name) {
StrToken *InputStrTok = nullptr;
if (Name.consume_front("-l"))
InputStrTok = ThisScriptFile.createNameSpecToken(Name.str(),
ThisScriptFile.asNeeded());
else {
std::string ExpandedName = expandSysrootMarkers(Name);
InputStrTok =
ThisScriptFile.createFileToken(ExpandedName, ThisScriptFile.asNeeded());
}
ThisScriptFile.getCurrentStringList()->pushBack(InputStrTok);
}
void ScriptParser::readOutput() {
expect("(");
StringRef Name = next();
ThisScriptFile.addOutputCmd(unquote(Name).str());
expect(")");
}
void ScriptParser::readOutputSectionDescription(llvm::StringRef Tok) {
llvm::StringRef OutSectName = unquote(Tok);
OutputSectDesc::Prolog Prologue = readOutputSectDescPrologue();
ThisScriptFile.enterOutputSectDesc(OutSectName.str(), Prologue);
expect("{");
while (peek() != "}" && !atEOF()) {
StringRef Tok = next();
if (Tok == ";") {
// Empty commands are allowed. Do nothing.
} else if (Tok == "FILL") {
readFill();
} else if (readInclude(Tok)) {
} else if (readOutputSectionData(Tok)) {
} else if (readAssignment(Tok)) {
} else if (readSortConstructors(Tok)) {
} else {
readInputSectionDescription(Tok);
}
}
expect("}");
OutputSectDesc::Epilog Epilogue = readOutputSectDescEpilogue();
ThisScriptFile.leavingOutputSectDesc();
ThisScriptFile.leaveOutputSectDesc(Epilogue);
}
void ScriptParser::readInputSectionDescription(StringRef Tok) {
InputSectDesc::Policy Policy = InputSectDesc::Policy::NoKeep;
if (Tok == "KEEP")
Policy = InputSectDesc::Policy::Keep;
else if (Tok == "DONTMOVE")
Policy = InputSectDesc::Policy::Fixed;
else if (Tok == "KEEP_DONTMOVE")
Policy = InputSectDesc::Policy::KeepFixed;
if (Policy != InputSectDesc::Policy::NoKeep) {
expect("(");
Tok = next();
}
InputSectDesc::Spec ISDSpec = readInputSectionDescSpec(Tok);
if (Policy != InputSectDesc::Policy::NoKeep)
expect(")");
ThisScriptFile.addInputSectDesc(Policy, ISDSpec);
}
bool ScriptParser::readSortConstructors(llvm::StringRef Tok) {
if (Tok != "SORT" || peek() != "(")
return false;
skip();
if (peek() != "CONSTRUCTORS") {
setError("Invalid SORT directive: expected CONSTRUCTORS");
while (!consume(")") && !atEOF())
skip();
return true;
}
skip();
expect(")");
return true;
}
InputSectDesc::Spec ScriptParser::readInputSectionDescSpec(StringRef Tok) {
ExcludeFiles *EF = nullptr;
if (Tok == "EXCLUDE_FILE") {
EF = readExcludeFile();
Tok = next();
}
WildcardPattern *FilePat = nullptr, *ArchiveMem = nullptr;
bool IsArchive = false;
if (!isValidFilePattern(Tok))
setError("Invalid file pattern: " + Tok);
if (!Tok.contains(':'))
FilePat = createAndRegisterWildcardPattern(Tok);
else {
std::pair<llvm::StringRef, llvm::StringRef> Split = Tok.split(':');
FilePat = createAndRegisterWildcardPattern(Split.first);
if (!Split.second.empty()) {
ArchiveMem = createAndRegisterWildcardPattern(Split.second);
}
llvm::StringRef peekTok = peek();
if (!atEOF() && peekTok != "(" &&
computeLineNumber(peekTok) == getCurrentLineNumber()) {
next();
if (ThisConfig.showLinkerScriptWarnings())
setWarn("Space between archive:member file pattern is deprecated");
ArchiveMem = createAndRegisterWildcardPattern(peekTok);
}
IsArchive = true;
}
StringList *WildcardSections = nullptr;
if (consume("(")) {
ThisScriptFile.createStringList();
while (peek() != ")" && !atEOF()) {
WildcardPattern *SectPat = readWildcardPattern();
if (!isValidSectionPattern(SectPat->name()))
setError("Invalid section pattern: " + SectPat->name());
ThisScriptFile.getCurrentStringList()->pushBack(SectPat);
}
expect(")");
WildcardSections = ThisScriptFile.getCurrentStringList();
}
InputSectDesc::Spec ISDSpec;
ISDSpec.initialize();
ISDSpec.WildcardFilePattern = FilePat;
ISDSpec.WildcardSectionPattern = WildcardSections;
ISDSpec.InputArchiveMember = ArchiveMem;
ISDSpec.InputIsArchive = IsArchive;
ISDSpec.ExcludeFilesRule = EF;
return ISDSpec;
}
OutputSectDesc::Prolog ScriptParser::readOutputSectDescPrologue() {
OutputSectDesc::Prolog Prologue;
Prologue.init();
if (peek(LexState::Expr) != ":") {
if (consume("(")) {
if (!readOutputSectTypeAndPermissions(Prologue, peek()))
Prologue.OutputSectionVMA = readExpr();
expect(")");
} else if (peek() == "{") {
expect(":");
} else {
Prologue.PluginCmd = readOutputSectionPluginDirective();
if (!Prologue.PluginCmd)
Prologue.OutputSectionVMA = readExpr();
}
if (Prologue.OutputSectionVMA != nullptr && consume("(")) {
StringRef Tok = peek();
if (!readOutputSectTypeAndPermissions(Prologue, Tok))
setError("Invalid output section type: " + Tok);
expect(")");
}
if (!Prologue.PluginCmd)
Prologue.PluginCmd = readOutputSectionPluginDirective();
if (Prologue.PluginCmd)
Prologue.PluginCmd->setHasOutputSection();
}
expect(LexState::Expr, ":");
if (consume("AT"))
Prologue.OutputSectionLMA = readParenExpr(/*setParen=*/false);
if (consume("ALIGN"))
Prologue.Alignment = readParenExpr(/*setParen=*/false);
if (consume("ALIGN_WITH_INPUT"))
Prologue.HasAlignWithInput = true;
if (Prologue.Alignment && Prologue.HasAlignWithInput) {
setError("ALIGN_WITH_INPUT specified with explicit alignment ");
}
if (consume("SUBALIGN"))
Prologue.OutputSectionSubaAlign = readParenExpr(/*setParen=*/false);
if (consume("ONLY_IF_RO"))
Prologue.SectionConstraint = OutputSectDesc::Constraint::ONLY_IF_RO;
else if (consume("ONLY_IF_RW"))
Prologue.SectionConstraint = OutputSectDesc::Constraint::ONLY_IF_RW;
return Prologue;
}
bool ScriptParser::readOutputSectTypeAndPermissions(
OutputSectDesc::Prolog &Prologue, llvm::StringRef Tok) {
std::optional<OutputSectDesc::Type> ExpType = readOutputSectType(Tok);
if (ExpType)
Prologue.ThisType = ExpType.value();
else
return false;
next();
if (consume(",")) {
Tok = next();
std::optional<uint32_t> ExpFlag = readOutputSectPermissions(Tok);
if (ExpFlag)
Prologue.SectionFlag = ExpFlag.value();
else
setError("Invalid permission flag: " + Tok);
}
return true;
}
std::optional<OutputSectDesc::Type>
ScriptParser::readOutputSectType(StringRef Tok) {
return StringSwitch<std::optional<OutputSectDesc::Type>>(Tok)
.Case("NOLOAD", OutputSectDesc::Type::NOLOAD)
.Case("DSECT", OutputSectDesc::Type::DSECT)
.Case("COPY", OutputSectDesc::Type::COPY)
.Case("INFO", OutputSectDesc::Type::INFO)
.Case("OVERLAY", OutputSectDesc::Type::OVERLAY)
.Case("PROGBITS", OutputSectDesc::Type::PROGBITS)
.Case("UNINIT", OutputSectDesc::Type::UNINIT)
.Default(std::nullopt);
}
std::optional<uint32_t>
ScriptParser::readOutputSectPermissions(llvm::StringRef Tok) {
if (std::optional<uint64_t> Permissions = parseInt(Tok))
return Permissions;
return StringSwitch<std::optional<uint32_t>>(Tok)
.Case("RW", OutputSectDesc::Permissions::RW)
.Case("RWX", OutputSectDesc::Permissions::RWX)
.Case("RX", OutputSectDesc::Permissions::RX)
.Case("R", OutputSectDesc::Permissions::R)
.Default(std::nullopt);
}
void ScriptParser::readPhdrs() {
expect("{");
ThisScriptFile.enterPhdrsCmd();
while (peek() != "}" && !atEOF()) {
PhdrSpec PhdrSpec;
PhdrSpec.init();
llvm::StringRef NameTok = next();
PhdrSpec.Name =
ThisScriptFile.createParserStr(NameTok.data(), NameTok.size());
llvm::StringRef TypeTok = next();
auto OptPhdrType = readPhdrType(TypeTok);
if (OptPhdrType.has_value())
PhdrSpec.ThisType = OptPhdrType.value();
else
setError("invalid program header type: " + TypeTok);
while (peek() != ";" && !atEOF()) {
if (consume("FILEHDR"))
PhdrSpec.ScriptHasFileHdr = true;
else if (consume("PHDRS"))
PhdrSpec.ScriptHasPhdr = true;