Coverage Report

Created: 2018-01-17 21:32

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