Coverage Report

Created: 2018-06-18 20:01

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/LinkerScript.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- LinkerScript.cpp ---------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file contains the parser/evaluator of the linker script.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "LinkerScript.h"
15
#include "Config.h"
16
#include "InputSection.h"
17
#include "OutputSections.h"
18
#include "SymbolTable.h"
19
#include "Symbols.h"
20
#include "SyntheticSections.h"
21
#include "Target.h"
22
#include "Writer.h"
23
#include "lld/Common/Memory.h"
24
#include "lld/Common/Strings.h"
25
#include "lld/Common/Threads.h"
26
#include "llvm/ADT/STLExtras.h"
27
#include "llvm/ADT/StringRef.h"
28
#include "llvm/BinaryFormat/ELF.h"
29
#include "llvm/Support/Casting.h"
30
#include "llvm/Support/Endian.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include "llvm/Support/FileSystem.h"
33
#include "llvm/Support/Path.h"
34
#include <algorithm>
35
#include <cassert>
36
#include <cstddef>
37
#include <cstdint>
38
#include <iterator>
39
#include <limits>
40
#include <string>
41
#include <vector>
42
43
using namespace llvm;
44
using namespace llvm::ELF;
45
using namespace llvm::object;
46
using namespace llvm::support::endian;
47
using namespace lld;
48
using namespace lld::elf;
49
50
LinkerScript *elf::Script;
51
52
548
static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
53
548
  if (OutputSection *OS = InputSec->getOutputSection())
54
546
    return OS->Addr;
55
2
  error(Loc + ": unable to evaluate expression: input section " +
56
2
        InputSec->Name + " has no output section assigned");
57
2
  return 0;
58
2
}
59
60
5.51k
uint64_t ExprValue::getValue() const {
61
5.51k
  if (Sec)
62
310
    return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
63
310
                   Alignment);
64
5.20k
  return alignTo(Val, Alignment);
65
5.20k
}
66
67
258
uint64_t ExprValue::getSecAddr() const {
68
258
  if (Sec)
69
238
    return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
70
20
  return 0;
71
20
}
72
73
305
uint64_t ExprValue::getSectionOffset() const {
74
305
  // If the alignment is trivial, we don't have to compute the full
75
305
  // value to know the offset. This allows this function to succeed in
76
305
  // cases where the output section is not yet known.
77
305
  if (Alignment == 1 && 
(289
!Sec289
||
!Sec->getOutputSection()218
))
78
75
    return Val;
79
230
  return getValue() - getSecAddr();
80
230
}
81
82
OutputSection *LinkerScript::createOutputSection(StringRef Name,
83
232k
                                                 StringRef Location) {
84
232k
  OutputSection *&SecRef = NameToOutputSection[Name];
85
232k
  OutputSection *Sec;
86
232k
  if (SecRef && 
SecRef->Location.empty()14
) {
87
5
    // There was a forward reference.
88
5
    Sec = SecRef;
89
232k
  } else {
90
232k
    Sec = make<OutputSection>(Name, SHT_NOBITS, 0);
91
232k
    if (!SecRef)
92
232k
      SecRef = Sec;
93
232k
  }
94
232k
  Sec->Location = Location;
95
232k
  return Sec;
96
232k
}
97
98
49
OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
99
49
  OutputSection *&CmdRef = NameToOutputSection[Name];
100
49
  if (!CmdRef)
101
8
    CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
102
49
  return CmdRef;
103
49
}
104
105
// Expands the memory region by the specified size.
106
static void expandMemoryRegion(MemoryRegion *MemRegion, uint64_t Size,
107
126
                               StringRef RegionName, StringRef SecName) {
108
126
  MemRegion->CurPos += Size;
109
126
  uint64_t NewSize = MemRegion->CurPos - MemRegion->Origin;
110
126
  if (NewSize > MemRegion->Length)
111
3
    error("section '" + SecName + "' will not fit in region '" + RegionName +
112
3
          "': overflowed by " + Twine(NewSize - MemRegion->Length) + " bytes");
113
126
}
114
115
446k
void LinkerScript::expandMemoryRegions(uint64_t Size) {
116
446k
  if (Ctx->MemRegion)
117
103
    expandMemoryRegion(Ctx->MemRegion, Size, Ctx->MemRegion->Name,
118
103
                       Ctx->OutSec->Name);
119
446k
  if (Ctx->LMARegion)
120
23
    expandMemoryRegion(Ctx->LMARegion, Size, Ctx->LMARegion->Name,
121
23
                       Ctx->OutSec->Name);
122
446k
}
123
124
223k
void LinkerScript::expandOutputSection(uint64_t Size) {
125
223k
  Ctx->OutSec->Size += Size;
126
223k
  expandMemoryRegions(Size);
127
223k
}
128
129
4.29k
void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
130
4.29k
  uint64_t Val = E().getValue();
131
4.29k
  if (Val < Dot && 
InSec9
)
132
2
    error(Loc + ": unable to move location counter backward for: " +
133
2
          Ctx->OutSec->Name);
134
4.29k
135
4.29k
  // Update to location counter means update to section size.
136
4.29k
  if (InSec)
137
32
    expandOutputSection(Val - Dot);
138
4.29k
  Dot = Val;
139
4.29k
}
140
141
// Used for handling linker symbol assignments, for both finalizing
142
// their values and doing early declarations. Returns true if symbol
143
// should be defined from linker script.
144
909
static bool shouldDefineSym(SymbolAssignment *Cmd) {
145
909
  if (Cmd->Name == ".")
146
346
    return false;
147
563
148
563
  if (!Cmd->Provide)
149
510
    return true;
150
53
151
53
  // If a symbol was in PROVIDE(), we need to define it only
152
53
  // when it is a referenced undefined symbol.
153
53
  Symbol *B = Symtab->find(Cmd->Name);
154
53
  if (B && 
!B->isDefined()39
)
155
31
    return true;
156
22
  return false;
157
22
}
158
159
// This function is called from processSectionCommands,
160
// while we are fixing the output section layout.
161
455
void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
162
455
  if (!shouldDefineSym(Cmd))
163
184
    return;
164
271
165
271
  // Define a symbol.
166
271
  Symbol *Sym;
167
271
  uint8_t Visibility = Cmd->Hidden ? 
STV_HIDDEN23
:
STV_DEFAULT248
;
168
271
  std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
169
271
                                              /*CanOmitFromDynSym*/ false,
170
271
                                              /*File*/ nullptr);
171
271
  ExprValue Value = Cmd->Expression();
172
271
  SectionBase *Sec = Value.isAbsolute() ? 
nullptr141
:
Value.Sec130
;
173
271
174
271
  // When this function is called, section addresses have not been
175
271
  // fixed yet. So, we may or may not know the value of the RHS
176
271
  // expression.
177
271
  //
178
271
  // For example, if an expression is `x = 42`, we know x is always 42.
179
271
  // However, if an expression is `x = .`, there's no way to know its
180
271
  // value at the moment.
181
271
  //
182
271
  // We want to set symbol values early if we can. This allows us to
183
271
  // use symbols as variables in linker scripts. Doing so allows us to
184
271
  // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
185
271
  uint64_t SymValue = Value.Sec ? 
0139
:
Value.getValue()132
;
186
271
187
271
  replaceSymbol<Defined>(Sym, nullptr, Cmd->Name, STB_GLOBAL, Visibility,
188
271
                         STT_NOTYPE, SymValue, 0, Sec);
189
271
  Cmd->Sym = cast<Defined>(Sym);
190
271
}
191
192
// This function is called from LinkerScript::declareSymbols.
193
// It creates a placeholder symbol if needed.
194
454
static void declareSymbol(SymbolAssignment *Cmd) {
195
454
  if (!shouldDefineSym(Cmd))
196
184
    return;
197
270
198
270
  // We can't calculate final value right now.
199
270
  Symbol *Sym;
200
270
  uint8_t Visibility = Cmd->Hidden ? 
STV_HIDDEN23
:
STV_DEFAULT247
;
201
270
  std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
202
270
                                              /*CanOmitFromDynSym*/ false,
203
270
                                              /*File*/ nullptr);
204
270
  replaceSymbol<Defined>(Sym, nullptr, Cmd->Name, STB_GLOBAL, Visibility,
205
270
                         STT_NOTYPE, 0, 0, nullptr);
206
270
  Cmd->Sym = cast<Defined>(Sym);
207
270
  Cmd->Provide = false;
208
270
}
209
210
// This method is used to handle INSERT AFTER statement. Here we rebuild
211
// the list of script commands to mix sections inserted into.
212
2.15k
void LinkerScript::processInsertCommands() {
213
2.15k
  std::vector<BaseCommand *> V;
214
2.15k
  auto Insert = [&](std::vector<BaseCommand *> &From) {
215
1.30k
    V.insert(V.end(), From.begin(), From.end());
216
1.30k
    From.clear();
217
1.30k
  };
218
2.15k
219
2.15k
  for (BaseCommand *Base : SectionCommands) {
220
990
    if (auto *OS = dyn_cast<OutputSection>(Base)) {
221
653
      Insert(InsertBeforeCommands[OS->Name]);
222
653
      V.push_back(Base);
223
653
      Insert(InsertAfterCommands[OS->Name]);
224
653
      continue;
225
653
    }
226
337
    V.push_back(Base);
227
337
  }
228
2.15k
229
2.15k
  for (auto &Cmds : {InsertBeforeCommands, InsertAfterCommands})
230
4.31k
    for (const std::pair<StringRef, std::vector<BaseCommand *>> &P : Cmds)
231
1.30k
      if (!P.second.empty())
232
4
        error("unable to INSERT AFTER/BEFORE " + P.first +
233
4
              ": section not defined");
234
2.15k
235
2.15k
  SectionCommands = std::move(V);
236
2.15k
}
237
238
// Symbols defined in script should not be inlined by LTO. At the same time
239
// we don't know their final values until late stages of link. Here we scan
240
// over symbol assignment commands and create placeholder symbols if needed.
241
2.15k
void LinkerScript::declareSymbols() {
242
2.15k
  assert(!Ctx);
243
2.15k
  for (BaseCommand *Base : SectionCommands) {
244
994
    if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
245
337
      declareSymbol(Cmd);
246
337
      continue;
247
337
    }
248
657
    auto *Sec = dyn_cast<OutputSection>(Base);
249
657
    if (!Sec)
250
0
      continue;
251
657
    // If the output section directive has constraints,
252
657
    // we can't say for sure if it is going to be included or not.
253
657
    // Skip such sections for now. Improve the checks if we ever
254
657
    // need symbols from that sections to be declared early.
255
657
    if (Sec->Constraint != ConstraintKind::NoConstraint)
256
14
      continue;
257
643
    for (BaseCommand *Base2 : Sec->SectionCommands)
258
836
      if (auto *Cmd = dyn_cast<SymbolAssignment>(Base2))
259
117
        declareSymbol(Cmd);
260
643
  }
261
2.15k
}
262
263
// This function is called from assignAddresses, while we are
264
// fixing the output section addresses. This function is supposed
265
// to set the final value for a given symbol assignment.
266
484
void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
267
484
  if (Cmd->Name == ".") {
268
197
    setDot(Cmd->Expression, Cmd->Location, InSec);
269
197
    return;
270
197
  }
271
287
272
287
  if (!Cmd->Sym)
273
12
    return;
274
275
275
275
  ExprValue V = Cmd->Expression();
276
275
  if (V.isAbsolute()) {
277
144
    Cmd->Sym->Section = nullptr;
278
144
    Cmd->Sym->Value = V.getValue();
279
144
  } else {
280
131
    Cmd->Sym->Section = V.Sec;
281
131
    Cmd->Sym->Value = V.getSectionOffset();
282
131
  }
283
275
}
284
285
144k
static std::string getFilename(InputFile *File) {
286
144k
  if (!File)
287
11.2k
    return "";
288
133k
  if (File->ArchiveName.empty())
289
132k
    return File->getName();
290
28
  return (File->ArchiveName + "(" + File->getName() + ")").str();
291
28
}
292
293
370
bool LinkerScript::shouldKeep(InputSectionBase *S) {
294
370
  if (KeptSections.empty())
295
352
    return false;
296
18
  std::string Filename = getFilename(S->File);
297
18
  for (InputSectionDescription *ID : KeptSections)
298
18
    if (ID->FilePat.match(Filename))
299
14
      for (SectionPattern &P : ID->SectionPatterns)
300
14
        if (P.SectionPat.match(S->Name))
301
4
          return true;
302
18
  
return false14
;
303
18
}
304
305
// A helper function for the SORT() command.
306
static std::function<bool(InputSectionBase *, InputSectionBase *)>
307
22
getComparator(SortSectionPolicy K) {
308
22
  switch (K) {
309
22
  case SortSectionPolicy::Alignment:
310
115
    return [](InputSectionBase *A, InputSectionBase *B) {
311
115
      // ">" is not a mistake. Sections with larger alignments are placed
312
115
      // before sections with smaller alignments in order to reduce the
313
115
      // amount of padding necessary. This is compatible with GNU.
314
115
      return A->Alignment > B->Alignment;
315
115
    };
316
22
  case SortSectionPolicy::Name:
317
698
    return [](InputSectionBase *A, InputSectionBase *B) {
318
698
      return A->Name < B->Name;
319
698
    };
320
22
  case SortSectionPolicy::Priority:
321
1
    return [](InputSectionBase *A, InputSectionBase *B) {
322
1
      return getPriority(A->Name) < getPriority(B->Name);
323
1
    };
324
22
  default:
325
0
    llvm_unreachable("unknown sort policy");
326
22
  }
327
22
}
328
329
// A helper function for the SORT() command.
330
static bool matchConstraints(ArrayRef<InputSection *> Sections,
331
638
                             ConstraintKind Kind) {
332
638
  if (Kind == ConstraintKind::NoConstraint)
333
624
    return true;
334
14
335
14
  bool IsRW = llvm::any_of(
336
15
      Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; });
337
14
338
14
  return (IsRW && 
Kind == ConstraintKind::ReadWrite11
) ||
339
14
         
(9
!IsRW9
&&
Kind == ConstraintKind::ReadOnly3
);
340
14
}
341
342
static void sortSections(MutableArrayRef<InputSection *> Vec,
343
1.39k
                         SortSectionPolicy K) {
344
1.39k
  if (K != SortSectionPolicy::Default && 
K != SortSectionPolicy::None23
)
345
22
    std::stable_sort(Vec.begin(), Vec.end(), getComparator(K));
346
1.39k
}
347
348
// Sort sections as instructed by SORT-family commands and --sort-section
349
// option. Because SORT-family commands can be nested at most two depth
350
// (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
351
// line option is respected even if a SORT command is given, the exact
352
// behavior we have here is a bit complicated. Here are the rules.
353
//
354
// 1. If two SORT commands are given, --sort-section is ignored.
355
// 2. If one SORT command is given, and if it is not SORT_NONE,
356
//    --sort-section is handled as an inner SORT command.
357
// 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
358
// 4. If no SORT command is given, sort according to --sort-section.
359
static void sortInputSections(MutableArrayRef<InputSection *> Vec,
360
698
                              const SectionPattern &Pat) {
361
698
  if (Pat.SortOuter == SortSectionPolicy::None)
362
2
    return;
363
696
364
696
  if (Pat.SortInner == SortSectionPolicy::Default)
365
693
    sortSections(Vec, Config->SortSection);
366
3
  else
367
3
    sortSections(Vec, Pat.SortInner);
368
696
  sortSections(Vec, Pat.SortOuter);
369
696
}
370
371
// Compute and remember which sections the InputSectionDescription matches.
372
std::vector<InputSection *>
373
693
LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
374
693
  std::vector<InputSection *> Ret;
375
693
376
693
  // Collects all sections that satisfy constraints of Cmd.
377
698
  for (const SectionPattern &Pat : Cmd->SectionPatterns) {
378
698
    size_t SizeBefore = Ret.size();
379
698
380
145k
    for (InputSectionBase *Sec : InputSections) {
381
145k
      if (!Sec->Live || 
Sec->Assigned145k
)
382
1.10k
        continue;
383
144k
384
144k
      // For -emit-relocs we have to ignore entries like
385
144k
      //   .rela.dyn : { *(.rela.data) }
386
144k
      // which are common because they are in the default bfd script.
387
144k
      // We do not ignore SHT_REL[A] linker-synthesized sections here because
388
144k
      // want to support scripts that do custom layout for them.
389
144k
      if (auto *IS = dyn_cast<InputSection>(Sec))
390
144k
        if (IS->getRelocatedSection())
391
12
          continue;
392
144k
393
144k
      std::string Filename = getFilename(Sec->File);
394
144k
      if (!Cmd->FilePat.match(Filename) ||
395
144k
          
Pat.ExcludedFilePat.match(Filename)143k
||
396
144k
          
!Pat.SectionPat.match(Sec->Name)143k
)
397
143k
        continue;
398
1.01k
399
1.01k
      // It is safe to assume that Sec is an InputSection
400
1.01k
      // because mergeable or EH input sections have already been
401
1.01k
      // handled and eliminated.
402
1.01k
      Ret.push_back(cast<InputSection>(Sec));
403
1.01k
      Sec->Assigned = true;
404
1.01k
    }
405
698
406
698
    sortInputSections(MutableArrayRef<InputSection *>(Ret).slice(SizeBefore),
407
698
                      Pat);
408
698
  }
409
693
  return Ret;
410
693
}
411
412
44
void LinkerScript::discard(ArrayRef<InputSection *> V) {
413
44
  for (InputSection *S : V) {
414
25
    if (S == InX::ShStrTab || 
S == InX::Dynamic24
||
S == InX::DynSymTab23
||
415
25
        
S == InX::DynStrTab22
||
S == InX::RelaPlt21
||
S == InX::RelaDyn20
)
416
6
      error("discarding " + S->Name + " section is not allowed");
417
25
418
25
    // You can discard .hash and .gnu.hash sections by linker scripts. Since
419
25
    // they are synthesized sections, we need to handle them differently than
420
25
    // other regular sections.
421
25
    if (S == InX::GnuHashTab)
422
1
      InX::GnuHashTab = nullptr;
423
25
    if (S == InX::HashTab)
424
1
      InX::HashTab = nullptr;
425
25
426
25
    S->Assigned = false;
427
25
    S->Live = false;
428
25
    discard(S->DependentSections);
429
25
  }
430
44
}
431
432
std::vector<InputSection *>
433
657
LinkerScript::createInputSectionList(OutputSection &OutCmd) {
434
657
  std::vector<InputSection *> Ret;
435
657
436
854
  for (BaseCommand *Base : OutCmd.SectionCommands) {
437
854
    if (auto *Cmd = dyn_cast<InputSectionDescription>(Base)) {
438
693
      Cmd->Sections = computeInputSections(Cmd);
439
693
      Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
440
693
    }
441
854
  }
442
657
  return Ret;
443
657
}
444
445
2.13k
void LinkerScript::processSectionCommands() {
446
2.13k
  // A symbol can be assigned before any section is mentioned in the linker
447
2.13k
  // script. In an DSO, the symbol values are addresses, so the only important
448
2.13k
  // section values are:
449
2.13k
  // * SHN_UNDEF
450
2.13k
  // * SHN_ABS
451
2.13k
  // * Any value meaning a regular section.
452
2.13k
  // To handle that, create a dummy aether section that fills the void before
453
2.13k
  // the linker scripts switches to another section. It has an index of one
454
2.13k
  // which will map to whatever the first actual section is.
455
2.13k
  Aether = make<OutputSection>("", 0, SHF_ALLOC);
456
2.13k
  Aether->SectionIndex = 1;
457
2.13k
458
2.13k
  // Ctx captures the local AddressState and makes it accessible deliberately.
459
2.13k
  // This is needed as there are some cases where we cannot just
460
2.13k
  // thread the current state through to a lambda function created by the
461
2.13k
  // script parser.
462
2.13k
  auto Deleter = make_unique<AddressState>();
463
2.13k
  Ctx = Deleter.get();
464
2.13k
  Ctx->OutSec = Aether;
465
2.13k
466
2.13k
  size_t I = 0;
467
2.13k
  // Add input sections to output sections.
468
2.13k
  for (BaseCommand *Base : SectionCommands) {
469
994
    // Handle symbol assignments outside of any output section.
470
994
    if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
471
337
      addSymbol(Cmd);
472
337
      continue;
473
337
    }
474
657
475
657
    if (auto *Sec = dyn_cast<OutputSection>(Base)) {
476
657
      std::vector<InputSection *> V = createInputSectionList(*Sec);
477
657
478
657
      // The output section name `/DISCARD/' is special.
479
657
      // Any input section assigned to it is discarded.
480
657
      if (Sec->Name == "/DISCARD/") {
481
19
        discard(V);
482
19
        Sec->SectionCommands.clear();
483
19
        continue;
484
19
      }
485
638
486
638
      // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
487
638
      // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
488
638
      // sections satisfy a given constraint. If not, a directive is handled
489
638
      // as if it wasn't present from the beginning.
490
638
      //
491
638
      // Because we'll iterate over SectionCommands many more times, the easy
492
638
      // way to "make it as if it wasn't present" is to make it empty.
493
638
      if (!matchConstraints(V, Sec->Constraint)) {
494
6
        for (InputSectionBase *S : V)
495
10
          S->Assigned = false;
496
6
        Sec->SectionCommands.clear();
497
6
        continue;
498
6
      }
499
632
500
632
      // A directive may contain symbol definitions like this:
501
632
      // ".foo : { ...; bar = .; }". Handle them.
502
632
      for (BaseCommand *Base : Sec->SectionCommands)
503
824
        if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
504
118
          addSymbol(OutCmd);
505
632
506
632
      // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
507
632
      // is given, input sections are aligned to that value, whether the
508
632
      // given value is larger or smaller than the original section alignment.
509
632
      if (Sec->SubalignExpr) {
510
5
        uint32_t Subalign = Sec->SubalignExpr().getValue();
511
5
        for (InputSectionBase *S : V)
512
16
          S->Alignment = Subalign;
513
5
      }
514
632
515
632
      // Add input sections to an output section.
516
632
      for (InputSection *S : V)
517
985
        Sec->addSection(S);
518
632
519
632
      Sec->SectionIndex = I++;
520
632
      if (Sec->Noload)
521
3
        Sec->Type = SHT_NOBITS;
522
632
      if (Sec->NonAlloc)
523
3
        Sec->Flags &= ~(uint64_t)SHF_ALLOC;
524
632
    }
525
657
  }
526
2.13k
  Ctx = nullptr;
527
2.13k
}
528
529
static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
530
239k
                                 StringRef Name) {
531
239k
  for (BaseCommand *Base : Vec)
532
277k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
533
141k
      if (Sec->Name == Name)
534
68
        return Sec;
535
239k
  
return nullptr239k
;
536
239k
}
537
538
static OutputSection *createSection(InputSectionBase *IS,
539
231k
                                    StringRef OutsecName) {
540
231k
  OutputSection *Sec = Script->createOutputSection(OutsecName, "<internal>");
541
231k
  Sec->addSection(cast<InputSection>(IS));
542
231k
  return Sec;
543
231k
}
544
545
static OutputSection *addInputSec(StringMap<OutputSection *> &Map,
546
239k
                                  InputSectionBase *IS, StringRef OutsecName) {
547
239k
  // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
548
239k
  // option is given. A section with SHT_GROUP defines a "section group", and
549
239k
  // its members have SHF_GROUP attribute. Usually these flags have already been
550
239k
  // stripped by InputFiles.cpp as section groups are processed and uniquified.
551
239k
  // However, for the -r option, we want to pass through all section groups
552
239k
  // as-is because adding/removing members or merging them with other groups
553
239k
  // change their semantics.
554
239k
  if (IS->Type == SHT_GROUP || 
(IS->Flags & SHF_GROUP)239k
)
555
19
    return createSection(IS, OutsecName);
556
239k
557
239k
  // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
558
239k
  // relocation sections .rela.foo and .rela.bar for example. Most tools do
559
239k
  // not allow multiple REL[A] sections for output section. Hence we
560
239k
  // should combine these relocation sections into single output.
561
239k
  // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
562
239k
  // other REL[A] sections created by linker itself.
563
239k
  if (!isa<SyntheticSection>(IS) &&
564
239k
      
(200k
IS->Type == SHT_REL200k
||
IS->Type == SHT_RELA200k
)) {
565
86
    auto *Sec = cast<InputSection>(IS);
566
86
    OutputSection *Out = Sec->getRelocatedSection()->getOutputSection();
567
86
568
86
    if (Out->RelocationSection) {
569
21
      Out->RelocationSection->addSection(Sec);
570
21
      return nullptr;
571
21
    }
572
65
573
65
    Out->RelocationSection = createSection(IS, OutsecName);
574
65
    return Out->RelocationSection;
575
65
  }
576
239k
577
239k
  // When control reaches here, mergeable sections have already been merged into
578
239k
  // synthetic sections. For relocatable case we want to create one output
579
239k
  // section per syntetic section so that they have a valid sh_entsize.
580
239k
  if (Config->Relocatable && 
(IS->Flags & SHF_MERGE)1.09k
)
581
7
    return createSection(IS, OutsecName);
582
239k
583
239k
  //  The ELF spec just says
584
239k
  // ----------------------------------------------------------------
585
239k
  // In the first phase, input sections that match in name, type and
586
239k
  // attribute flags should be concatenated into single sections.
587
239k
  // ----------------------------------------------------------------
588
239k
  //
589
239k
  // However, it is clear that at least some flags have to be ignored for
590
239k
  // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
591
239k
  // ignored. We should not have two output .text sections just because one was
592
239k
  // in a group and another was not for example.
593
239k
  //
594
239k
  // It also seems that wording was a late addition and didn't get the
595
239k
  // necessary scrutiny.
596
239k
  //
597
239k
  // Merging sections with different flags is expected by some users. One
598
239k
  // reason is that if one file has
599
239k
  //
600
239k
  // int *const bar __attribute__((section(".foo"))) = (int *)0;
601
239k
  //
602
239k
  // gcc with -fPIC will produce a read only .foo section. But if another
603
239k
  // file has
604
239k
  //
605
239k
  // int zed;
606
239k
  // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
607
239k
  //
608
239k
  // gcc with -fPIC will produce a read write section.
609
239k
  //
610
239k
  // Last but not least, when using linker script the merge rules are forced by
611
239k
  // the script. Unfortunately, linker scripts are name based. This means that
612
239k
  // expressions like *(.foo*) can refer to multiple input sections with
613
239k
  // different flags. We cannot put them in different output sections or we
614
239k
  // would produce wrong results for
615
239k
  //
616
239k
  // start = .; *(.foo.*) end = .; *(.bar)
617
239k
  //
618
239k
  // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
619
239k
  // another. The problem is that there is no way to layout those output
620
239k
  // sections such that the .foo sections are the only thing between the start
621
239k
  // and end symbols.
622
239k
  //
623
239k
  // Given the above issues, we instead merge sections by name and error on
624
239k
  // incompatible types and flags.
625
239k
  OutputSection *&Sec = Map[OutsecName];
626
239k
  if (Sec) {
627
8.05k
    Sec->addSection(cast<InputSection>(IS));
628
8.05k
    return nullptr;
629
8.05k
  }
630
231k
631
231k
  Sec = createSection(IS, OutsecName);
632
231k
  return Sec;
633
231k
}
634
635
// Add sections that didn't match any sections command.
636
2.13k
void LinkerScript::addOrphanSections() {
637
2.13k
  unsigned End = SectionCommands.size();
638
2.13k
  StringMap<OutputSection *> Map;
639
2.13k
  std::vector<OutputSection *> V;
640
2.13k
641
241k
  auto Add = [&](InputSectionBase *S) {
642
241k
    if (!S->Live || 
S->Parent240k
)
643
1.65k
      return;
644
239k
645
239k
    StringRef Name = getOutputSectionName(S);
646
239k
647
239k
    if (Config->OrphanHandling == OrphanHandlingPolicy::Error)
648
24
      error(toString(S) + " is being placed in '" + Name + "'");
649
239k
    else if (Config->OrphanHandling == OrphanHandlingPolicy::Warn)
650
24
      warn(toString(S) + " is being placed in '" + Name + "'");
651
239k
652
239k
    if (OutputSection *Sec =
653
68
            findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) {
654
68
      Sec->addSection(cast<InputSection>(S));
655
68
      return;
656
68
    }
657
239k
658
239k
    if (OutputSection *OS = addInputSec(Map, S, Name))
659
231k
      V.push_back(OS);
660
239k
    assert(S->getOutputSection()->SectionIndex == UINT32_MAX);
661
239k
  };
662
2.13k
663
2.13k
  // For futher --emit-reloc handling code we need target output section
664
2.13k
  // to be created before we create relocation output section, so we want
665
2.13k
  // to create target sections first. We do not want priority handling
666
2.13k
  // for synthetic sections because them are special.
667
241k
  for (InputSectionBase *IS : InputSections) {
668
241k
    if (auto *Sec = dyn_cast<InputSection>(IS))
669
241k
      if (InputSectionBase *Rel = Sec->getRelocatedSection())
670
90
        if (auto *RelIS = dyn_cast_or_null<InputSectionBase>(Rel->Parent))
671
3
          Add(RelIS);
672
241k
    Add(IS);
673
241k
  }
674
2.13k
675
2.13k
  // If no SECTIONS command was given, we should insert sections commands
676
2.13k
  // before others, so that we can handle scripts which refers them,
677
2.13k
  // for example: "foo = ABSOLUTE(ADDR(.text)));".
678
2.13k
  // When SECTIONS command is present we just add all orphans to the end.
679
2.13k
  if (HasSectionsCommand)
680
409
    SectionCommands.insert(SectionCommands.end(), V.begin(), V.end());
681
1.72k
  else
682
1.72k
    SectionCommands.insert(SectionCommands.begin(), V.begin(), V.end());
683
2.13k
}
684
685
892k
uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) {
686
892k
  bool IsTbss =
687
892k
      (Ctx->OutSec->Flags & SHF_TLS) && 
Ctx->OutSec->Type == SHT_NOBITS688
;
688
892k
  uint64_t Start = IsTbss ? 
Dot + Ctx->ThreadBssOffset312
:
Dot891k
;
689
892k
  Start = alignTo(Start, Alignment);
690
892k
  uint64_t End = Start + Size;
691
892k
692
892k
  if (IsTbss)
693
312
    Ctx->ThreadBssOffset = End - Dot;
694
891k
  else
695
891k
    Dot = End;
696
892k
  return End;
697
892k
}
698
699
223k
void LinkerScript::output(InputSection *S) {
700
223k
  uint64_t Before = advance(0, 1);
701
223k
  uint64_t Pos = advance(S->getSize(), S->Alignment);
702
223k
  S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr;
703
223k
704
223k
  // Update output section size after adding each section. This is so that
705
223k
  // SIZEOF works correctly in the case below:
706
223k
  // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
707
223k
  expandOutputSection(Pos - Before);
708
223k
}
709
710
222k
void LinkerScript::switchTo(OutputSection *Sec) {
711
222k
  if (Ctx->OutSec == Sec)
712
0
    return;
713
222k
  Ctx->OutSec = Sec;
714
222k
715
222k
  uint64_t Before = advance(0, 1);
716
222k
  Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment);
717
222k
  expandMemoryRegions(Ctx->OutSec->Addr - Before);
718
222k
}
719
720
// This function searches for a memory region to place the given output
721
// section in. If found, a pointer to the appropriate memory region is
722
// returned. Otherwise, a nullptr is returned.
723
133k
MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
724
133k
  // If a memory region name was specified in the output section command,
725
133k
  // then try to find that region first.
726
133k
  if (!Sec->MemoryRegionName.empty()) {
727
33
    if (MemoryRegion *M = MemoryRegions.lookup(Sec->MemoryRegionName))
728
32
      return M;
729
1
    error("memory region '" + Sec->MemoryRegionName + "' not declared");
730
1
    return nullptr;
731
1
  }
732
133k
733
133k
  // If at least one memory region is defined, all sections must
734
133k
  // belong to some memory region. Otherwise, we don't need to do
735
133k
  // anything for memory regions.
736
133k
  if (MemoryRegions.empty())
737
133k
    return nullptr;
738
87
739
87
  // See if a region can be found by matching section flags.
740
168
  
for (auto &Pair : MemoryRegions)87
{
741
168
    MemoryRegion *M = Pair.second;
742
168
    if ((M->Flags & Sec->Flags) && 
(M->NegFlags & Sec->Flags) == 010
)
743
10
      return M;
744
168
  }
745
87
746
87
  // Otherwise, no suitable region was found.
747
87
  
if (77
Sec->Flags & SHF_ALLOC77
)
748
1
    error("no memory region specified for section '" + Sec->Name + "'");
749
77
  return nullptr;
750
87
}
751
752
// This function assigns offsets to input sections and an output section
753
// for a single sections command (e.g. ".text { *(.text); }").
754
220k
void LinkerScript::assignOffsets(OutputSection *Sec) {
755
220k
  if (!(Sec->Flags & SHF_ALLOC))
756
140k
    Dot = 0;
757
79.1k
  else if (Sec->AddrExpr)
758
4.09k
    setDot(Sec->AddrExpr, Sec->Location, false);
759
220k
760
220k
  Ctx->MemRegion = Sec->MemRegion;
761
220k
  Ctx->LMARegion = Sec->LMARegion;
762
220k
  if (Ctx->MemRegion)
763
41
    Dot = Ctx->MemRegion->CurPos;
764
220k
765
220k
  switchTo(Sec);
766
220k
767
220k
  if (Sec->LMAExpr)
768
34
    Ctx->LMAOffset = Sec->LMAExpr().getValue() - Dot;
769
220k
770
220k
  if (MemoryRegion *MR = Sec->LMARegion)
771
10
    Ctx->LMAOffset = MR->CurPos - Dot;
772
220k
773
220k
  // If neither AT nor AT> is specified for an allocatable section, the linker
774
220k
  // will set the LMA such that the difference between VMA and LMA for the
775
220k
  // section is the same as the preceding output section in the same region
776
220k
  // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
777
220k
  if (PhdrEntry *L = Ctx->OutSec->PtLoad)
778
78.7k
    L->LMAOffset = Ctx->LMAOffset;
779
220k
780
220k
  // We can call this method multiple times during the creation of
781
220k
  // thunks and want to start over calculation each time.
782
220k
  Sec->Size = 0;
783
220k
784
220k
  // We visited SectionsCommands from processSectionCommands to
785
220k
  // layout sections. Now, we visit SectionsCommands again to fix
786
220k
  // section offsets.
787
220k
  for (BaseCommand *Base : Sec->SectionCommands) {
788
220k
    // This handles the assignments to symbol or to the dot.
789
220k
    if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
790
128
      Cmd->Addr = Dot;
791
128
      assignSymbol(Cmd, true);
792
128
      Cmd->Size = Dot - Cmd->Addr;
793
128
      continue;
794
128
    }
795
220k
796
220k
    // Handle BYTE(), SHORT(), LONG(), or QUAD().
797
220k
    if (auto *Cmd = dyn_cast<ByteCommand>(Base)) {
798
48
      Cmd->Offset = Dot - Ctx->OutSec->Addr;
799
48
      Dot += Cmd->Size;
800
48
      expandOutputSection(Cmd->Size);
801
48
      continue;
802
48
    }
803
220k
804
220k
    // Handle a single input section description command.
805
220k
    // It calculates and assigns the offsets for each section and also
806
220k
    // updates the output section size.
807
220k
    auto *Cmd = cast<InputSectionDescription>(Base);
808
223k
    for (InputSection *Sec : Cmd->Sections) {
809
223k
      // We tentatively added all synthetic sections at the beginning and
810
223k
      // removed empty ones afterwards (because there is no way to know
811
223k
      // whether they were going be empty or not other than actually running
812
223k
      // linker scripts.) We need to ignore remains of empty sections.
813
223k
      if (auto *S = dyn_cast<SyntheticSection>(Sec))
814
19.6k
        if (S->empty())
815
0
          continue;
816
223k
817
223k
      if (!Sec->Live)
818
0
        continue;
819
223k
      assert(Ctx->OutSec == Sec->getParent());
820
223k
      output(Sec);
821
223k
    }
822
220k
  }
823
220k
}
824
825
15.8k
static bool isDiscardable(OutputSection &Sec) {
826
15.8k
  // We do not remove empty sections that are explicitly
827
15.8k
  // assigned to any segment.
828
15.8k
  if (!Sec.Phdrs.empty())
829
7
    return false;
830
15.8k
831
15.8k
  // We do not want to remove sections that reference symbols in address and
832
15.8k
  // other expressions. We add script symbols as undefined, and want to ensure
833
15.8k
  // all of them are defined in the output, hence have to keep them.
834
15.8k
  if (Sec.ExpressionsUseSymbols)
835
4
    return false;
836
15.8k
837
15.8k
  for (BaseCommand *Base : Sec.SectionCommands)
838
15.8k
    if (!isa<InputSectionDescription>(*Base))
839
15
      return false;
840
15.8k
  
return true15.8k
;
841
15.8k
}
842
843
2.03k
void LinkerScript::adjustSectionsBeforeSorting() {
844
2.03k
  // If the output section contains only symbol assignments, create a
845
2.03k
  // corresponding output section. The issue is what to do with linker script
846
2.03k
  // like ".foo : { symbol = 42; }". One option would be to convert it to
847
2.03k
  // "symbol = 42;". That is, move the symbol out of the empty section
848
2.03k
  // description. That seems to be what bfd does for this simple case. The
849
2.03k
  // problem is that this is not completely general. bfd will give up and
850
2.03k
  // create a dummy section too if there is a ". = . + 1" inside the section
851
2.03k
  // for example.
852
2.03k
  // Given that we want to create the section, we have to worry what impact
853
2.03k
  // it will have on the link. For example, if we just create a section with
854
2.03k
  // 0 for flags, it would change which PT_LOADs are created.
855
2.03k
  // We could remember that particular section is dummy and ignore it in
856
2.03k
  // other parts of the linker, but unfortunately there are quite a few places
857
2.03k
  // that would need to change:
858
2.03k
  //   * The program header creation.
859
2.03k
  //   * The orphan section placement.
860
2.03k
  //   * The address assignment.
861
2.03k
  // The other option is to pick flags that minimize the impact the section
862
2.03k
  // will have on the rest of the linker. That is why we copy the flags from
863
2.03k
  // the previous sections. Only a few flags are needed to keep the impact low.
864
2.03k
  uint64_t Flags = SHF_ALLOC;
865
2.03k
866
230k
  for (BaseCommand *&Cmd : SectionCommands) {
867
230k
    auto *Sec = dyn_cast<OutputSection>(Cmd);
868
230k
    if (!Sec)
869
332
      continue;
870
230k
871
230k
    // Handle align (e.g. ".foo : ALIGN(16) { ... }").
872
230k
    if (Sec->AlignExpr)
873
15
      Sec->Alignment =
874
15
          std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
875
230k
876
230k
    // A live output section means that some input section was added to it. It
877
230k
    // might have been removed (if it was empty synthetic section), but we at
878
230k
    // least know the flags.
879
230k
    if (Sec->Live)
880
230k
      Flags = Sec->Flags;
881
230k
882
230k
    // We do not want to keep any special flags for output section
883
230k
    // in case it is empty.
884
230k
    bool IsEmpty = getInputSections(Sec).empty();
885
230k
    if (IsEmpty)
886
15.8k
      Sec->Flags = Flags & (SHF_ALLOC | SHF_WRITE | SHF_EXECINSTR);
887
230k
888
230k
    if (IsEmpty && 
isDiscardable(*Sec)15.8k
) {
889
15.8k
      Sec->Live = false;
890
15.8k
      Cmd = nullptr;
891
15.8k
    }
892
230k
  }
893
2.03k
894
2.03k
  // It is common practice to use very generic linker scripts. So for any
895
2.03k
  // given run some of the output sections in the script will be empty.
896
2.03k
  // We could create corresponding empty output sections, but that would
897
2.03k
  // clutter the output.
898
2.03k
  // We instead remove trivially empty sections. The bfd linker seems even
899
2.03k
  // more aggressive at removing them.
900
230k
  llvm::erase_if(SectionCommands, [&](BaseCommand *Base) { return !Base; });
901
2.03k
}
902
903
394
void LinkerScript::adjustSectionsAfterSorting() {
904
394
  // Try and find an appropriate memory region to assign offsets in.
905
133k
  for (BaseCommand *Base : SectionCommands) {
906
133k
    if (auto *Sec = dyn_cast<OutputSection>(Base)) {
907
133k
      if (!Sec->LMARegionName.empty()) {
908
10
        if (MemoryRegion *M = MemoryRegions.lookup(Sec->LMARegionName))
909
10
          Sec->LMARegion = M;
910
0
        else
911
0
          error("memory region '" + Sec->LMARegionName + "' not declared");
912
10
      }
913
133k
      Sec->MemRegion = findMemoryRegion(Sec);
914
133k
    }
915
133k
  }
916
394
917
394
  // If output section command doesn't specify any segments,
918
394
  // and we haven't previously assigned any section to segment,
919
394
  // then we simply assign section to the very first load segment.
920
394
  // Below is an example of such linker script:
921
394
  // PHDRS { seg PT_LOAD; }
922
394
  // SECTIONS { .aaa : { *(.aaa) } }
923
394
  std::vector<StringRef> DefPhdrs;
924
394
  auto FirstPtLoad = llvm::find_if(PhdrsCommands, [](const PhdrsCommand &Cmd) {
925
25
    return Cmd.Type == PT_LOAD;
926
25
  });
927
394
  if (FirstPtLoad != PhdrsCommands.end())
928
23
    DefPhdrs.push_back(FirstPtLoad->Name);
929
394
930
394
  // Walk the commands and propagate the program headers to commands that don't
931
394
  // explicitly specify them.
932
133k
  for (BaseCommand *Base : SectionCommands) {
933
133k
    auto *Sec = dyn_cast<OutputSection>(Base);
934
133k
    if (!Sec)
935
292
      continue;
936
133k
937
133k
    if (Sec->Phdrs.empty()) {
938
133k
      // To match the bfd linker script behaviour, only propagate program
939
133k
      // headers to sections that are allocated.
940
133k
      if (Sec->Flags & SHF_ALLOC)
941
66.7k
        Sec->Phdrs = DefPhdrs;
942
133k
    } else {
943
38
      DefPhdrs = Sec->Phdrs;
944
38
    }
945
133k
  }
946
394
}
947
948
325
static OutputSection *findFirstSection(PhdrEntry *Load) {
949
325
  for (OutputSection *Sec : OutputSections)
950
502
    if (Sec->PtLoad == Load)
951
295
      return Sec;
952
325
  
return nullptr30
;
953
325
}
954
955
1.94k
static uint64_t computeBase(uint64_t Min, bool AllocateHeaders) {
956
1.94k
  // If there is no SECTIONS or if the linkerscript is explicit about program
957
1.94k
  // headers, do our best to allocate them.
958
1.94k
  if (!Script->HasSectionsCommand || 
AllocateHeaders384
)
959
1.57k
    return 0;
960
371
  // Otherwise only allocate program headers if that would not add a page.
961
371
  return alignDown(Min, Config->MaxPageSize);
962
371
}
963
964
// Try to find an address for the file and program headers output sections,
965
// which were unconditionally added to the first PT_LOAD segment earlier.
966
//
967
// When using the default layout, we check if the headers fit below the first
968
// allocated section. When using a linker script, we also check if the headers
969
// are covered by the output section. This allows omitting the headers by not
970
// leaving enough space for them in the linker script; this pattern is common
971
// in embedded systems.
972
//
973
// If there isn't enough space for these sections, we'll remove them from the
974
// PT_LOAD segment, and we'll also remove the PT_PHDR segment.
975
2.02k
void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
976
2.02k
  uint64_t Min = std::numeric_limits<uint64_t>::max();
977
2.02k
  for (OutputSection *Sec : OutputSections)
978
214k
    if (Sec->Flags & SHF_ALLOC)
979
75.6k
      Min = std::min<uint64_t>(Min, Sec->Addr);
980
2.02k
981
2.02k
  auto It = llvm::find_if(
982
3.88k
      Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
983
2.02k
  if (It == Phdrs.end())
984
78
    return;
985
1.94k
  PhdrEntry *FirstPTLoad = *It;
986
1.94k
987
1.94k
  bool HasExplicitHeaders =
988
1.94k
      llvm::any_of(PhdrsCommands, [](const PhdrsCommand &Cmd) {
989
29
        return Cmd.HasPhdrs || 
Cmd.HasFilehdr15
;
990
29
      });
991
1.94k
  uint64_t HeaderSize = getHeaderSize();
992
1.94k
  if (HeaderSize <= Min - computeBase(Min, HasExplicitHeaders)) {
993
1.62k
    Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
994
1.62k
    Out::ElfHeader->Addr = Min;
995
1.62k
    Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
996
1.62k
    return;
997
1.62k
  }
998
325
999
325
  // Error if we were explicitly asked to allocate headers.
1000
325
  if (HasExplicitHeaders)
1001
1
    error("could not allocate headers");
1002
325
1003
325
  Out::ElfHeader->PtLoad = nullptr;
1004
325
  Out::ProgramHeaders->PtLoad = nullptr;
1005
325
  FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
1006
325
1007
325
  llvm::erase_if(Phdrs,
1008
1.33k
                 [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
1009
325
}
1010
1011
4.67k
LinkerScript::AddressState::AddressState() {
1012
4.67k
  for (auto &MRI : Script->MemoryRegions) {
1013
77
    MemoryRegion *MR = MRI.second;
1014
77
    MR->CurPos = MR->Origin;
1015
77
  }
1016
4.67k
}
1017
1018
2.54k
static uint64_t getInitialDot() {
1019
2.54k
  // By default linker scripts use an initial value of 0 for '.',
1020
2.54k
  // but prefer -image-base if set.
1021
2.54k
  if (Script->HasSectionsCommand)
1022
459
    return Config->ImageBase ? 
*Config->ImageBase1
:
0458
;
1023
2.08k
1024
2.08k
  uint64_t StartAddr = UINT64_MAX;
1025
2.08k
  // The Sections with -T<section> have been sorted in order of ascending
1026
2.08k
  // address. We must lower StartAddr if the lowest -T<section address> as
1027
2.08k
  // calls to setDot() must be monotonically increasing.
1028
2.08k
  for (auto &KV : Config->SectionStartMap)
1029
50
    StartAddr = std::min(StartAddr, KV.second);
1030
2.08k
  return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize());
1031
2.08k
}
1032
1033
// Here we assign addresses as instructed by linker script SECTIONS
1034
// sub-commands. Doing that allows us to use final VA values, so here
1035
// we also handle rest commands like symbol assignments and ASSERTs.
1036
2.54k
void LinkerScript::assignAddresses() {
1037
2.54k
  Dot = getInitialDot();
1038
2.54k
1039
2.54k
  auto Deleter = make_unique<AddressState>();
1040
2.54k
  Ctx = Deleter.get();
1041
2.54k
  ErrorOnMissingSection = true;
1042
2.54k
  switchTo(Aether);
1043
2.54k
1044
220k
  for (BaseCommand *Base : SectionCommands) {
1045
220k
    if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
1046
356
      Cmd->Addr = Dot;
1047
356
      assignSymbol(Cmd, false);
1048
356
      Cmd->Size = Dot - Cmd->Addr;
1049
356
      continue;
1050
356
    }
1051
220k
    assignOffsets(cast<OutputSection>(Base));
1052
220k
  }
1053
2.54k
  Ctx = nullptr;
1054
2.54k
}
1055
1056
// Creates program headers as instructed by PHDRS linker script command.
1057
27
std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
1058
27
  std::vector<PhdrEntry *> Ret;
1059
27
1060
27
  // Process PHDRS and FILEHDR keywords because they are not
1061
27
  // real output sections and cannot be added in the following loop.
1062
37
  for (const PhdrsCommand &Cmd : PhdrsCommands) {
1063
37
    PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? 
*Cmd.Flags9
:
PF_R28
);
1064
37
1065
37
    if (Cmd.HasFilehdr)
1066
12
      Phdr->add(Out::ElfHeader);
1067
37
    if (Cmd.HasPhdrs)
1068
15
      Phdr->add(Out::ProgramHeaders);
1069
37
1070
37
    if (Cmd.LMAExpr) {
1071
1
      Phdr->p_paddr = Cmd.LMAExpr().getValue();
1072
1
      Phdr->HasLMA = true;
1073
1
    }
1074
37
    Ret.push_back(Phdr);
1075
37
  }
1076
27
1077
27
  // Add output sections to program headers.
1078
189
  for (OutputSection *Sec : OutputSections) {
1079
189
    // Assign headers specified by linker script
1080
189
    for (size_t Id : getPhdrIndices(Sec)) {
1081
72
      Ret[Id]->add(Sec);
1082
72
      if (!PhdrsCommands[Id].Flags.hasValue())
1083
50
        Ret[Id]->p_flags |= Sec->getPhdrFlags();
1084
72
    }
1085
189
  }
1086
27
  return Ret;
1087
27
}
1088
1089
// Returns true if we should emit an .interp section.
1090
//
1091
// We usually do. But if PHDRS commands are given, and
1092
// no PT_INTERP is there, there's no place to emit an
1093
// .interp, so we don't do that in that case.
1094
18
bool LinkerScript::needsInterpSection() {
1095
18
  if (PhdrsCommands.empty())
1096
16
    return true;
1097
2
  for (PhdrsCommand &Cmd : PhdrsCommands)
1098
2
    if (Cmd.Type == PT_INTERP)
1099
0
      return true;
1100
2
  return false;
1101
2
}
1102
1103
366
ExprValue LinkerScript::getSymbolValue(StringRef Name, const Twine &Loc) {
1104
366
  if (Name == ".") {
1105
241
    if (Ctx)
1106
240
      return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc};
1107
1
    error(Loc + ": unable to get location counter value");
1108
1
    return 0;
1109
1
  }
1110
125
1111
125
  if (Symbol *Sym = Symtab->find(Name)) {
1112
125
    if (auto *DS = dyn_cast<Defined>(Sym))
1113
114
      return {DS->Section, false, DS->Value, Loc};
1114
11
    if (isa<SharedSymbol>(Sym))
1115
3
      if (!ErrorOnMissingSection)
1116
2
        return {nullptr, false, 0, Loc};
1117
9
  }
1118
9
1119
9
  error(Loc + ": symbol not found: " + Name);
1120
9
  return 0;
1121
9
}
1122
1123
// Returns the index of the segment named Name.
1124
static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec,
1125
74
                                     StringRef Name) {
1126
92
  for (size_t I = 0; I < Vec.size(); 
++I18
)
1127
90
    if (Vec[I].Name == Name)
1128
72
      return I;
1129
74
  
return None2
;
1130
74
}
1131
1132
// Returns indices of ELF headers containing specific section. Each index is a
1133
// zero based number of ELF header listed within PHDRS {} script block.
1134
189
std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
1135
189
  std::vector<size_t> Ret;
1136
189
1137
189
  for (StringRef S : Cmd->Phdrs) {
1138
74
    if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S))
1139
72
      Ret.push_back(*Idx);
1140
2
    else if (S != "NONE")
1141
1
      error(Cmd->Location + ": section header '" + S +
1142
1
            "' is not listed in PHDRS");
1143
74
  }
1144
189
  return Ret;
1145
189
}