Coverage Report

Created: 2019-01-18 03:29

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