Coverage Report

Created: 2018-08-19 14:04

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