Coverage Report

Created: 2019-07-24 05:18

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