Coverage Report

Created: 2018-08-19 21:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Driver.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
// The driver drives the entire linking process. It is responsible for
11
// parsing command line options and doing whatever it is instructed to do.
12
//
13
// One notable thing in the LLD's driver when compared to other linkers is
14
// that the LLD's driver is agnostic on the host operating system.
15
// Other linkers usually have implicit default values (such as a dynamic
16
// linker path or library paths) for each host OS.
17
//
18
// I don't think implicit default values are useful because they are
19
// usually explicitly specified by the compiler driver. They can even
20
// be harmful when you are doing cross-linking. Therefore, in LLD, we
21
// simply trust the compiler driver to pass all required options and
22
// don't try to make effort on our side.
23
//
24
//===----------------------------------------------------------------------===//
25
26
#include "Driver.h"
27
#include "Config.h"
28
#include "Filesystem.h"
29
#include "ICF.h"
30
#include "InputFiles.h"
31
#include "InputSection.h"
32
#include "LinkerScript.h"
33
#include "MarkLive.h"
34
#include "OutputSections.h"
35
#include "ScriptParser.h"
36
#include "SymbolTable.h"
37
#include "Symbols.h"
38
#include "SyntheticSections.h"
39
#include "Target.h"
40
#include "Writer.h"
41
#include "lld/Common/Args.h"
42
#include "lld/Common/Driver.h"
43
#include "lld/Common/ErrorHandler.h"
44
#include "lld/Common/Memory.h"
45
#include "lld/Common/Strings.h"
46
#include "lld/Common/TargetOptionsCommandFlags.h"
47
#include "lld/Common/Threads.h"
48
#include "lld/Common/Version.h"
49
#include "llvm/ADT/SetVector.h"
50
#include "llvm/ADT/StringExtras.h"
51
#include "llvm/ADT/StringSwitch.h"
52
#include "llvm/Support/CommandLine.h"
53
#include "llvm/Support/Compression.h"
54
#include "llvm/Support/LEB128.h"
55
#include "llvm/Support/Path.h"
56
#include "llvm/Support/TarWriter.h"
57
#include "llvm/Support/TargetSelect.h"
58
#include "llvm/Support/raw_ostream.h"
59
#include <cstdlib>
60
#include <utility>
61
62
using namespace llvm;
63
using namespace llvm::ELF;
64
using namespace llvm::object;
65
using namespace llvm::sys;
66
67
using namespace lld;
68
using namespace lld::elf;
69
70
Configuration *elf::Config;
71
LinkerDriver *elf::Driver;
72
73
static void setConfigs(opt::InputArgList &Args);
74
75
bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
76
2.48k
               raw_ostream &Error) {
77
2.48k
  errorHandler().LogName = sys::path::filename(Args[0]);
78
2.48k
  errorHandler().ErrorLimitExceededMsg =
79
2.48k
      "too many errors emitted, stopping now (use "
80
2.48k
      "-error-limit=0 to see all errors)";
81
2.48k
  errorHandler().ErrorOS = &Error;
82
2.48k
  errorHandler().ExitEarly = CanExitEarly;
83
2.48k
  errorHandler().ColorDiagnostics = Error.has_colors();
84
2.48k
85
2.48k
  InputSections.clear();
86
2.48k
  OutputSections.clear();
87
2.48k
  Tar = nullptr;
88
2.48k
  BinaryFiles.clear();
89
2.48k
  BitcodeFiles.clear();
90
2.48k
  ObjectFiles.clear();
91
2.48k
  SharedFiles.clear();
92
2.48k
93
2.48k
  Config = make<Configuration>();
94
2.48k
  Driver = make<LinkerDriver>();
95
2.48k
  Script = make<LinkerScript>();
96
2.48k
  Symtab = make<SymbolTable>();
97
2.48k
  Config->ProgName = Args[0];
98
2.48k
99
2.48k
  Driver->main(Args);
100
2.48k
101
2.48k
  // Exit immediately if we don't need to return to the caller.
102
2.48k
  // This saves time because the overhead of calling destructors
103
2.48k
  // for all globally-allocated objects is not negligible.
104
2.48k
  if (CanExitEarly)
105
0
    exitLld(errorCount() ? 1 : 0);
106
2.48k
107
2.48k
  freeArena();
108
2.48k
  return !errorCount();
109
2.48k
}
110
111
// Parses a linker -m option.
112
33
static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
113
33
  uint8_t OSABI = 0;
114
33
  StringRef S = Emul;
115
33
  if (S.endswith("_fbsd")) {
116
4
    S = S.drop_back(5);
117
4
    OSABI = ELFOSABI_FREEBSD;
118
4
  }
119
33
120
33
  std::pair<ELFKind, uint16_t> Ret =
121
33
      StringSwitch<std::pair<ELFKind, uint16_t>>(S)
122
33
          .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
123
33
                 {ELF64LEKind, EM_AARCH64})
124
33
          .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
125
33
          .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
126
33
          .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
127
33
          .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
128
33
          .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
129
33
          .Case("elf32ppc", {ELF32BEKind, EM_PPC})
130
33
          .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
131
33
          .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
132
33
          .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
133
33
          .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
134
33
          .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
135
33
          .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
136
33
          .Case("elf_i386", {ELF32LEKind, EM_386})
137
33
          .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
138
33
          .Default({ELFNoneKind, EM_NONE});
139
33
140
33
  if (Ret.first == ELFNoneKind)
141
2
    error("unknown emulation: " + Emul);
142
33
  return std::make_tuple(Ret.first, Ret.second, OSABI);
143
33
}
144
145
// Returns slices of MB by parsing MB as an archive file.
146
// Each slice consists of a member file in the archive.
147
std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
148
23
    MemoryBufferRef MB) {
149
23
  std::unique_ptr<Archive> File =
150
23
      CHECK(Archive::create(MB),
151
23
            MB.getBufferIdentifier() + ": failed to parse archive");
152
23
153
23
  std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
154
23
  Error Err = Error::success();
155
23
  bool AddToTar = File->isThin() && 
Tar2
;
156
27
  for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
157
27
    Archive::Child C =
158
27
        CHECK(COrErr, MB.getBufferIdentifier() +
159
27
                          ": could not get the child of the archive");
160
27
    MemoryBufferRef MBRef =
161
27
        CHECK(C.getMemoryBufferRef(),
162
27
              MB.getBufferIdentifier() +
163
27
                  ": could not get the buffer for a child of the archive");
164
27
    if (AddToTar)
165
1
      Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
166
27
    V.push_back(std::make_pair(MBRef, C.getChildOffset()));
167
27
  }
168
23
  if (Err)
169
0
    fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
170
0
          toString(std::move(Err)));
171
23
172
23
  // Take ownership of memory buffers created for members of thin archives.
173
23
  for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
174
2
    make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
175
23
176
23
  return V;
177
23
}
178
179
// Opens a file and create a file object. Path has to be resolved already.
180
3.50k
void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
181
3.50k
  using namespace sys::fs;
182
3.50k
183
3.50k
  Optional<MemoryBufferRef> Buffer = readFile(Path);
184
3.50k
  if (!Buffer.hasValue())
185
88
    return;
186
3.41k
  MemoryBufferRef MBRef = *Buffer;
187
3.41k
188
3.41k
  if (Config->FormatBinary) {
189
6
    Files.push_back(make<BinaryFile>(MBRef));
190
6
    return;
191
6
  }
192
3.40k
193
3.40k
  switch (identify_magic(MBRef.getBuffer())) {
194
3.40k
  case file_magic::unknown:
195
68
    readLinkerScript(MBRef);
196
68
    return;
197
3.40k
  case file_magic::archive: {
198
125
    // Handle -whole-archive.
199
125
    if (InWholeArchive) {
200
19
      for (const auto &P : getArchiveMembers(MBRef))
201
22
        Files.push_back(createObjectFile(P.first, Path, P.second));
202
19
      return;
203
19
    }
204
106
205
106
    std::unique_ptr<Archive> File =
206
106
        CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
207
106
208
106
    // If an archive file has no symbol table, it is likely that a user
209
106
    // is attempting LTO and using a default ar command that doesn't
210
106
    // understand the LLVM bitcode file. It is a pretty common error, so
211
106
    // we'll handle it as if it had a symbol table.
212
106
    if (!File->isEmpty() && 
!File->hasSymbolTable()104
) {
213
4
      for (const auto &P : getArchiveMembers(MBRef))
214
5
        Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
215
4
      return;
216
4
    }
217
102
218
102
    // Handle the regular case.
219
102
    Files.push_back(make<ArchiveFile>(std::move(File)));
220
102
    return;
221
102
  }
222
341
  case file_magic::elf_shared_object:
223
341
    if (Config->Relocatable) {
224
1
      error("attempted static link of dynamic object " + Path);
225
1
      return;
226
1
    }
227
340
228
340
    // DSOs usually have DT_SONAME tags in their ELF headers, and the
229
340
    // sonames are used to identify DSOs. But if they are missing,
230
340
    // they are identified by filenames. We don't know whether the new
231
340
    // file has a DT_SONAME or not because we haven't parsed it yet.
232
340
    // Here, we set the default soname for the file because we might
233
340
    // need it later.
234
340
    //
235
340
    // If a file was specified by -lfoo, the directory part is not
236
340
    // significant, as a user did not specify it. This behavior is
237
340
    // compatible with GNU.
238
340
    Files.push_back(
239
340
        createSharedFile(MBRef, WithLOption ? 
path::filename(Path)13
:
Path327
));
240
340
    return;
241
2.87k
  case file_magic::bitcode:
242
2.87k
  case file_magic::elf_relocatable:
243
2.87k
    if (InLib)
244
24
      Files.push_back(make<LazyObjFile>(MBRef, "", 0));
245
2.84k
    else
246
2.84k
      Files.push_back(createObjectFile(MBRef));
247
2.87k
    break;
248
2.87k
  default:
249
1
    error(Path + ": unknown file type");
250
3.40k
  }
251
3.40k
}
252
253
// Add a given library by searching it from input search paths.
254
36
void LinkerDriver::addLibrary(StringRef Name) {
255
36
  if (Optional<std::string> Path = searchLibrary(Name))
256
27
    addFile(*Path, /*WithLOption=*/true);
257
9
  else
258
9
    error("unable to find library -l" + Name);
259
36
}
260
261
// This function is called on startup. We need this for LTO since
262
// LTO calls LLVM functions to compile bitcode files to native code.
263
// Technically this can be delayed until we read bitcode files, but
264
// we don't bother to do lazily because the initialization is fast.
265
2.47k
static void initLLVM() {
266
2.47k
  InitializeAllTargets();
267
2.47k
  InitializeAllTargetMCs();
268
2.47k
  InitializeAllAsmPrinters();
269
2.47k
  InitializeAllAsmParsers();
270
2.47k
}
271
272
// Some command line options or some combinations of them are not allowed.
273
// This function checks for such errors.
274
2.33k
static void checkOptions(opt::InputArgList &Args) {
275
2.33k
  // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
276
2.33k
  // table which is a relatively new feature.
277
2.33k
  if (Config->EMachine == EM_MIPS && 
Config->GnuHash183
)
278
2
    error("the .gnu.hash section is not compatible with the MIPS target.");
279
2.33k
280
2.33k
  if (Config->FixCortexA53Errata843419 && 
Config->EMachine != EM_AARCH646
)
281
1
    error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
282
2.33k
283
2.33k
  if (Config->Pie && 
Config->Shared55
)
284
1
    error("-shared and -pie may not be used together");
285
2.33k
286
2.33k
  if (!Config->Shared && 
!Config->FilterList.empty()1.48k
)
287
1
    error("-F may not be used without -shared");
288
2.33k
289
2.33k
  if (!Config->Shared && 
!Config->AuxiliaryList.empty()1.48k
)
290
1
    error("-f may not be used without -shared");
291
2.33k
292
2.33k
  if (!Config->Relocatable && 
!Config->DefineCommon2.25k
)
293
1
    error("-no-define-common not supported in non relocatable output");
294
2.33k
295
2.33k
  if (Config->Relocatable) {
296
77
    if (Config->Shared)
297
1
      error("-r and -shared may not be used together");
298
77
    if (Config->GcSections)
299
1
      error("-r and --gc-sections may not be used together");
300
77
    if (Config->GdbIndex)
301
1
      error("-r and --gdb-index may not be used together");
302
77
    if (Config->ICF != ICFLevel::None)
303
1
      error("-r and --icf may not be used together");
304
77
    if (Config->Pie)
305
1
      error("-r and -pie may not be used together");
306
77
  }
307
2.33k
308
2.33k
  if (Config->ExecuteOnly) {
309
3
    if (Config->EMachine != EM_AARCH64)
310
0
      error("-execute-only is only supported on AArch64 targets");
311
3
312
3
    if (Config->SingleRoRx && 
!Script->HasSectionsCommand2
)
313
0
      error("-execute-only and -no-rosegment cannot be used together");
314
3
  }
315
2.33k
}
316
317
2.47k
static const char *getReproduceOption(opt::InputArgList &Args) {
318
2.47k
  if (auto *Arg = Args.getLastArg(OPT_reproduce))
319
9
    return Arg->getValue();
320
2.46k
  return getenv("LLD_REPRODUCE");
321
2.46k
}
322
323
22.2k
static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
324
22.2k
  for (auto *Arg : Args.filtered(OPT_z))
325
720
    if (Key == Arg->getValue())
326
26
      return true;
327
22.2k
  
return false22.2k
;
328
22.2k
}
329
330
static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2,
331
17.3k
                     bool Default) {
332
17.3k
  for (auto *Arg : Args.filtered_reverse(OPT_z)) {
333
561
    if (K1 == Arg->getValue())
334
13
      return true;
335
548
    if (K2 == Arg->getValue())
336
24
      return false;
337
548
  }
338
17.3k
  
return Default17.3k
;
339
17.3k
}
340
341
81
static bool isKnown(StringRef S) {
342
81
  return S == "combreloc" || 
S == "copyreloc"80
||
S == "defs"80
||
343
81
         
S == "execstack"77
||
S == "hazardplt"76
||
S == "initfirst"70
||
344
81
         
S == "keep-text-section-prefix"69
||
S == "lazy"68
||
S == "muldefs"67
||
345
81
         
S == "nocombreloc"65
||
S == "nocopyreloc"64
||
S == "nodelete"62
||
346
81
         
S == "nodlopen"61
||
S == "noexecstack"60
||
347
81
         
S == "nokeep-text-section-prefix"59
||
S == "norelro"58
||
S == "notext"53
||
348
81
         
S == "now"38
||
S == "origin"34
||
S == "relro"33
||
S == "retpolineplt"28
||
349
81
         
S == "rodynamic"19
||
S == "text"16
||
S == "wxneeded"15
||
350
81
         
S.startswith("max-page-size=")13
||
S.startswith("stack-size=")4
;
351
81
}
352
353
// Report an error for an unknown -z option.
354
2.47k
static void checkZOptions(opt::InputArgList &Args) {
355
2.47k
  for (auto *Arg : Args.filtered(OPT_z))
356
81
    if (!isKnown(Arg->getValue()))
357
2
      error("unknown -z value: " + StringRef(Arg->getValue()));
358
2.47k
}
359
360
2.48k
void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
361
2.48k
  ELFOptTable Parser;
362
2.48k
  opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
363
2.48k
364
2.48k
  // Interpret this flag early because error() depends on them.
365
2.48k
  errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
366
2.48k
367
2.48k
  // Handle -help
368
2.48k
  if (Args.hasArg(OPT_help)) {
369
2
    printHelp();
370
2
    return;
371
2
  }
372
2.48k
373
2.48k
  // Handle -v or -version.
374
2.48k
  //
375
2.48k
  // A note about "compatible with GNU linkers" message: this is a hack for
376
2.48k
  // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
377
2.48k
  // still the newest version in March 2017) or earlier to recognize LLD as
378
2.48k
  // a GNU compatible linker. As long as an output for the -v option
379
2.48k
  // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
380
2.48k
  //
381
2.48k
  // This is somewhat ugly hack, but in reality, we had no choice other
382
2.48k
  // than doing this. Considering the very long release cycle of Libtool,
383
2.48k
  // it is not easy to improve it to recognize LLD as a GNU compatible
384
2.48k
  // linker in a timely manner. Even if we can make it, there are still a
385
2.48k
  // lot of "configure" scripts out there that are generated by old version
386
2.48k
  // of Libtool. We cannot convince every software developer to migrate to
387
2.48k
  // the latest version and re-generate scripts. So we have this hack.
388
2.48k
  if (Args.hasArg(OPT_v) || 
Args.hasArg(OPT_version)2.47k
)
389
6
    message(getLLDVersion() + " (compatible with GNU linkers)");
390
2.48k
391
2.48k
  // The behavior of -v or --version is a bit strange, but this is
392
2.48k
  // needed for compatibility with GNU linkers.
393
2.48k
  if (Args.hasArg(OPT_v) && 
!Args.hasArg(OPT_INPUT)3
)
394
1
    return;
395
2.48k
  if (Args.hasArg(OPT_version))
396
3
    return;
397
2.47k
398
2.47k
  if (const char *Path = getReproduceOption(Args)) {
399
10
    // Note that --reproduce is a debug option so you can ignore it
400
10
    // if you are trying to understand the whole picture of the code.
401
10
    Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
402
10
        TarWriter::create(Path, path::stem(Path));
403
10
    if (ErrOrWriter) {
404
10
      Tar = ErrOrWriter->get();
405
10
      Tar->append("response.txt", createResponseFile(Args));
406
10
      Tar->append("version.txt", getLLDVersion() + "\n");
407
10
      make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
408
10
    } else {
409
0
      error(Twine("--reproduce: failed to open ") + Path + ": " +
410
0
            toString(ErrOrWriter.takeError()));
411
0
    }
412
10
  }
413
2.47k
414
2.47k
  readConfigs(Args);
415
2.47k
  checkZOptions(Args);
416
2.47k
  initLLVM();
417
2.47k
  createFiles(Args);
418
2.47k
  if (errorCount())
419
141
    return;
420
2.33k
421
2.33k
  inferMachineType();
422
2.33k
  setConfigs(Args);
423
2.33k
  checkOptions(Args);
424
2.33k
  if (errorCount())
425
13
    return;
426
2.32k
427
2.32k
  switch (Config->EKind) {
428
2.32k
  case ELF32LEKind:
429
285
    link<ELF32LE>(Args);
430
285
    return;
431
2.32k
  case ELF32BEKind:
432
120
    link<ELF32BE>(Args);
433
120
    return;
434
2.32k
  case ELF64LEKind:
435
1.82k
    link<ELF64LE>(Args);
436
1.82k
    return;
437
2.32k
  case ELF64BEKind:
438
89
    link<ELF64BE>(Args);
439
89
    return;
440
2.32k
  default:
441
0
    llvm_unreachable("unknown Config->EKind");
442
2.32k
  }
443
2.32k
}
444
445
2.47k
static std::string getRpath(opt::InputArgList &Args) {
446
2.47k
  std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
447
2.47k
  return llvm::join(V.begin(), V.end(), ":");
448
2.47k
}
449
450
// Determines what we should do if there are remaining unresolved
451
// symbols after the name resolution.
452
2.47k
static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
453
2.47k
  UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
454
2.47k
                                              OPT_warn_unresolved_symbols, true)
455
2.47k
                                     ? 
UnresolvedPolicy::ReportError2.47k
456
2.47k
                                     : 
UnresolvedPolicy::Warn5
;
457
2.47k
458
2.47k
  // Process the last of -unresolved-symbols, -no-undefined or -z defs.
459
8.96k
  for (auto *Arg : llvm::reverse(Args)) {
460
8.96k
    switch (Arg->getOption().getID()) {
461
8.96k
    case OPT_unresolved_symbols: {
462
32
      StringRef S = Arg->getValue();
463
32
      if (S == "ignore-all" || 
S == "ignore-in-object-files"10
)
464
24
        return UnresolvedPolicy::Ignore;
465
8
      if (S == "ignore-in-shared-libs" || 
S == "report-all"5
)
466
6
        return ErrorOrWarn;
467
2
      error("unknown --unresolved-symbols value: " + S);
468
2
      continue;
469
2
    }
470
2
    case OPT_no_undefined:
471
2
      return ErrorOrWarn;
472
81
    case OPT_z:
473
81
      if (StringRef(Arg->getValue()) == "defs")
474
3
        return ErrorOrWarn;
475
78
      continue;
476
8.96k
    }
477
8.96k
  }
478
2.47k
479
2.47k
  // -shared implies -unresolved-symbols=ignore-all because missing
480
2.47k
  // symbols are likely to be resolved at runtime using other DSOs.
481
2.47k
  
if (2.44k
Config->Shared2.44k
)
482
861
    return UnresolvedPolicy::Ignore;
483
1.58k
  return ErrorOrWarn;
484
1.58k
}
485
486
2.47k
static Target2Policy getTarget2(opt::InputArgList &Args) {
487
2.47k
  StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
488
2.47k
  if (S == "rel")
489
1
    return Target2Policy::Rel;
490
2.47k
  if (S == "abs")
491
1
    return Target2Policy::Abs;
492
2.47k
  if (S == "got-rel")
493
2.47k
    return Target2Policy::GotRel;
494
0
  error("unknown --target2 option: " + S);
495
0
  return Target2Policy::GotRel;
496
0
}
497
498
2.47k
static bool isOutputFormatBinary(opt::InputArgList &Args) {
499
2.47k
  StringRef S = Args.getLastArgValue(OPT_oformat, "elf");
500
2.47k
  if (S == "binary")
501
5
    return true;
502
2.47k
  if (!S.startswith("elf"))
503
1
    error("unknown --oformat value: " + S);
504
2.47k
  return false;
505
2.47k
}
506
507
2.47k
static DiscardPolicy getDiscard(opt::InputArgList &Args) {
508
2.47k
  if (Args.hasArg(OPT_relocatable))
509
78
    return DiscardPolicy::None;
510
2.39k
511
2.39k
  auto *Arg =
512
2.39k
      Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
513
2.39k
  if (!Arg)
514
2.39k
    return DiscardPolicy::Default;
515
7
  if (Arg->getOption().getID() == OPT_discard_all)
516
4
    return DiscardPolicy::All;
517
3
  if (Arg->getOption().getID() == OPT_discard_locals)
518
1
    return DiscardPolicy::Locals;
519
2
  return DiscardPolicy::None;
520
2
}
521
522
2.47k
static StringRef getDynamicLinker(opt::InputArgList &Args) {
523
2.47k
  auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
524
2.47k
  if (!Arg || 
Arg->getOption().getID() == OPT_no_dynamic_linker16
)
525
2.46k
    return "";
526
15
  return Arg->getValue();
527
15
}
528
529
2.47k
static ICFLevel getICF(opt::InputArgList &Args) {
530
2.47k
  auto *Arg = Args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
531
2.47k
  if (!Arg || 
Arg->getOption().getID() == OPT_icf_none59
)
532
2.41k
    return ICFLevel::None;
533
58
  if (Arg->getOption().getID() == OPT_icf_safe)
534
4
    return ICFLevel::Safe;
535
54
  return ICFLevel::All;
536
54
}
537
538
2.47k
static StripPolicy getStrip(opt::InputArgList &Args) {
539
2.47k
  if (Args.hasArg(OPT_relocatable))
540
78
    return StripPolicy::None;
541
2.39k
542
2.39k
  auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
543
2.39k
  if (!Arg)
544
2.39k
    return StripPolicy::None;
545
6
  if (Arg->getOption().getID() == OPT_strip_all)
546
3
    return StripPolicy::All;
547
3
  return StripPolicy::Debug;
548
3
}
549
550
61
static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
551
61
  uint64_t VA = 0;
552
61
  if (S.startswith("0x"))
553
49
    S = S.drop_front(2);
554
61
  if (!to_integer(S, VA, 16))
555
5
    error("invalid argument: " + toString(Arg));
556
61
  return VA;
557
61
}
558
559
2.47k
static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
560
2.47k
  StringMap<uint64_t> Ret;
561
2.47k
  for (auto *Arg : Args.filtered(OPT_section_start)) {
562
19
    StringRef Name;
563
19
    StringRef Addr;
564
19
    std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
565
19
    Ret[Name] = parseSectionAddress(Addr, *Arg);
566
19
  }
567
2.47k
568
2.47k
  if (auto *Arg = Args.getLastArg(OPT_Ttext))
569
26
    Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
570
2.47k
  if (auto *Arg = Args.getLastArg(OPT_Tdata))
571
8
    Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
572
2.47k
  if (auto *Arg = Args.getLastArg(OPT_Tbss))
573
8
    Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
574
2.47k
  return Ret;
575
2.47k
}
576
577
2.47k
static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
578
2.47k
  StringRef S = Args.getLastArgValue(OPT_sort_section);
579
2.47k
  if (S == "alignment")
580
3
    return SortSectionPolicy::Alignment;
581
2.47k
  if (S == "name")
582
3
    return SortSectionPolicy::Name;
583
2.47k
  if (!S.empty())
584
0
    error("unknown --sort-section rule: " + S);
585
2.47k
  return SortSectionPolicy::Default;
586
2.47k
}
587
588
2.47k
static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
589
2.47k
  StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
590
2.47k
  if (S == "warn")
591
1
    return OrphanHandlingPolicy::Warn;
592
2.47k
  if (S == "error")
593
1
    return OrphanHandlingPolicy::Error;
594
2.47k
  if (S != "place")
595
1
    error("unknown --orphan-handling mode: " + S);
596
2.47k
  return OrphanHandlingPolicy::Place;
597
2.47k
}
598
599
// Parse --build-id or --build-id=<style>. We handle "tree" as a
600
// synonym for "sha1" because all our hash functions including
601
// -build-id=sha1 are actually tree hashes for performance reasons.
602
static std::pair<BuildIdKind, std::vector<uint8_t>>
603
2.47k
getBuildId(opt::InputArgList &Args) {
604
2.47k
  auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
605
2.47k
  if (!Arg)
606
2.45k
    return {BuildIdKind::None, {}};
607
18
608
18
  if (Arg->getOption().getID() == OPT_build_id)
609
5
    return {BuildIdKind::Fast, {}};
610
13
611
13
  StringRef S = Arg->getValue();
612
13
  if (S == "fast")
613
1
    return {BuildIdKind::Fast, {}};
614
12
  if (S == "md5")
615
2
    return {BuildIdKind::Md5, {}};
616
10
  if (S == "sha1" || 
S == "tree"8
)
617
4
    return {BuildIdKind::Sha1, {}};
618
6
  if (S == "uuid")
619
1
    return {BuildIdKind::Uuid, {}};
620
5
  if (S.startswith("0x"))
621
3
    return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
622
2
623
2
  if (S != "none")
624
0
    error("unknown --build-id style: " + S);
625
2
  return {BuildIdKind::None, {}};
626
2
}
627
628
2.47k
static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &Args) {
629
2.47k
  StringRef S = Args.getLastArgValue(OPT_pack_dyn_relocs, "none");
630
2.47k
  if (S == "android")
631
2
    return {true, false};
632
2.47k
  if (S == "relr")
633
3
    return {false, true};
634
2.47k
  if (S == "android+relr")
635
0
    return {true, true};
636
2.47k
637
2.47k
  if (S != "none")
638
0
    error("unknown -pack-dyn-relocs format: " + S);
639
2.47k
  return {false, false};
640
2.47k
}
641
642
7
static void readCallGraph(MemoryBufferRef MB) {
643
7
  // Build a map from symbol name to section
644
7
  DenseMap<StringRef, const Symbol *> SymbolNameToSymbol;
645
7
  for (InputFile *File : ObjectFiles)
646
7
    for (Symbol *Sym : File->getSymbols())
647
59
      SymbolNameToSymbol[Sym->getName()] = Sym;
648
7
649
92
  auto FindSection = [&](StringRef SymName) -> InputSectionBase * {
650
92
    const Symbol *Sym = SymbolNameToSymbol.lookup(SymName);
651
92
    if (Sym)
652
88
      warnUnorderableSymbol(Sym);
653
4
    else if (Config->WarnSymbolOrdering)
654
2
      warn(MB.getBufferIdentifier() + ": no such symbol: " + SymName);
655
92
656
92
    if (const Defined *DR = dyn_cast_or_null<Defined>(Sym))
657
86
      return dyn_cast_or_null<InputSectionBase>(DR->Section);
658
6
    return nullptr;
659
6
  };
660
7
661
49
  for (StringRef L : args::getLines(MB)) {
662
49
    SmallVector<StringRef, 3> Fields;
663
49
    L.split(Fields, ' ');
664
49
    uint64_t Count;
665
49
    if (Fields.size() != 3 || !to_integer(Fields[2], Count))
666
0
      fatal(MB.getBufferIdentifier() + ": parse error");
667
49
668
49
    if (const InputSectionBase *FromSB = FindSection(Fields[0]))
669
43
      if (const InputSectionBase *ToSB = FindSection(Fields[1]))
670
39
        Config->CallGraphProfile[std::make_pair(FromSB, ToSB)] += Count;
671
49
  }
672
7
}
673
674
2.47k
static bool getCompressDebugSections(opt::InputArgList &Args) {
675
2.47k
  StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
676
2.47k
  if (S == "none")
677
2.47k
    return false;
678
7
  if (S != "zlib")
679
1
    error("unknown --compress-debug-sections value: " + S);
680
7
  if (!zlib::isAvailable())
681
0
    error("--compress-debug-sections: zlib is not available");
682
7
  return true;
683
7
}
684
685
static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args,
686
4.95k
                                                        unsigned Id) {
687
4.95k
  auto *Arg = Args.getLastArg(Id);
688
4.95k
  if (!Arg)
689
4.94k
    return {"", ""};
690
5
691
5
  StringRef S = Arg->getValue();
692
5
  std::pair<StringRef, StringRef> Ret = S.split(';');
693
5
  if (Ret.second.empty())
694
2
    error(Arg->getSpelling() + " expects 'old;new' format, but got " + S);
695
5
  return Ret;
696
5
}
697
698
// Parse the symbol ordering file and warn for any duplicate entries.
699
32
static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) {
700
32
  SetVector<StringRef> Names;
701
32
  for (StringRef S : args::getLines(MB))
702
69
    if (!Names.insert(S) && 
Config->WarnSymbolOrdering4
)
703
4
      warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S);
704
32
705
32
  return Names.takeVector();
706
32
}
707
708
13
static void parseClangOption(StringRef Opt, const Twine &Msg) {
709
13
  std::string Err;
710
13
  raw_string_ostream OS(Err);
711
13
712
13
  const char *Argv[] = {Config->ProgName.data(), Opt.data()};
713
13
  if (cl::ParseCommandLineOptions(2, Argv, "", &OS))
714
11
    return;
715
2
  OS.flush();
716
2
  error(Msg + ": " + StringRef(Err).trim());
717
2
}
718
719
// Initializes Config members by the command line options.
720
2.47k
void LinkerDriver::readConfigs(opt::InputArgList &Args) {
721
2.47k
  errorHandler().Verbose = Args.hasArg(OPT_verbose);
722
2.47k
  errorHandler().FatalWarnings =
723
2.47k
      Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
724
2.47k
  ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
725
2.47k
726
2.47k
  Config->AllowMultipleDefinition =
727
2.47k
      Args.hasFlag(OPT_allow_multiple_definition,
728
2.47k
                   OPT_no_allow_multiple_definition, false) ||
729
2.47k
      
hasZOption(Args, "muldefs")2.47k
;
730
2.47k
  Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
731
2.47k
  Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
732
2.47k
  Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
733
2.47k
  Config->CheckSections =
734
2.47k
      Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
735
2.47k
  Config->Chroot = Args.getLastArgValue(OPT_chroot);
736
2.47k
  Config->CompressDebugSections = getCompressDebugSections(Args);
737
2.47k
  Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false);
738
2.47k
  Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
739
2.47k
                                      !Args.hasArg(OPT_relocatable));
740
2.47k
  Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
741
2.47k
  Config->DisableVerify = Args.hasArg(OPT_disable_verify);
742
2.47k
  Config->Discard = getDiscard(Args);
743
2.47k
  Config->DwoDir = Args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
744
2.47k
  Config->DynamicLinker = getDynamicLinker(Args);
745
2.47k
  Config->EhFrameHdr =
746
2.47k
      Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
747
2.47k
  Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
748
2.47k
  Config->EnableNewDtags =
749
2.47k
      Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
750
2.47k
  Config->Entry = Args.getLastArgValue(OPT_entry);
751
2.47k
  Config->ExecuteOnly =
752
2.47k
      Args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
753
2.47k
  Config->ExportDynamic =
754
2.47k
      Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
755
2.47k
  Config->FilterList = args::getStrings(Args, OPT_filter);
756
2.47k
  Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
757
2.47k
  Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
758
2.47k
  Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
759
2.47k
  Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
760
2.47k
  Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
761
2.47k
  Config->ICF = getICF(Args);
762
2.47k
  Config->IgnoreDataAddressEquality =
763
2.47k
      Args.hasArg(OPT_ignore_data_address_equality);
764
2.47k
  Config->IgnoreFunctionAddressEquality =
765
2.47k
      Args.hasArg(OPT_ignore_function_address_equality);
766
2.47k
  Config->Init = Args.getLastArgValue(OPT_init, "_init");
767
2.47k
  Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
768
2.47k
  Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager);
769
2.47k
  Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager);
770
2.47k
  Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
771
2.47k
  Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
772
2.47k
  Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
773
2.47k
  Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
774
2.47k
  Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile);
775
2.47k
  Config->MapFile = Args.getLastArgValue(OPT_Map);
776
2.47k
  Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0);
777
2.47k
  Config->MergeArmExidx =
778
2.47k
      Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
779
2.47k
  Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
780
2.47k
  Config->Nostdlib = Args.hasArg(OPT_nostdlib);
781
2.47k
  Config->OFormatBinary = isOutputFormatBinary(Args);
782
2.47k
  Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
783
2.47k
  Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
784
2.47k
  Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
785
2.47k
  Config->Optimize = args::getInteger(Args, OPT_O, 1);
786
2.47k
  Config->OrphanHandling = getOrphanHandling(Args);
787
2.47k
  Config->OutputFile = Args.getLastArgValue(OPT_o);
788
2.47k
  Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
789
2.47k
  Config->PrintIcfSections =
790
2.47k
      Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
791
2.47k
  Config->PrintGcSections =
792
2.47k
      Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
793
2.47k
  Config->Rpath = getRpath(Args);
794
2.47k
  Config->Relocatable = Args.hasArg(OPT_relocatable);
795
2.47k
  Config->SaveTemps = Args.hasArg(OPT_save_temps);
796
2.47k
  Config->SearchPaths = args::getStrings(Args, OPT_library_path);
797
2.47k
  Config->SectionStartMap = getSectionStartMap(Args);
798
2.47k
  Config->Shared = Args.hasArg(OPT_shared);
799
2.47k
  Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
800
2.47k
  Config->SoName = Args.getLastArgValue(OPT_soname);
801
2.47k
  Config->SortSection = getSortSection(Args);
802
2.47k
  Config->Strip = getStrip(Args);
803
2.47k
  Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
804
2.47k
  Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
805
2.47k
  Config->Target2 = getTarget2(Args);
806
2.47k
  Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
807
2.47k
  Config->ThinLTOCachePolicy = CHECK(
808
2.47k
      parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
809
2.47k
      "--thinlto-cache-policy: invalid cache policy");
810
2.47k
  Config->ThinLTOEmitImportsFiles =
811
2.47k
      Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
812
2.47k
  Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
813
2.47k
                             
Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq)2.46k
;
814
2.47k
  Config->ThinLTOIndexOnlyArg =
815
2.47k
      Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
816
2.47k
  Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
817
2.47k
  Config->ThinLTOObjectSuffixReplace =
818
2.47k
      getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
819
2.47k
  Config->ThinLTOPrefixReplace =
820
2.47k
      getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq);
821
2.47k
  Config->Trace = Args.hasArg(OPT_trace);
822
2.47k
  Config->Undefined = args::getStrings(Args, OPT_undefined);
823
2.47k
  Config->UndefinedVersion =
824
2.47k
      Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
825
2.47k
  Config->UseAndroidRelrTags = Args.hasFlag(
826
2.47k
      OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
827
2.47k
  Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
828
2.47k
  Config->WarnBackrefs =
829
2.47k
      Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
830
2.47k
  Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
831
2.47k
  Config->WarnSymbolOrdering =
832
2.47k
      Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
833
2.47k
  Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
834
2.47k
  Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
835
2.47k
  Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
836
2.47k
  Config->ZHazardplt = hasZOption(Args, "hazardplt");
837
2.47k
  Config->ZInitfirst = hasZOption(Args, "initfirst");
838
2.47k
  Config->ZKeepTextSectionPrefix = getZFlag(
839
2.47k
      Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
840
2.47k
  Config->ZNodelete = hasZOption(Args, "nodelete");
841
2.47k
  Config->ZNodlopen = hasZOption(Args, "nodlopen");
842
2.47k
  Config->ZNow = getZFlag(Args, "now", "lazy", false);
843
2.47k
  Config->ZOrigin = hasZOption(Args, "origin");
844
2.47k
  Config->ZRelro = getZFlag(Args, "relro", "norelro", true);
845
2.47k
  Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
846
2.47k
  Config->ZRodynamic = hasZOption(Args, "rodynamic");
847
2.47k
  Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
848
2.47k
  Config->ZText = getZFlag(Args, "text", "notext", true);
849
2.47k
  Config->ZWxneeded = hasZOption(Args, "wxneeded");
850
2.47k
851
2.47k
  // Parse LTO options.
852
2.47k
  if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq))
853
1
    parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())),
854
1
                     Arg->getSpelling());
855
2.47k
856
2.47k
  for (auto *Arg : Args.filtered(OPT_plugin_opt))
857
5
    parseClangOption(Arg->getValue(), Arg->getSpelling());
858
2.47k
859
2.47k
  // Parse -mllvm options.
860
2.47k
  for (auto *Arg : Args.filtered(OPT_mllvm))
861
7
    parseClangOption(Arg->getValue(), Arg->getSpelling());
862
2.47k
863
2.47k
  if (Config->LTOO > 3)
864
4
    error("invalid optimization level for LTO: " + Twine(Config->LTOO));
865
2.47k
  if (Config->LTOPartitions == 0)
866
2
    error("--lto-partitions: number of threads must be > 0");
867
2.47k
  if (Config->ThinLTOJobs == 0)
868
2
    error("--thinlto-jobs: number of threads must be > 0");
869
2.47k
870
2.47k
  // Parse ELF{32,64}{LE,BE} and CPU type.
871
2.47k
  if (auto *Arg = Args.getLastArg(OPT_m)) {
872
33
    StringRef S = Arg->getValue();
873
33
    std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
874
33
        parseEmulation(S);
875
33
    Config->MipsN32Abi = (S == "elf32btsmipn32" || 
S == "elf32ltsmipn32"32
);
876
33
    Config->Emulation = S;
877
33
  }
878
2.47k
879
2.47k
  // Parse -hash-style={sysv,gnu,both}.
880
2.47k
  if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
881
147
    StringRef S = Arg->getValue();
882
147
    if (S == "sysv")
883
132
      Config->SysvHash = true;
884
15
    else if (S == "gnu")
885
10
      Config->GnuHash = true;
886
5
    else if (S == "both")
887
5
      Config->SysvHash = Config->GnuHash = true;
888
0
    else
889
0
      error("unknown -hash-style: " + S);
890
147
  }
891
2.47k
892
2.47k
  if (Args.hasArg(OPT_print_map))
893
7
    Config->MapFile = "-";
894
2.47k
895
2.47k
  // --omagic is an option to create old-fashioned executables in which
896
2.47k
  // .text segments are writable. Today, the option is still in use to
897
2.47k
  // create special-purpose programs such as boot loaders. It doesn't
898
2.47k
  // make sense to create PT_GNU_RELRO for such executables.
899
2.47k
  if (Config->Omagic)
900
4
    Config->ZRelro = false;
901
2.47k
902
2.47k
  std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
903
2.47k
904
2.47k
  std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) =
905
2.47k
      getPackDynRelocs(Args);
906
2.47k
907
2.47k
  if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
908
32
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
909
32
      Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
910
2.47k
911
2.47k
  // If --retain-symbol-file is used, we'll keep only the symbols listed in
912
2.47k
  // the file and discard all others.
913
2.47k
  if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
914
3
    Config->DefaultSymbolVersion = VER_NDX_LOCAL;
915
3
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
916
3
      for (StringRef S : args::getLines(*Buffer))
917
4
        Config->VersionScriptGlobals.push_back(
918
4
            {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
919
3
  }
920
2.47k
921
2.47k
  bool HasExportDynamic =
922
2.47k
      Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
923
2.47k
924
2.47k
  // Parses -dynamic-list and -export-dynamic-symbol. They make some
925
2.47k
  // symbols private. Note that -export-dynamic takes precedence over them
926
2.47k
  // as it says all symbols should be exported.
927
2.47k
  if (!HasExportDynamic) {
928
2.45k
    for (auto *Arg : Args.filtered(OPT_dynamic_list))
929
24
      if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
930
24
        readDynamicList(*Buffer);
931
2.45k
932
2.45k
    for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
933
5
      Config->DynamicList.push_back(
934
5
          {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
935
2.45k
  }
936
2.47k
937
2.47k
  // If --export-dynamic-symbol=foo is given and symbol foo is defined in
938
2.47k
  // an object file in an archive file, that object file should be pulled
939
2.47k
  // out and linked. (It doesn't have to behave like that from technical
940
2.47k
  // point of view, but this is needed for compatibility with GNU.)
941
2.47k
  for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
942
7
    Config->Undefined.push_back(Arg->getValue());
943
2.47k
944
2.47k
  for (auto *Arg : Args.filtered(OPT_version_script))
945
82
    if (Optional<std::string> Path = searchScript(Arg->getValue())) {
946
81
      if (Optional<MemoryBufferRef> Buffer = readFile(*Path))
947
81
        readVersionScript(*Buffer);
948
81
    } else {
949
1
      error(Twine("cannot find version script ") + Arg->getValue());
950
1
    }
951
2.47k
}
952
953
// Some Config members do not directly correspond to any particular
954
// command line options, but computed based on other Config values.
955
// This function initialize such members. See Config.h for the details
956
// of these values.
957
2.33k
static void setConfigs(opt::InputArgList &Args) {
958
2.33k
  ELFKind Kind = Config->EKind;
959
2.33k
  uint16_t Machine = Config->EMachine;
960
2.33k
961
2.33k
  Config->CopyRelocs = (Config->Relocatable || 
Config->EmitRelocs2.25k
);
962
2.33k
  Config->Is64 = (Kind == ELF64LEKind || 
Kind == ELF64BEKind497
);
963
2.33k
  Config->IsLE = (Kind == ELF32LEKind || 
Kind == ELF64LEKind2.05k
);
964
2.33k
  Config->Endianness =
965
2.33k
      Config->IsLE ? 
support::endianness::little2.12k
:
support::endianness::big211
;
966
2.33k
  Config->IsMips64EL = (Kind == ELF64LEKind && 
Machine == EM_MIPS1.83k
);
967
2.33k
  Config->Pic = Config->Pie || 
Config->Shared2.28k
;
968
2.33k
  Config->Wordsize = Config->Is64 ? 
81.92k
:
4408
;
969
2.33k
970
2.33k
  // There is an ILP32 ABI for x86-64, although it's not very popular.
971
2.33k
  // It is called the x32 ABI.
972
2.33k
  bool IsX32 = (Kind == ELF32LEKind && 
Machine == EM_X86_64286
);
973
2.33k
974
2.33k
  // ELF defines two different ways to store relocation addends as shown below:
975
2.33k
  //
976
2.33k
  //  Rel:  Addends are stored to the location where relocations are applied.
977
2.33k
  //  Rela: Addends are stored as part of relocation entry.
978
2.33k
  //
979
2.33k
  // In other words, Rela makes it easy to read addends at the price of extra
980
2.33k
  // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
981
2.33k
  // different mechanisms in the first place, but this is how the spec is
982
2.33k
  // defined.
983
2.33k
  //
984
2.33k
  // You cannot choose which one, Rel or Rela, you want to use. Instead each
985
2.33k
  // ABI defines which one you need to use. The following expression expresses
986
2.33k
  // that.
987
2.33k
  Config->IsRela =
988
2.33k
      (Config->Is64 || 
IsX32408
||
Machine == EM_PPC405
||
Machine == EM_RISCV402
) &&
989
2.33k
      
Machine != EM_MIPS1.93k
;
990
2.33k
991
2.33k
  // If the output uses REL relocations we must store the dynamic relocation
992
2.33k
  // addends to the output sections. We also store addends for RELA relocations
993
2.33k
  // if --apply-dynamic-relocs is used.
994
2.33k
  // We default to not writing the addends when using RELA relocations since
995
2.33k
  // any standard conforming tool can find it in r_addend.
996
2.33k
  Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
997
2.33k
                                      OPT_no_apply_dynamic_relocs, false) ||
998
2.33k
                         
!Config->IsRela2.33k
;
999
2.33k
}
1000
1001
// Returns a value of "-format" option.
1002
7
static bool isFormatBinary(StringRef S) {
1003
7
  if (S == "binary")
1004
5
    return true;
1005
2
  if (S == "elf" || S == "default")
1006
1
    return false;
1007
1
  error("unknown -format value: " + S +
1008
1
        " (supported formats: elf, default, binary)");
1009
1
  return false;
1010
1
}
1011
1012
2.47k
void LinkerDriver::createFiles(opt::InputArgList &Args) {
1013
2.47k
  // For --{push,pop}-state.
1014
2.47k
  std::vector<std::tuple<bool, bool, bool>> Stack;
1015
2.47k
1016
2.47k
  // Iterate over argv to process input files and positional arguments.
1017
9.07k
  for (auto *Arg : Args) {
1018
9.07k
    switch (Arg->getOption().getUnaliasedOption().getID()) {
1019
9.07k
    case OPT_library:
1020
34
      addLibrary(Arg->getValue());
1021
34
      break;
1022
9.07k
    case OPT_INPUT:
1023
3.43k
      addFile(Arg->getValue(), /*WithLOption=*/false);
1024
3.43k
      break;
1025
9.07k
    case OPT_defsym: {
1026
30
      StringRef From;
1027
30
      StringRef To;
1028
30
      std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1029
30
      if (From.empty() || 
To.empty()29
)
1030
2
        error("-defsym: syntax error: " + StringRef(Arg->getValue()));
1031
28
      else
1032
28
        readDefsym(From, MemoryBufferRef(To, "-defsym"));
1033
30
      break;
1034
9.07k
    }
1035
9.07k
    case OPT_script:
1036
503
      if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1037
502
        if (Optional<MemoryBufferRef> MB = readFile(*Path))
1038
502
          readLinkerScript(*MB);
1039
502
        break;
1040
502
      }
1041
1
      error(Twine("cannot find linker script ") + Arg->getValue());
1042
1
      break;
1043
15
    case OPT_as_needed:
1044
15
      Config->AsNeeded = true;
1045
15
      break;
1046
7
    case OPT_format:
1047
7
      Config->FormatBinary = isFormatBinary(Arg->getValue());
1048
7
      break;
1049
1
    case OPT_no_as_needed:
1050
1
      Config->AsNeeded = false;
1051
1
      break;
1052
28
    case OPT_Bstatic:
1053
28
      Config->Static = true;
1054
28
      break;
1055
6
    case OPT_Bdynamic:
1056
6
      Config->Static = false;
1057
6
      break;
1058
18
    case OPT_whole_archive:
1059
18
      InWholeArchive = true;
1060
18
      break;
1061
3
    case OPT_no_whole_archive:
1062
3
      InWholeArchive = false;
1063
3
      break;
1064
2
    case OPT_just_symbols:
1065
2
      if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
1066
2
        Files.push_back(createObjectFile(*MB));
1067
2
        Files.back()->JustSymbols = true;
1068
2
      }
1069
2
      break;
1070
8
    case OPT_start_group:
1071
8
      if (InputFile::IsInGroup)
1072
1
        error("nested --start-group");
1073
8
      InputFile::IsInGroup = true;
1074
8
      break;
1075
6
    case OPT_end_group:
1076
6
      if (!InputFile::IsInGroup)
1077
1
        error("stray --end-group");
1078
6
      InputFile::IsInGroup = false;
1079
6
      ++InputFile::NextGroupId;
1080
6
      break;
1081
19
    case OPT_start_lib:
1082
19
      if (InLib)
1083
1
        error("nested --start-lib");
1084
19
      if (InputFile::IsInGroup)
1085
2
        error("may not nest --start-lib in --start-group");
1086
19
      InLib = true;
1087
19
      InputFile::IsInGroup = true;
1088
19
      break;
1089
11
    case OPT_end_lib:
1090
11
      if (!InLib)
1091
1
        error("stray --end-lib");
1092
11
      InLib = false;
1093
11
      InputFile::IsInGroup = false;
1094
11
      ++InputFile::NextGroupId;
1095
11
      break;
1096
6
    case OPT_push_state:
1097
6
      Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive);
1098
6
      break;
1099
3
    case OPT_pop_state:
1100
3
      if (Stack.empty()) {
1101
0
        error("unbalanced --push-state/--pop-state");
1102
0
        break;
1103
0
      }
1104
3
      std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back();
1105
3
      Stack.pop_back();
1106
3
      break;
1107
9.07k
    }
1108
9.07k
  }
1109
2.47k
1110
2.47k
  if (Files.empty() && 
errorCount() == 047
)
1111
2
    error("no input files");
1112
2.47k
}
1113
1114
// If -m <machine_type> was not given, infer it from object files.
1115
2.33k
void LinkerDriver::inferMachineType() {
1116
2.33k
  if (Config->EKind != ELFNoneKind)
1117
31
    return;
1118
2.30k
1119
2.33k
  
for (InputFile *F : Files)2.30k
{
1120
2.33k
    if (F->EKind == ELFNoneKind)
1121
27
      continue;
1122
2.30k
    Config->EKind = F->EKind;
1123
2.30k
    Config->EMachine = F->EMachine;
1124
2.30k
    Config->OSABI = F->OSABI;
1125
2.30k
    Config->MipsN32Abi = Config->EMachine == EM_MIPS && 
isMipsN32Abi(F)177
;
1126
2.30k
    return;
1127
2.30k
  }
1128
2.30k
  error("target emulation unknown: -m or at least one .o file required");
1129
1
}
1130
1131
// Parse -z max-page-size=<value>. The default value is defined by
1132
// each target.
1133
2.32k
static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1134
2.32k
  uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1135
2.32k
                                       Target->DefaultMaxPageSize);
1136
2.32k
  if (!isPowerOf2_64(Val))
1137
1
    error("max-page-size: value isn't a power of 2");
1138
2.32k
  return Val;
1139
2.32k
}
1140
1141
// Parses -image-base option.
1142
2.32k
static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1143
2.32k
  // Because we are using "Config->MaxPageSize" here, this function has to be
1144
2.32k
  // called after the variable is initialized.
1145
2.32k
  auto *Arg = Args.getLastArg(OPT_image_base);
1146
2.32k
  if (!Arg)
1147
2.31k
    return None;
1148
8
1149
8
  StringRef S = Arg->getValue();
1150
8
  uint64_t V;
1151
8
  if (!to_integer(S, V)) {
1152
0
    error("-image-base: number expected, but got " + S);
1153
0
    return 0;
1154
0
  }
1155
8
  if ((V % Config->MaxPageSize) != 0)
1156
2
    warn("-image-base: address isn't multiple of page size: " + S);
1157
8
  return V;
1158
8
}
1159
1160
// Parses `--exclude-libs=lib,lib,...`.
1161
// The library names may be delimited by commas or colons.
1162
8
static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1163
8
  DenseSet<StringRef> Ret;
1164
8
  for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1165
8
    StringRef S = Arg->getValue();
1166
15
    for (;;) {
1167
15
      size_t Pos = S.find_first_of(",:");
1168
15
      if (Pos == StringRef::npos)
1169
8
        break;
1170
7
      Ret.insert(S.substr(0, Pos));
1171
7
      S = S.substr(Pos + 1);
1172
7
    }
1173
8
    Ret.insert(S);
1174
8
  }
1175
8
  return Ret;
1176
8
}
1177
1178
// Handles the -exclude-libs option. If a static library file is specified
1179
// by the -exclude-libs option, all public symbols from the archive become
1180
// private unless otherwise specified by version scripts or something.
1181
// A special library name "ALL" means all archive files.
1182
//
1183
// This is not a popular option, but some programs such as bionic libc use it.
1184
template <class ELFT>
1185
8
static void excludeLibs(opt::InputArgList &Args) {
1186
8
  DenseSet<StringRef> Libs = getExcludeLibs(Args);
1187
8
  bool All = Libs.count("ALL");
1188
8
1189
23
  auto Visit = [&](InputFile *File) {
1190
23
    if (!File->ArchiveName.empty())
1191
13
      if (All || 
Libs.count(path::filename(File->ArchiveName))8
)
1192
11
        for (Symbol *Sym : File->getSymbols())
1193
25
          if (!Sym->isLocal() && 
Sym->File == File19
)
1194
14
            Sym->VersionId = VER_NDX_LOCAL;
1195
23
  };
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputFile*)::operator()(lld::elf::InputFile*) const
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputFile*)::operator()(lld::elf::InputFile*) const
Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputFile*)::operator()(lld::elf::InputFile*) const
Line
Count
Source
1189
23
  auto Visit = [&](InputFile *File) {
1190
23
    if (!File->ArchiveName.empty())
1191
13
      if (All || 
Libs.count(path::filename(File->ArchiveName))8
)
1192
11
        for (Symbol *Sym : File->getSymbols())
1193
25
          if (!Sym->isLocal() && 
Sym->File == File19
)
1194
14
            Sym->VersionId = VER_NDX_LOCAL;
1195
23
  };
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputFile*)::operator()(lld::elf::InputFile*) const
1196
8
1197
8
  for (InputFile *File : ObjectFiles)
1198
16
    Visit(File);
1199
8
1200
8
  for (BitcodeFile *File : BitcodeFiles)
1201
7
    Visit(File);
1202
8
}
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)
Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)
Line
Count
Source
1185
8
static void excludeLibs(opt::InputArgList &Args) {
1186
8
  DenseSet<StringRef> Libs = getExcludeLibs(Args);
1187
8
  bool All = Libs.count("ALL");
1188
8
1189
8
  auto Visit = [&](InputFile *File) {
1190
8
    if (!File->ArchiveName.empty())
1191
8
      if (All || Libs.count(path::filename(File->ArchiveName)))
1192
8
        for (Symbol *Sym : File->getSymbols())
1193
8
          if (!Sym->isLocal() && Sym->File == File)
1194
8
            Sym->VersionId = VER_NDX_LOCAL;
1195
8
  };
1196
8
1197
8
  for (InputFile *File : ObjectFiles)
1198
16
    Visit(File);
1199
8
1200
8
  for (BitcodeFile *File : BitcodeFiles)
1201
7
    Visit(File);
1202
8
}
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)
1203
1204
// Force Sym to be entered in the output. Used for -u or equivalent.
1205
2.33k
template <class ELFT> static void handleUndefined(StringRef Name) {
1206
2.33k
  Symbol *Sym = Symtab->find(Name);
1207
2.33k
  if (!Sym)
1208
1.11k
    return;
1209
1.22k
1210
1.22k
  // Since symbol S may not be used inside the program, LTO may
1211
1.22k
  // eliminate it. Mark the symbol as "used" to prevent it.
1212
1.22k
  Sym->IsUsedInRegularObj = true;
1213
1.22k
1214
1.22k
  if (Sym->isLazy())
1215
16
    Symtab->fetchLazy<ELFT>(Sym);
1216
1.22k
}
Driver.cpp:void handleUndefined<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::StringRef)
Line
Count
Source
1205
285
template <class ELFT> static void handleUndefined(StringRef Name) {
1206
285
  Symbol *Sym = Symtab->find(Name);
1207
285
  if (!Sym)
1208
120
    return;
1209
165
1210
165
  // Since symbol S may not be used inside the program, LTO may
1211
165
  // eliminate it. Mark the symbol as "used" to prevent it.
1212
165
  Sym->IsUsedInRegularObj = true;
1213
165
1214
165
  if (Sym->isLazy())
1215
1
    Symtab->fetchLazy<ELFT>(Sym);
1216
165
}
Driver.cpp:void handleUndefined<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::StringRef)
Line
Count
Source
1205
120
template <class ELFT> static void handleUndefined(StringRef Name) {
1206
120
  Symbol *Sym = Symtab->find(Name);
1207
120
  if (!Sym)
1208
49
    return;
1209
71
1210
71
  // Since symbol S may not be used inside the program, LTO may
1211
71
  // eliminate it. Mark the symbol as "used" to prevent it.
1212
71
  Sym->IsUsedInRegularObj = true;
1213
71
1214
71
  if (Sym->isLazy())
1215
0
    Symtab->fetchLazy<ELFT>(Sym);
1216
71
}
Driver.cpp:void handleUndefined<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::StringRef)
Line
Count
Source
1205
1.84k
template <class ELFT> static void handleUndefined(StringRef Name) {
1206
1.84k
  Symbol *Sym = Symtab->find(Name);
1207
1.84k
  if (!Sym)
1208
899
    return;
1209
943
1210
943
  // Since symbol S may not be used inside the program, LTO may
1211
943
  // eliminate it. Mark the symbol as "used" to prevent it.
1212
943
  Sym->IsUsedInRegularObj = true;
1213
943
1214
943
  if (Sym->isLazy())
1215
15
    Symtab->fetchLazy<ELFT>(Sym);
1216
943
}
Driver.cpp:void handleUndefined<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::StringRef)
Line
Count
Source
1205
89
template <class ELFT> static void handleUndefined(StringRef Name) {
1206
89
  Symbol *Sym = Symtab->find(Name);
1207
89
  if (!Sym)
1208
46
    return;
1209
43
1210
43
  // Since symbol S may not be used inside the program, LTO may
1211
43
  // eliminate it. Mark the symbol as "used" to prevent it.
1212
43
  Sym->IsUsedInRegularObj = true;
1213
43
1214
43
  if (Sym->isLazy())
1215
0
    Symtab->fetchLazy<ELFT>(Sym);
1216
43
}
1217
1218
75.9k
template <class ELFT> static void handleLibcall(StringRef Name) {
1219
75.9k
  Symbol *Sym = Symtab->find(Name);
1220
75.9k
  if (!Sym || 
!Sym->isLazy()4
)
1221
75.9k
    return;
1222
4
1223
4
  MemoryBufferRef MB;
1224
4
  if (auto *LO = dyn_cast<LazyObject>(Sym))
1225
2
    MB = LO->File->MB;
1226
2
  else
1227
2
    MB = cast<LazyArchive>(Sym)->getMemberBuffer();
1228
4
1229
4
  if (isBitcode(MB))
1230
2
    Symtab->fetchLazy<ELFT>(Sym);
1231
4
}
Driver.cpp:void handleLibcall<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::StringRef)
Line
Count
Source
1218
463
template <class ELFT> static void handleLibcall(StringRef Name) {
1219
463
  Symbol *Sym = Symtab->find(Name);
1220
463
  if (!Sym || 
!Sym->isLazy()0
)
1221
463
    return;
1222
0
1223
0
  MemoryBufferRef MB;
1224
0
  if (auto *LO = dyn_cast<LazyObject>(Sym))
1225
0
    MB = LO->File->MB;
1226
0
  else
1227
0
    MB = cast<LazyArchive>(Sym)->getMemberBuffer();
1228
0
1229
0
  if (isBitcode(MB))
1230
0
    Symtab->fetchLazy<ELFT>(Sym);
1231
0
}
Unexecuted instantiation: Driver.cpp:void handleLibcall<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::StringRef)
Driver.cpp:void handleLibcall<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::StringRef)
Line
Count
Source
1218
75.4k
template <class ELFT> static void handleLibcall(StringRef Name) {
1219
75.4k
  Symbol *Sym = Symtab->find(Name);
1220
75.4k
  if (!Sym || 
!Sym->isLazy()4
)
1221
75.4k
    return;
1222
4
1223
4
  MemoryBufferRef MB;
1224
4
  if (auto *LO = dyn_cast<LazyObject>(Sym))
1225
2
    MB = LO->File->MB;
1226
2
  else
1227
2
    MB = cast<LazyArchive>(Sym)->getMemberBuffer();
1228
4
1229
4
  if (isBitcode(MB))
1230
2
    Symtab->fetchLazy<ELFT>(Sym);
1231
4
}
Unexecuted instantiation: Driver.cpp:void handleLibcall<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::StringRef)
1232
1233
15.8k
template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1234
15.8k
  // If all references to a DSO happen to be weak, the DSO is not added to
1235
15.8k
  // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1236
15.8k
  // from the DSO. Otherwise, they become dangling references that point to a
1237
15.8k
  // non-existent DSO.
1238
15.8k
  if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1239
709
    return !S->getFile<ELFT>().IsNeeded;
1240
15.1k
1241
15.1k
  // We are done processing archives, so lazy symbols that were used but not
1242
15.1k
  // found can be converted to undefined. We could also just delete the other
1243
15.1k
  // lazy symbols, but that seems to be more work than it is worth.
1244
15.1k
  return Sym.isLazy() && 
Sym.IsUsedInRegularObj59
;
1245
15.1k
}
Driver.cpp:bool shouldDemote<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::Symbol&)
Line
Count
Source
1233
997
template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1234
997
  // If all references to a DSO happen to be weak, the DSO is not added to
1235
997
  // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1236
997
  // from the DSO. Otherwise, they become dangling references that point to a
1237
997
  // non-existent DSO.
1238
997
  if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1239
109
    return !S->getFile<ELFT>().IsNeeded;
1240
888
1241
888
  // We are done processing archives, so lazy symbols that were used but not
1242
888
  // found can be converted to undefined. We could also just delete the other
1243
888
  // lazy symbols, but that seems to be more work than it is worth.
1244
888
  return Sym.isLazy() && 
Sym.IsUsedInRegularObj1
;
1245
888
}
Driver.cpp:bool shouldDemote<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::Symbol&)
Line
Count
Source
1233
508
template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1234
508
  // If all references to a DSO happen to be weak, the DSO is not added to
1235
508
  // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1236
508
  // from the DSO. Otherwise, they become dangling references that point to a
1237
508
  // non-existent DSO.
1238
508
  if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1239
95
    return !S->getFile<ELFT>().IsNeeded;
1240
413
1241
413
  // We are done processing archives, so lazy symbols that were used but not
1242
413
  // found can be converted to undefined. We could also just delete the other
1243
413
  // lazy symbols, but that seems to be more work than it is worth.
1244
413
  return Sym.isLazy() && 
Sym.IsUsedInRegularObj0
;
1245
413
}
Driver.cpp:bool shouldDemote<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::Symbol&)
Line
Count
Source
1233
4.10k
template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1234
4.10k
  // If all references to a DSO happen to be weak, the DSO is not added to
1235
4.10k
  // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1236
4.10k
  // from the DSO. Otherwise, they become dangling references that point to a
1237
4.10k
  // non-existent DSO.
1238
4.10k
  if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1239
471
    return !S->getFile<ELFT>().IsNeeded;
1240
3.62k
1241
3.62k
  // We are done processing archives, so lazy symbols that were used but not
1242
3.62k
  // found can be converted to undefined. We could also just delete the other
1243
3.62k
  // lazy symbols, but that seems to be more work than it is worth.
1244
3.62k
  return Sym.isLazy() && 
Sym.IsUsedInRegularObj57
;
1245
3.62k
}
Driver.cpp:bool shouldDemote<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::Symbol&)
Line
Count
Source
1233
10.2k
template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1234
10.2k
  // If all references to a DSO happen to be weak, the DSO is not added to
1235
10.2k
  // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1236
10.2k
  // from the DSO. Otherwise, they become dangling references that point to a
1237
10.2k
  // non-existent DSO.
1238
10.2k
  if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1239
34
    return !S->getFile<ELFT>().IsNeeded;
1240
10.2k
1241
10.2k
  // We are done processing archives, so lazy symbols that were used but not
1242
10.2k
  // found can be converted to undefined. We could also just delete the other
1243
10.2k
  // lazy symbols, but that seems to be more work than it is worth.
1244
10.2k
  return Sym.isLazy() && 
Sym.IsUsedInRegularObj1
;
1245
10.2k
}
1246
1247
// Some files, such as .so or files between -{start,end}-lib may be removed
1248
// after their symbols are added to the symbol table. If that happens, we
1249
// need to remove symbols that refer files that no longer exist, so that
1250
// they won't appear in the symbol table of the output file.
1251
//
1252
// We remove symbols by demoting them to undefined symbol.
1253
2.23k
template <class ELFT> static void demoteSymbols() {
1254
15.8k
  for (Symbol *Sym : Symtab->getSymbols()) {
1255
15.8k
    if (shouldDemote<ELFT>(*Sym)) {
1256
42
      bool Used = Sym->Used;
1257
42
      replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1258
42
                               Sym->StOther, Sym->Type);
1259
42
      Sym->Used = Used;
1260
42
    }
1261
15.8k
  }
1262
2.23k
}
Driver.cpp:void demoteSymbols<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
1253
269
template <class ELFT> static void demoteSymbols() {
1254
997
  for (Symbol *Sym : Symtab->getSymbols()) {
1255
997
    if (shouldDemote<ELFT>(*Sym)) {
1256
7
      bool Used = Sym->Used;
1257
7
      replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1258
7
                               Sym->StOther, Sym->Type);
1259
7
      Sym->Used = Used;
1260
7
    }
1261
997
  }
1262
269
}
Driver.cpp:void demoteSymbols<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
1253
119
template <class ELFT> static void demoteSymbols() {
1254
508
  for (Symbol *Sym : Symtab->getSymbols()) {
1255
508
    if (shouldDemote<ELFT>(*Sym)) {
1256
0
      bool Used = Sym->Used;
1257
0
      replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1258
0
                               Sym->StOther, Sym->Type);
1259
0
      Sym->Used = Used;
1260
0
    }
1261
508
  }
1262
119
}
Driver.cpp:void demoteSymbols<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
1253
1.76k
template <class ELFT> static void demoteSymbols() {
1254
4.10k
  for (Symbol *Sym : Symtab->getSymbols()) {
1255
4.10k
    if (shouldDemote<ELFT>(*Sym)) {
1256
34
      bool Used = Sym->Used;
1257
34
      replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1258
34
                               Sym->StOther, Sym->Type);
1259
34
      Sym->Used = Used;
1260
34
    }
1261
4.10k
  }
1262
1.76k
}
Driver.cpp:void demoteSymbols<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
1253
85
template <class ELFT> static void demoteSymbols() {
1254
10.2k
  for (Symbol *Sym : Symtab->getSymbols()) {
1255
10.2k
    if (shouldDemote<ELFT>(*Sym)) {
1256
1
      bool Used = Sym->Used;
1257
1
      replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1258
1
                               Sym->StOther, Sym->Type);
1259
1
      Sym->Used = Used;
1260
1
    }
1261
10.2k
  }
1262
85
}
1263
1264
// The section referred to by S is considered address-significant. Set the
1265
// KeepUnique flag on the section if appropriate.
1266
371
static void markAddrsig(Symbol *S) {
1267
371
  if (auto *D = dyn_cast_or_null<Defined>(S))
1268
296
    if (D->Section)
1269
284
      // We don't need to keep text sections unique under --icf=all even if they
1270
284
      // are address-significant.
1271
284
      if (Config->ICF == ICFLevel::Safe || 
!(D->Section->Flags & SHF_EXECINSTR)218
)
1272
108
        D->Section->KeepUnique = true;
1273
371
}
1274
1275
// Record sections that define symbols mentioned in --keep-unique <symbol>
1276
// and symbols referred to by address-significance tables. These sections are
1277
// ineligible for ICF.
1278
template <class ELFT>
1279
57
static void findKeepUniqueSections(opt::InputArgList &Args) {
1280
57
  for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1281
3
    StringRef Name = Arg->getValue();
1282
3
    auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1283
3
    if (!D || 
!D->Section2
) {
1284
1
      warn("could not find symbol " + Name + " to keep unique");
1285
1
      continue;
1286
1
    }
1287
2
    D->Section->KeepUnique = true;
1288
2
  }
1289
57
1290
57
  // --icf=all --ignore-data-address-equality means that we can ignore
1291
57
  // the dynsym and address-significance tables entirely.
1292
57
  if (Config->ICF == ICFLevel::All && 
Config->IgnoreDataAddressEquality53
)
1293
3
    return;
1294
54
1295
54
  // Symbols in the dynsym could be address-significant in other executables
1296
54
  // or DSOs, so we conservatively mark them as address-significant.
1297
54
  for (Symbol *S : Symtab->getSymbols())
1298
212
    if (S->includeInDynsym())
1299
43
      markAddrsig(S);
1300
54
1301
54
  // Visit the address-significance table in each object file and mark each
1302
54
  // referenced symbol as address-significant.
1303
71
  for (InputFile *F : ObjectFiles) {
1304
71
    auto *Obj = cast<ObjFile<ELFT>>(F);
1305
71
    ArrayRef<Symbol *> Syms = Obj->getSymbols();
1306
71
    if (Obj->AddrsigSec) {
1307
5
      ArrayRef<uint8_t> Contents =
1308
5
          check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1309
5
      const uint8_t *Cur = Contents.begin();
1310
45
      while (Cur != Contents.end()) {
1311
40
        unsigned Size;
1312
40
        const char *Err;
1313
40
        uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1314
40
        if (Err)
1315
0
          fatal(toString(F) + ": could not decode addrsig section: " + Err);
1316
40
        markAddrsig(Syms[SymIndex]);
1317
40
        Cur += Size;
1318
40
      }
1319
66
    } else {
1320
66
      // If an object file does not have an address-significance table,
1321
66
      // conservatively mark all of its symbols as address-significant.
1322
66
      for (Symbol *S : Syms)
1323
288
        markAddrsig(S);
1324
66
    }
1325
71
  }
1326
54
}
Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)
Line
Count
Source
1279
3
static void findKeepUniqueSections(opt::InputArgList &Args) {
1280
3
  for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1281
0
    StringRef Name = Arg->getValue();
1282
0
    auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1283
0
    if (!D || !D->Section) {
1284
0
      warn("could not find symbol " + Name + " to keep unique");
1285
0
      continue;
1286
0
    }
1287
0
    D->Section->KeepUnique = true;
1288
0
  }
1289
3
1290
3
  // --icf=all --ignore-data-address-equality means that we can ignore
1291
3
  // the dynsym and address-significance tables entirely.
1292
3
  if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality)
1293
0
    return;
1294
3
1295
3
  // Symbols in the dynsym could be address-significant in other executables
1296
3
  // or DSOs, so we conservatively mark them as address-significant.
1297
3
  for (Symbol *S : Symtab->getSymbols())
1298
11
    if (S->includeInDynsym())
1299
4
      markAddrsig(S);
1300
3
1301
3
  // Visit the address-significance table in each object file and mark each
1302
3
  // referenced symbol as address-significant.
1303
3
  for (InputFile *F : ObjectFiles) {
1304
3
    auto *Obj = cast<ObjFile<ELFT>>(F);
1305
3
    ArrayRef<Symbol *> Syms = Obj->getSymbols();
1306
3
    if (Obj->AddrsigSec) {
1307
0
      ArrayRef<uint8_t> Contents =
1308
0
          check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1309
0
      const uint8_t *Cur = Contents.begin();
1310
0
      while (Cur != Contents.end()) {
1311
0
        unsigned Size;
1312
0
        const char *Err;
1313
0
        uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1314
0
        if (Err)
1315
0
          fatal(toString(F) + ": could not decode addrsig section: " + Err);
1316
0
        markAddrsig(Syms[SymIndex]);
1317
0
        Cur += Size;
1318
0
      }
1319
3
    } else {
1320
3
      // If an object file does not have an address-significance table,
1321
3
      // conservatively mark all of its symbols as address-significant.
1322
3
      for (Symbol *S : Syms)
1323
25
        markAddrsig(S);
1324
3
    }
1325
3
  }
1326
3
}
Unexecuted instantiation: Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)
Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)
Line
Count
Source
1279
54
static void findKeepUniqueSections(opt::InputArgList &Args) {
1280
54
  for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1281
3
    StringRef Name = Arg->getValue();
1282
3
    auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1283
3
    if (!D || 
!D->Section2
) {
1284
1
      warn("could not find symbol " + Name + " to keep unique");
1285
1
      continue;
1286
1
    }
1287
2
    D->Section->KeepUnique = true;
1288
2
  }
1289
54
1290
54
  // --icf=all --ignore-data-address-equality means that we can ignore
1291
54
  // the dynsym and address-significance tables entirely.
1292
54
  if (Config->ICF == ICFLevel::All && 
Config->IgnoreDataAddressEquality50
)
1293
3
    return;
1294
51
1295
51
  // Symbols in the dynsym could be address-significant in other executables
1296
51
  // or DSOs, so we conservatively mark them as address-significant.
1297
51
  for (Symbol *S : Symtab->getSymbols())
1298
201
    if (S->includeInDynsym())
1299
39
      markAddrsig(S);
1300
51
1301
51
  // Visit the address-significance table in each object file and mark each
1302
51
  // referenced symbol as address-significant.
1303
68
  for (InputFile *F : ObjectFiles) {
1304
68
    auto *Obj = cast<ObjFile<ELFT>>(F);
1305
68
    ArrayRef<Symbol *> Syms = Obj->getSymbols();
1306
68
    if (Obj->AddrsigSec) {
1307
5
      ArrayRef<uint8_t> Contents =
1308
5
          check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1309
5
      const uint8_t *Cur = Contents.begin();
1310
45
      while (Cur != Contents.end()) {
1311
40
        unsigned Size;
1312
40
        const char *Err;
1313
40
        uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1314
40
        if (Err)
1315
0
          fatal(toString(F) + ": could not decode addrsig section: " + Err);
1316
40
        markAddrsig(Syms[SymIndex]);
1317
40
        Cur += Size;
1318
40
      }
1319
63
    } else {
1320
63
      // If an object file does not have an address-significance table,
1321
63
      // conservatively mark all of its symbols as address-significant.
1322
63
      for (Symbol *S : Syms)
1323
263
        markAddrsig(S);
1324
63
    }
1325
68
  }
1326
51
}
Unexecuted instantiation: Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)
1327
1328
static const char *LibcallRoutineNames[] = {
1329
#define HANDLE_LIBCALL(code, name) name,
1330
#include "llvm/IR/RuntimeLibcalls.def"
1331
#undef HANDLE_LIBCALL
1332
};
1333
1334
// Do actual linking. Note that when this function is called,
1335
// all linker scripts have already been parsed.
1336
2.32k
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1337
2.32k
  Target = getTarget();
1338
2.32k
1339
2.32k
  Config->MaxPageSize = getMaxPageSize(Args);
1340
2.32k
  Config->ImageBase = getImageBase(Args);
1341
2.32k
1342
2.32k
  // If a -hash-style option was not given, set to a default value,
1343
2.32k
  // which varies depending on the target.
1344
2.32k
  if (!Args.hasArg(OPT_hash_style)) {
1345
2.17k
    if (Config->EMachine == EM_MIPS)
1346
181
      Config->SysvHash = true;
1347
1.99k
    else
1348
1.99k
      Config->SysvHash = Config->GnuHash = true;
1349
2.17k
  }
1350
2.32k
1351
2.32k
  // Default output filename is "a.out" by the Unix tradition.
1352
2.32k
  if (Config->OutputFile.empty())
1353
6
    Config->OutputFile = "a.out";
1354
2.32k
1355
2.32k
  // Fail early if the output file or map file is not writable. If a user has a
1356
2.32k
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1357
2.32k
  // find that it failed because there was a mistake in their command-line.
1358
2.32k
  if (auto E = tryCreateFile(Config->OutputFile))
1359
8
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
1360
2.32k
  if (auto E = tryCreateFile(Config->MapFile))
1361
3
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1362
2.32k
  if (errorCount())
1363
13
    return;
1364
2.31k
1365
2.31k
  // Use default entry point name if no name was given via the command
1366
2.31k
  // line nor linker scripts. For some reason, MIPS entry point name is
1367
2.31k
  // different from others.
1368
2.31k
  Config->WarnMissingEntry =
1369
2.31k
      (!Config->Entry.empty() || 
(2.26k
!Config->Shared2.26k
&&
!Config->Relocatable1.42k
));
1370
2.31k
  if (Config->Entry.empty() && 
!Config->Relocatable2.26k
)
1371
2.19k
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"161
:
"_start"2.03k
;
1372
2.31k
1373
2.31k
  // Handle --trace-symbol.
1374
2.31k
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1375
34
    Symtab->trace(Arg->getValue());
1376
2.31k
1377
2.31k
  // Add all files to the symbol table. This will add almost all
1378
2.31k
  // symbols that we need to the symbol table.
1379
2.31k
  for (InputFile *F : Files)
1380
3.21k
    Symtab->addFile<ELFT>(F);
1381
2.31k
1382
2.31k
  // Now that we have every file, we can decide if we will need a
1383
2.31k
  // dynamic symbol table.
1384
2.31k
  // We need one if we were asked to export dynamic symbols or if we are
1385
2.31k
  // producing a shared library.
1386
2.31k
  // We also need one if any shared libraries are used and for pie executables
1387
2.31k
  // (probably because the dynamic linker needs it).
1388
2.31k
  Config->HasDynSymTab =
1389
2.31k
      !SharedFiles.empty() || 
Config->Pic1.99k
||
Config->ExportDynamic1.16k
;
1390
2.31k
1391
2.31k
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1392
2.31k
  // are undefined symbols for them, so we add these to trigger that logic.
1393
2.31k
  for (StringRef Sym : Script->ReferencedSymbols)
1394
75
    Symtab->addUndefined<ELFT>(Sym);
1395
2.31k
1396
2.31k
  // Handle the `--undefined <sym>` options.
1397
2.31k
  for (StringRef S : Config->Undefined)
1398
26
    handleUndefined<ELFT>(S);
1399
2.31k
1400
2.31k
  // If an entry symbol is in a static archive, pull out that file now.
1401
2.31k
  handleUndefined<ELFT>(Config->Entry);
1402
2.31k
1403
2.31k
  // If any of our inputs are bitcode files, the LTO code generator may create
1404
2.31k
  // references to certain library functions that might not be explicit in the
1405
2.31k
  // bitcode file's symbol table. If any of those library functions are defined
1406
2.31k
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1407
2.31k
  // compile those archive members by adding them to the link beforehand.
1408
2.31k
  //
1409
2.31k
  // However, adding all libcall symbols to the link can have undesired
1410
2.31k
  // consequences. For example, the libgcc implementation of
1411
2.31k
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1412
2.31k
  // that aborts the program if the Linux kernel does not support 64-bit
1413
2.31k
  // atomics, which would prevent the program from running even if it does not
1414
2.31k
  // use 64-bit atomics.
1415
2.31k
  //
1416
2.31k
  // Therefore, we only add libcall symbols to the link before LTO if we have
1417
2.31k
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1418
2.31k
  // libcall symbols will be added to the link after LTO when we add the LTO
1419
2.31k
  // object file to the link.
1420
2.31k
  if (!BitcodeFiles.empty())
1421
164
    for (const char *S : LibcallRoutineNames)
1422
75.9k
      handleLibcall<ELFT>(S);
1423
2.31k
1424
2.31k
  // Return if there were name resolution errors.
1425
2.31k
  if (errorCount())
1426
52
    return;
1427
2.25k
1428
2.25k
  // Now when we read all script files, we want to finalize order of linker
1429
2.25k
  // script commands, which can be not yet final because of INSERT commands.
1430
2.25k
  Script->processInsertCommands();
1431
2.25k
1432
2.25k
  // We want to declare linker script's symbols early,
1433
2.25k
  // so that we can version them.
1434
2.25k
  // They also might be exported if referenced by DSOs.
1435
2.25k
  Script->declareSymbols();
1436
2.25k
1437
2.25k
  // Handle the -exclude-libs option.
1438
2.25k
  if (Args.hasArg(OPT_exclude_libs))
1439
8
    excludeLibs<ELFT>(Args);
1440
2.25k
1441
2.25k
  // Create ElfHeader early. We need a dummy section in
1442
2.25k
  // addReservedSymbols to mark the created symbols as not absolute.
1443
2.25k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1444
2.25k
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1445
2.25k
1446
2.25k
  // We need to create some reserved symbols such as _end. Create them.
1447
2.25k
  if (!Config->Relocatable)
1448
2.18k
    addReservedSymbols();
1449
2.25k
1450
2.25k
  // Apply version scripts.
1451
2.25k
  //
1452
2.25k
  // For a relocatable output, version scripts don't make sense, and
1453
2.25k
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1454
2.25k
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1455
2.25k
  if (!Config->Relocatable)
1456
2.18k
    Symtab->scanVersionScript();
1457
2.25k
1458
2.25k
  // Create wrapped symbols for -wrap option.
1459
2.25k
  for (auto *Arg : Args.filtered(OPT_wrap))
1460
14
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1461
2.25k
1462
2.25k
  // Do link-time optimization if given files are LLVM bitcode files.
1463
2.25k
  // This compiles bitcode files into real object files.
1464
2.25k
  //
1465
2.25k
  // With this the symbol table should be complete. After this, no new names
1466
2.25k
  // except a few linker-synthesized ones will be added to the symbol table.
1467
2.25k
  Symtab->addCombinedLTOObject<ELFT>();
1468
2.25k
  if (errorCount())
1469
13
    return;
1470
2.24k
1471
2.24k
  // If -thinlto-index-only is given, we should create only "index
1472
2.24k
  // files" and not object files. Index file creation is already done
1473
2.24k
  // in addCombinedLTOObject, so we are done if that's the case.
1474
2.24k
  if (Config->ThinLTOIndexOnly)
1475
10
    return;
1476
2.23k
1477
2.23k
  // Apply symbol renames for -wrap.
1478
2.23k
  Symtab->applySymbolWrap();
1479
2.23k
1480
2.23k
  // Now that we have a complete list of input files.
1481
2.23k
  // Beyond this point, no new files are added.
1482
2.23k
  // Aggregate all input sections into one place.
1483
2.23k
  for (InputFile *F : ObjectFiles)
1484
2.70k
    for (InputSectionBase *S : F->getSections())
1485
345k
      if (S && 
S != &InputSection::Discarded336k
)
1486
335k
        InputSections.push_back(S);
1487
2.23k
  for (BinaryFile *F : BinaryFiles)
1488
4
    for (InputSectionBase *S : F->getSections())
1489
4
      InputSections.push_back(cast<InputSection>(S));
1490
2.23k
1491
2.23k
  // We do not want to emit debug sections if --strip-all
1492
2.23k
  // or -strip-debug are given.
1493
2.23k
  if (Config->Strip != StripPolicy::None)
1494
11
    
llvm::erase_if(InputSections, [](InputSectionBase *S) 5
{
1495
11
      return S->Name.startswith(".debug") || 
S->Name.startswith(".zdebug")8
;
1496
11
    });
Unexecuted instantiation: void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Unexecuted instantiation: void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
1494
11
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1495
11
      return S->Name.startswith(".debug") || 
S->Name.startswith(".zdebug")8
;
1496
11
    });
Unexecuted instantiation: void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
1497
2.23k
1498
2.23k
  Config->EFlags = Target->calcEFlags();
1499
2.23k
1500
2.23k
  if (Config->EMachine == EM_ARM) {
1501
131
    // FIXME: These warnings can be removed when lld only uses these features
1502
131
    // when the input objects have been compiled with an architecture that
1503
131
    // supports them.
1504
131
    if (Config->ARMHasBlx == false)
1505
118
      warn("lld uses blx instruction, no object with architecture supporting "
1506
118
           "feature detected.");
1507
131
    if (Config->ARMJ1J2BranchEncoding == false)
1508
119
      warn("lld uses extended branch encoding, no object with architecture "
1509
119
           "supporting feature detected.");
1510
131
    if (Config->ARMHasMovtMovw == false)
1511
119
      warn("lld may use movt/movw, no object with architecture supporting "
1512
119
           "feature detected.");
1513
131
  }
1514
2.23k
1515
2.23k
  // This adds a .comment section containing a version string. We have to add it
1516
2.23k
  // before decompressAndMergeSections because the .comment section is a
1517
2.23k
  // mergeable section.
1518
2.23k
  if (!Config->Relocatable)
1519
2.16k
    InputSections.push_back(createCommentSection());
1520
2.23k
1521
2.23k
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1522
2.23k
  // and identical code folding.
1523
2.23k
  decompressSections();
1524
2.23k
  splitSections<ELFT>();
1525
2.23k
  markLive<ELFT>();
1526
2.23k
  demoteSymbols<ELFT>();
1527
2.23k
  mergeSections();
1528
2.23k
  if (Config->ICF != ICFLevel::None) {
1529
57
    findKeepUniqueSections<ELFT>(Args);
1530
57
    doIcf<ELFT>();
1531
57
  }
1532
2.23k
1533
2.23k
  // Read the callgraph now that we know what was gced or icfed
1534
2.23k
  if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1535
7
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1536
7
      readCallGraph(*Buffer);
1537
2.23k
1538
2.23k
  // Write the result to the file.
1539
2.23k
  writeResult<ELFT>();
1540
2.23k
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)
Line
Count
Source
1336
285
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1337
285
  Target = getTarget();
1338
285
1339
285
  Config->MaxPageSize = getMaxPageSize(Args);
1340
285
  Config->ImageBase = getImageBase(Args);
1341
285
1342
285
  // If a -hash-style option was not given, set to a default value,
1343
285
  // which varies depending on the target.
1344
285
  if (!Args.hasArg(OPT_hash_style)) {
1345
248
    if (Config->EMachine == EM_MIPS)
1346
17
      Config->SysvHash = true;
1347
231
    else
1348
231
      Config->SysvHash = Config->GnuHash = true;
1349
248
  }
1350
285
1351
285
  // Default output filename is "a.out" by the Unix tradition.
1352
285
  if (Config->OutputFile.empty())
1353
0
    Config->OutputFile = "a.out";
1354
285
1355
285
  // Fail early if the output file or map file is not writable. If a user has a
1356
285
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1357
285
  // find that it failed because there was a mistake in their command-line.
1358
285
  if (auto E = tryCreateFile(Config->OutputFile))
1359
0
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
1360
285
  if (auto E = tryCreateFile(Config->MapFile))
1361
0
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1362
285
  if (errorCount())
1363
0
    return;
1364
285
1365
285
  // Use default entry point name if no name was given via the command
1366
285
  // line nor linker scripts. For some reason, MIPS entry point name is
1367
285
  // different from others.
1368
285
  Config->WarnMissingEntry =
1369
285
      (!Config->Entry.empty() || 
(279
!Config->Shared279
&&
!Config->Relocatable179
));
1370
285
  if (Config->Entry.empty() && 
!Config->Relocatable279
)
1371
272
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"14
:
"_start"258
;
1372
285
1373
285
  // Handle --trace-symbol.
1374
285
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1375
0
    Symtab->trace(Arg->getValue());
1376
285
1377
285
  // Add all files to the symbol table. This will add almost all
1378
285
  // symbols that we need to the symbol table.
1379
285
  for (InputFile *F : Files)
1380
409
    Symtab->addFile<ELFT>(F);
1381
285
1382
285
  // Now that we have every file, we can decide if we will need a
1383
285
  // dynamic symbol table.
1384
285
  // We need one if we were asked to export dynamic symbols or if we are
1385
285
  // producing a shared library.
1386
285
  // We also need one if any shared libraries are used and for pie executables
1387
285
  // (probably because the dynamic linker needs it).
1388
285
  Config->HasDynSymTab =
1389
285
      !SharedFiles.empty() || 
Config->Pic241
||
Config->ExportDynamic139
;
1390
285
1391
285
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1392
285
  // are undefined symbols for them, so we add these to trigger that logic.
1393
285
  for (StringRef Sym : Script->ReferencedSymbols)
1394
0
    Symtab->addUndefined<ELFT>(Sym);
1395
285
1396
285
  // Handle the `--undefined <sym>` options.
1397
285
  for (StringRef S : Config->Undefined)
1398
0
    handleUndefined<ELFT>(S);
1399
285
1400
285
  // If an entry symbol is in a static archive, pull out that file now.
1401
285
  handleUndefined<ELFT>(Config->Entry);
1402
285
1403
285
  // If any of our inputs are bitcode files, the LTO code generator may create
1404
285
  // references to certain library functions that might not be explicit in the
1405
285
  // bitcode file's symbol table. If any of those library functions are defined
1406
285
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1407
285
  // compile those archive members by adding them to the link beforehand.
1408
285
  //
1409
285
  // However, adding all libcall symbols to the link can have undesired
1410
285
  // consequences. For example, the libgcc implementation of
1411
285
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1412
285
  // that aborts the program if the Linux kernel does not support 64-bit
1413
285
  // atomics, which would prevent the program from running even if it does not
1414
285
  // use 64-bit atomics.
1415
285
  //
1416
285
  // Therefore, we only add libcall symbols to the link before LTO if we have
1417
285
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1418
285
  // libcall symbols will be added to the link after LTO when we add the LTO
1419
285
  // object file to the link.
1420
285
  if (!BitcodeFiles.empty())
1421
1
    for (const char *S : LibcallRoutineNames)
1422
463
      handleLibcall<ELFT>(S);
1423
285
1424
285
  // Return if there were name resolution errors.
1425
285
  if (errorCount())
1426
16
    return;
1427
269
1428
269
  // Now when we read all script files, we want to finalize order of linker
1429
269
  // script commands, which can be not yet final because of INSERT commands.
1430
269
  Script->processInsertCommands();
1431
269
1432
269
  // We want to declare linker script's symbols early,
1433
269
  // so that we can version them.
1434
269
  // They also might be exported if referenced by DSOs.
1435
269
  Script->declareSymbols();
1436
269
1437
269
  // Handle the -exclude-libs option.
1438
269
  if (Args.hasArg(OPT_exclude_libs))
1439
0
    excludeLibs<ELFT>(Args);
1440
269
1441
269
  // Create ElfHeader early. We need a dummy section in
1442
269
  // addReservedSymbols to mark the created symbols as not absolute.
1443
269
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1444
269
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1445
269
1446
269
  // We need to create some reserved symbols such as _end. Create them.
1447
269
  if (!Config->Relocatable)
1448
262
    addReservedSymbols();
1449
269
1450
269
  // Apply version scripts.
1451
269
  //
1452
269
  // For a relocatable output, version scripts don't make sense, and
1453
269
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1454
269
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1455
269
  if (!Config->Relocatable)
1456
262
    Symtab->scanVersionScript();
1457
269
1458
269
  // Create wrapped symbols for -wrap option.
1459
269
  for (auto *Arg : Args.filtered(OPT_wrap))
1460
0
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1461
269
1462
269
  // Do link-time optimization if given files are LLVM bitcode files.
1463
269
  // This compiles bitcode files into real object files.
1464
269
  //
1465
269
  // With this the symbol table should be complete. After this, no new names
1466
269
  // except a few linker-synthesized ones will be added to the symbol table.
1467
269
  Symtab->addCombinedLTOObject<ELFT>();
1468
269
  if (errorCount())
1469
0
    return;
1470
269
1471
269
  // If -thinlto-index-only is given, we should create only "index
1472
269
  // files" and not object files. Index file creation is already done
1473
269
  // in addCombinedLTOObject, so we are done if that's the case.
1474
269
  if (Config->ThinLTOIndexOnly)
1475
0
    return;
1476
269
1477
269
  // Apply symbol renames for -wrap.
1478
269
  Symtab->applySymbolWrap();
1479
269
1480
269
  // Now that we have a complete list of input files.
1481
269
  // Beyond this point, no new files are added.
1482
269
  // Aggregate all input sections into one place.
1483
269
  for (InputFile *F : ObjectFiles)
1484
317
    for (InputSectionBase *S : F->getSections())
1485
2.32k
      if (S && 
S != &InputSection::Discarded1.06k
)
1486
1.05k
        InputSections.push_back(S);
1487
269
  for (BinaryFile *F : BinaryFiles)
1488
0
    for (InputSectionBase *S : F->getSections())
1489
0
      InputSections.push_back(cast<InputSection>(S));
1490
269
1491
269
  // We do not want to emit debug sections if --strip-all
1492
269
  // or -strip-debug are given.
1493
269
  if (Config->Strip != StripPolicy::None)
1494
0
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1495
0
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1496
0
    });
1497
269
1498
269
  Config->EFlags = Target->calcEFlags();
1499
269
1500
269
  if (Config->EMachine == EM_ARM) {
1501
131
    // FIXME: These warnings can be removed when lld only uses these features
1502
131
    // when the input objects have been compiled with an architecture that
1503
131
    // supports them.
1504
131
    if (Config->ARMHasBlx == false)
1505
118
      warn("lld uses blx instruction, no object with architecture supporting "
1506
118
           "feature detected.");
1507
131
    if (Config->ARMJ1J2BranchEncoding == false)
1508
119
      warn("lld uses extended branch encoding, no object with architecture "
1509
119
           "supporting feature detected.");
1510
131
    if (Config->ARMHasMovtMovw == false)
1511
119
      warn("lld may use movt/movw, no object with architecture supporting "
1512
119
           "feature detected.");
1513
131
  }
1514
269
1515
269
  // This adds a .comment section containing a version string. We have to add it
1516
269
  // before decompressAndMergeSections because the .comment section is a
1517
269
  // mergeable section.
1518
269
  if (!Config->Relocatable)
1519
262
    InputSections.push_back(createCommentSection());
1520
269
1521
269
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1522
269
  // and identical code folding.
1523
269
  decompressSections();
1524
269
  splitSections<ELFT>();
1525
269
  markLive<ELFT>();
1526
269
  demoteSymbols<ELFT>();
1527
269
  mergeSections();
1528
269
  if (Config->ICF != ICFLevel::None) {
1529
3
    findKeepUniqueSections<ELFT>(Args);
1530
3
    doIcf<ELFT>();
1531
3
  }
1532
269
1533
269
  // Read the callgraph now that we know what was gced or icfed
1534
269
  if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1535
0
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1536
0
      readCallGraph(*Buffer);
1537
269
1538
269
  // Write the result to the file.
1539
269
  writeResult<ELFT>();
1540
269
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)
Line
Count
Source
1336
120
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1337
120
  Target = getTarget();
1338
120
1339
120
  Config->MaxPageSize = getMaxPageSize(Args);
1340
120
  Config->ImageBase = getImageBase(Args);
1341
120
1342
120
  // If a -hash-style option was not given, set to a default value,
1343
120
  // which varies depending on the target.
1344
120
  if (!Args.hasArg(OPT_hash_style)) {
1345
119
    if (Config->EMachine == EM_MIPS)
1346
117
      Config->SysvHash = true;
1347
2
    else
1348
2
      Config->SysvHash = Config->GnuHash = true;
1349
119
  }
1350
120
1351
120
  // Default output filename is "a.out" by the Unix tradition.
1352
120
  if (Config->OutputFile.empty())
1353
1
    Config->OutputFile = "a.out";
1354
120
1355
120
  // Fail early if the output file or map file is not writable. If a user has a
1356
120
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1357
120
  // find that it failed because there was a mistake in their command-line.
1358
120
  if (auto E = tryCreateFile(Config->OutputFile))
1359
0
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
1360
120
  if (auto E = tryCreateFile(Config->MapFile))
1361
0
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1362
120
  if (errorCount())
1363
0
    return;
1364
120
1365
120
  // Use default entry point name if no name was given via the command
1366
120
  // line nor linker scripts. For some reason, MIPS entry point name is
1367
120
  // different from others.
1368
120
  Config->WarnMissingEntry =
1369
120
      (!Config->Entry.empty() || 
(118
!Config->Shared118
&&
!Config->Relocatable66
));
1370
120
  if (Config->Entry.empty() && 
!Config->Relocatable118
)
1371
109
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"106
:
"_start"3
;
1372
120
1373
120
  // Handle --trace-symbol.
1374
120
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1375
0
    Symtab->trace(Arg->getValue());
1376
120
1377
120
  // Add all files to the symbol table. This will add almost all
1378
120
  // symbols that we need to the symbol table.
1379
120
  for (InputFile *F : Files)
1380
182
    Symtab->addFile<ELFT>(F);
1381
120
1382
120
  // Now that we have every file, we can decide if we will need a
1383
120
  // dynamic symbol table.
1384
120
  // We need one if we were asked to export dynamic symbols or if we are
1385
120
  // producing a shared library.
1386
120
  // We also need one if any shared libraries are used and for pie executables
1387
120
  // (probably because the dynamic linker needs it).
1388
120
  Config->HasDynSymTab =
1389
120
      !SharedFiles.empty() || 
Config->Pic96
||
Config->ExportDynamic47
;
1390
120
1391
120
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1392
120
  // are undefined symbols for them, so we add these to trigger that logic.
1393
120
  for (StringRef Sym : Script->ReferencedSymbols)
1394
0
    Symtab->addUndefined<ELFT>(Sym);
1395
120
1396
120
  // Handle the `--undefined <sym>` options.
1397
120
  for (StringRef S : Config->Undefined)
1398
0
    handleUndefined<ELFT>(S);
1399
120
1400
120
  // If an entry symbol is in a static archive, pull out that file now.
1401
120
  handleUndefined<ELFT>(Config->Entry);
1402
120
1403
120
  // If any of our inputs are bitcode files, the LTO code generator may create
1404
120
  // references to certain library functions that might not be explicit in the
1405
120
  // bitcode file's symbol table. If any of those library functions are defined
1406
120
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1407
120
  // compile those archive members by adding them to the link beforehand.
1408
120
  //
1409
120
  // However, adding all libcall symbols to the link can have undesired
1410
120
  // consequences. For example, the libgcc implementation of
1411
120
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1412
120
  // that aborts the program if the Linux kernel does not support 64-bit
1413
120
  // atomics, which would prevent the program from running even if it does not
1414
120
  // use 64-bit atomics.
1415
120
  //
1416
120
  // Therefore, we only add libcall symbols to the link before LTO if we have
1417
120
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1418
120
  // libcall symbols will be added to the link after LTO when we add the LTO
1419
120
  // object file to the link.
1420
120
  if (!BitcodeFiles.empty())
1421
0
    for (const char *S : LibcallRoutineNames)
1422
0
      handleLibcall<ELFT>(S);
1423
120
1424
120
  // Return if there were name resolution errors.
1425
120
  if (errorCount())
1426
1
    return;
1427
119
1428
119
  // Now when we read all script files, we want to finalize order of linker
1429
119
  // script commands, which can be not yet final because of INSERT commands.
1430
119
  Script->processInsertCommands();
1431
119
1432
119
  // We want to declare linker script's symbols early,
1433
119
  // so that we can version them.
1434
119
  // They also might be exported if referenced by DSOs.
1435
119
  Script->declareSymbols();
1436
119
1437
119
  // Handle the -exclude-libs option.
1438
119
  if (Args.hasArg(OPT_exclude_libs))
1439
0
    excludeLibs<ELFT>(Args);
1440
119
1441
119
  // Create ElfHeader early. We need a dummy section in
1442
119
  // addReservedSymbols to mark the created symbols as not absolute.
1443
119
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1444
119
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1445
119
1446
119
  // We need to create some reserved symbols such as _end. Create them.
1447
119
  if (!Config->Relocatable)
1448
110
    addReservedSymbols();
1449
119
1450
119
  // Apply version scripts.
1451
119
  //
1452
119
  // For a relocatable output, version scripts don't make sense, and
1453
119
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1454
119
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1455
119
  if (!Config->Relocatable)
1456
110
    Symtab->scanVersionScript();
1457
119
1458
119
  // Create wrapped symbols for -wrap option.
1459
119
  for (auto *Arg : Args.filtered(OPT_wrap))
1460
0
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1461
119
1462
119
  // Do link-time optimization if given files are LLVM bitcode files.
1463
119
  // This compiles bitcode files into real object files.
1464
119
  //
1465
119
  // With this the symbol table should be complete. After this, no new names
1466
119
  // except a few linker-synthesized ones will be added to the symbol table.
1467
119
  Symtab->addCombinedLTOObject<ELFT>();
1468
119
  if (errorCount())
1469
0
    return;
1470
119
1471
119
  // If -thinlto-index-only is given, we should create only "index
1472
119
  // files" and not object files. Index file creation is already done
1473
119
  // in addCombinedLTOObject, so we are done if that's the case.
1474
119
  if (Config->ThinLTOIndexOnly)
1475
0
    return;
1476
119
1477
119
  // Apply symbol renames for -wrap.
1478
119
  Symtab->applySymbolWrap();
1479
119
1480
119
  // Now that we have a complete list of input files.
1481
119
  // Beyond this point, no new files are added.
1482
119
  // Aggregate all input sections into one place.
1483
119
  for (InputFile *F : ObjectFiles)
1484
157
    for (InputSectionBase *S : F->getSections())
1485
1.39k
      if (S && 
S != &InputSection::Discarded818
)
1486
818
        InputSections.push_back(S);
1487
119
  for (BinaryFile *F : BinaryFiles)
1488
0
    for (InputSectionBase *S : F->getSections())
1489
0
      InputSections.push_back(cast<InputSection>(S));
1490
119
1491
119
  // We do not want to emit debug sections if --strip-all
1492
119
  // or -strip-debug are given.
1493
119
  if (Config->Strip != StripPolicy::None)
1494
0
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1495
0
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1496
0
    });
1497
119
1498
119
  Config->EFlags = Target->calcEFlags();
1499
119
1500
119
  if (Config->EMachine == EM_ARM) {
1501
0
    // FIXME: These warnings can be removed when lld only uses these features
1502
0
    // when the input objects have been compiled with an architecture that
1503
0
    // supports them.
1504
0
    if (Config->ARMHasBlx == false)
1505
0
      warn("lld uses blx instruction, no object with architecture supporting "
1506
0
           "feature detected.");
1507
0
    if (Config->ARMJ1J2BranchEncoding == false)
1508
0
      warn("lld uses extended branch encoding, no object with architecture "
1509
0
           "supporting feature detected.");
1510
0
    if (Config->ARMHasMovtMovw == false)
1511
0
      warn("lld may use movt/movw, no object with architecture supporting "
1512
0
           "feature detected.");
1513
0
  }
1514
119
1515
119
  // This adds a .comment section containing a version string. We have to add it
1516
119
  // before decompressAndMergeSections because the .comment section is a
1517
119
  // mergeable section.
1518
119
  if (!Config->Relocatable)
1519
110
    InputSections.push_back(createCommentSection());
1520
119
1521
119
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1522
119
  // and identical code folding.
1523
119
  decompressSections();
1524
119
  splitSections<ELFT>();
1525
119
  markLive<ELFT>();
1526
119
  demoteSymbols<ELFT>();
1527
119
  mergeSections();
1528
119
  if (Config->ICF != ICFLevel::None) {
1529
0
    findKeepUniqueSections<ELFT>(Args);
1530
0
    doIcf<ELFT>();
1531
0
  }
1532
119
1533
119
  // Read the callgraph now that we know what was gced or icfed
1534
119
  if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1535
0
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1536
0
      readCallGraph(*Buffer);
1537
119
1538
119
  // Write the result to the file.
1539
119
  writeResult<ELFT>();
1540
119
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)
Line
Count
Source
1336
1.82k
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1337
1.82k
  Target = getTarget();
1338
1.82k
1339
1.82k
  Config->MaxPageSize = getMaxPageSize(Args);
1340
1.82k
  Config->ImageBase = getImageBase(Args);
1341
1.82k
1342
1.82k
  // If a -hash-style option was not given, set to a default value,
1343
1.82k
  // which varies depending on the target.
1344
1.82k
  if (!Args.hasArg(OPT_hash_style)) {
1345
1.72k
    if (Config->EMachine == EM_MIPS)
1346
2
      Config->SysvHash = true;
1347
1.72k
    else
1348
1.72k
      Config->SysvHash = Config->GnuHash = true;
1349
1.72k
  }
1350
1.82k
1351
1.82k
  // Default output filename is "a.out" by the Unix tradition.
1352
1.82k
  if (Config->OutputFile.empty())
1353
5
    Config->OutputFile = "a.out";
1354
1.82k
1355
1.82k
  // Fail early if the output file or map file is not writable. If a user has a
1356
1.82k
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1357
1.82k
  // find that it failed because there was a mistake in their command-line.
1358
1.82k
  if (auto E = tryCreateFile(Config->OutputFile))
1359
8
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
1360
1.82k
  if (auto E = tryCreateFile(Config->MapFile))
1361
3
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1362
1.82k
  if (errorCount())
1363
13
    return;
1364
1.81k
1365
1.81k
  // Use default entry point name if no name was given via the command
1366
1.81k
  // line nor linker scripts. For some reason, MIPS entry point name is
1367
1.81k
  // different from others.
1368
1.81k
  Config->WarnMissingEntry =
1369
1.81k
      (!Config->Entry.empty() || 
(1.78k
!Config->Shared1.78k
&&
!Config->Relocatable1.13k
));
1370
1.81k
  if (Config->Entry.empty() && 
!Config->Relocatable1.78k
)
1371
1.72k
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"0
: "_start";
1372
1.81k
1373
1.81k
  // Handle --trace-symbol.
1374
1.81k
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1375
34
    Symtab->trace(Arg->getValue());
1376
1.81k
1377
1.81k
  // Add all files to the symbol table. This will add almost all
1378
1.81k
  // symbols that we need to the symbol table.
1379
1.81k
  for (InputFile *F : Files)
1380
2.50k
    Symtab->addFile<ELFT>(F);
1381
1.81k
1382
1.81k
  // Now that we have every file, we can decide if we will need a
1383
1.81k
  // dynamic symbol table.
1384
1.81k
  // We need one if we were asked to export dynamic symbols or if we are
1385
1.81k
  // producing a shared library.
1386
1.81k
  // We also need one if any shared libraries are used and for pie executables
1387
1.81k
  // (probably because the dynamic linker needs it).
1388
1.81k
  Config->HasDynSymTab =
1389
1.81k
      !SharedFiles.empty() || 
Config->Pic1.58k
||
Config->ExportDynamic946
;
1390
1.81k
1391
1.81k
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1392
1.81k
  // are undefined symbols for them, so we add these to trigger that logic.
1393
1.81k
  for (StringRef Sym : Script->ReferencedSymbols)
1394
71
    Symtab->addUndefined<ELFT>(Sym);
1395
1.81k
1396
1.81k
  // Handle the `--undefined <sym>` options.
1397
1.81k
  for (StringRef S : Config->Undefined)
1398
26
    handleUndefined<ELFT>(S);
1399
1.81k
1400
1.81k
  // If an entry symbol is in a static archive, pull out that file now.
1401
1.81k
  handleUndefined<ELFT>(Config->Entry);
1402
1.81k
1403
1.81k
  // If any of our inputs are bitcode files, the LTO code generator may create
1404
1.81k
  // references to certain library functions that might not be explicit in the
1405
1.81k
  // bitcode file's symbol table. If any of those library functions are defined
1406
1.81k
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1407
1.81k
  // compile those archive members by adding them to the link beforehand.
1408
1.81k
  //
1409
1.81k
  // However, adding all libcall symbols to the link can have undesired
1410
1.81k
  // consequences. For example, the libgcc implementation of
1411
1.81k
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1412
1.81k
  // that aborts the program if the Linux kernel does not support 64-bit
1413
1.81k
  // atomics, which would prevent the program from running even if it does not
1414
1.81k
  // use 64-bit atomics.
1415
1.81k
  //
1416
1.81k
  // Therefore, we only add libcall symbols to the link before LTO if we have
1417
1.81k
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1418
1.81k
  // libcall symbols will be added to the link after LTO when we add the LTO
1419
1.81k
  // object file to the link.
1420
1.81k
  if (!BitcodeFiles.empty())
1421
163
    for (const char *S : LibcallRoutineNames)
1422
75.4k
      handleLibcall<ELFT>(S);
1423
1.81k
1424
1.81k
  // Return if there were name resolution errors.
1425
1.81k
  if (errorCount())
1426
31
    return;
1427
1.78k
1428
1.78k
  // Now when we read all script files, we want to finalize order of linker
1429
1.78k
  // script commands, which can be not yet final because of INSERT commands.
1430
1.78k
  Script->processInsertCommands();
1431
1.78k
1432
1.78k
  // We want to declare linker script's symbols early,
1433
1.78k
  // so that we can version them.
1434
1.78k
  // They also might be exported if referenced by DSOs.
1435
1.78k
  Script->declareSymbols();
1436
1.78k
1437
1.78k
  // Handle the -exclude-libs option.
1438
1.78k
  if (Args.hasArg(OPT_exclude_libs))
1439
8
    excludeLibs<ELFT>(Args);
1440
1.78k
1441
1.78k
  // Create ElfHeader early. We need a dummy section in
1442
1.78k
  // addReservedSymbols to mark the created symbols as not absolute.
1443
1.78k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1444
1.78k
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1445
1.78k
1446
1.78k
  // We need to create some reserved symbols such as _end. Create them.
1447
1.78k
  if (!Config->Relocatable)
1448
1.73k
    addReservedSymbols();
1449
1.78k
1450
1.78k
  // Apply version scripts.
1451
1.78k
  //
1452
1.78k
  // For a relocatable output, version scripts don't make sense, and
1453
1.78k
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1454
1.78k
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1455
1.78k
  if (!Config->Relocatable)
1456
1.73k
    Symtab->scanVersionScript();
1457
1.78k
1458
1.78k
  // Create wrapped symbols for -wrap option.
1459
1.78k
  for (auto *Arg : Args.filtered(OPT_wrap))
1460
14
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1461
1.78k
1462
1.78k
  // Do link-time optimization if given files are LLVM bitcode files.
1463
1.78k
  // This compiles bitcode files into real object files.
1464
1.78k
  //
1465
1.78k
  // With this the symbol table should be complete. After this, no new names
1466
1.78k
  // except a few linker-synthesized ones will be added to the symbol table.
1467
1.78k
  Symtab->addCombinedLTOObject<ELFT>();
1468
1.78k
  if (errorCount())
1469
13
    return;
1470
1.77k
1471
1.77k
  // If -thinlto-index-only is given, we should create only "index
1472
1.77k
  // files" and not object files. Index file creation is already done
1473
1.77k
  // in addCombinedLTOObject, so we are done if that's the case.
1474
1.77k
  if (Config->ThinLTOIndexOnly)
1475
10
    return;
1476
1.76k
1477
1.76k
  // Apply symbol renames for -wrap.
1478
1.76k
  Symtab->applySymbolWrap();
1479
1.76k
1480
1.76k
  // Now that we have a complete list of input files.
1481
1.76k
  // Beyond this point, no new files are added.
1482
1.76k
  // Aggregate all input sections into one place.
1483
1.76k
  for (InputFile *F : ObjectFiles)
1484
2.12k
    for (InputSectionBase *S : F->getSections())
1485
341k
      if (S && 
S != &InputSection::Discarded334k
)
1486
333k
        InputSections.push_back(S);
1487
1.76k
  for (BinaryFile *F : BinaryFiles)
1488
4
    for (InputSectionBase *S : F->getSections())
1489
4
      InputSections.push_back(cast<InputSection>(S));
1490
1.76k
1491
1.76k
  // We do not want to emit debug sections if --strip-all
1492
1.76k
  // or -strip-debug are given.
1493
1.76k
  if (Config->Strip != StripPolicy::None)
1494
5
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1495
5
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1496
5
    });
1497
1.76k
1498
1.76k
  Config->EFlags = Target->calcEFlags();
1499
1.76k
1500
1.76k
  if (Config->EMachine == EM_ARM) {
1501
0
    // FIXME: These warnings can be removed when lld only uses these features
1502
0
    // when the input objects have been compiled with an architecture that
1503
0
    // supports them.
1504
0
    if (Config->ARMHasBlx == false)
1505
0
      warn("lld uses blx instruction, no object with architecture supporting "
1506
0
           "feature detected.");
1507
0
    if (Config->ARMJ1J2BranchEncoding == false)
1508
0
      warn("lld uses extended branch encoding, no object with architecture "
1509
0
           "supporting feature detected.");
1510
0
    if (Config->ARMHasMovtMovw == false)
1511
0
      warn("lld may use movt/movw, no object with architecture supporting "
1512
0
           "feature detected.");
1513
0
  }
1514
1.76k
1515
1.76k
  // This adds a .comment section containing a version string. We have to add it
1516
1.76k
  // before decompressAndMergeSections because the .comment section is a
1517
1.76k
  // mergeable section.
1518
1.76k
  if (!Config->Relocatable)
1519
1.70k
    InputSections.push_back(createCommentSection());
1520
1.76k
1521
1.76k
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1522
1.76k
  // and identical code folding.
1523
1.76k
  decompressSections();
1524
1.76k
  splitSections<ELFT>();
1525
1.76k
  markLive<ELFT>();
1526
1.76k
  demoteSymbols<ELFT>();
1527
1.76k
  mergeSections();
1528
1.76k
  if (Config->ICF != ICFLevel::None) {
1529
54
    findKeepUniqueSections<ELFT>(Args);
1530
54
    doIcf<ELFT>();
1531
54
  }
1532
1.76k
1533
1.76k
  // Read the callgraph now that we know what was gced or icfed
1534
1.76k
  if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1535
7
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1536
7
      readCallGraph(*Buffer);
1537
1.76k
1538
1.76k
  // Write the result to the file.
1539
1.76k
  writeResult<ELFT>();
1540
1.76k
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)
Line
Count
Source
1336
89
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1337
89
  Target = getTarget();
1338
89
1339
89
  Config->MaxPageSize = getMaxPageSize(Args);
1340
89
  Config->ImageBase = getImageBase(Args);
1341
89
1342
89
  // If a -hash-style option was not given, set to a default value,
1343
89
  // which varies depending on the target.
1344
89
  if (!Args.hasArg(OPT_hash_style)) {
1345
88
    if (Config->EMachine == EM_MIPS)
1346
45
      Config->SysvHash = true;
1347
43
    else
1348
43
      Config->SysvHash = Config->GnuHash = true;
1349
88
  }
1350
89
1351
89
  // Default output filename is "a.out" by the Unix tradition.
1352
89
  if (Config->OutputFile.empty())
1353
0
    Config->OutputFile = "a.out";
1354
89
1355
89
  // Fail early if the output file or map file is not writable. If a user has a
1356
89
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1357
89
  // find that it failed because there was a mistake in their command-line.
1358
89
  if (auto E = tryCreateFile(Config->OutputFile))
1359
0
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
1360
89
  if (auto E = tryCreateFile(Config->MapFile))
1361
0
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1362
89
  if (errorCount())
1363
0
    return;
1364
89
1365
89
  // Use default entry point name if no name was given via the command
1366
89
  // line nor linker scripts. For some reason, MIPS entry point name is
1367
89
  // different from others.
1368
89
  Config->WarnMissingEntry =
1369
89
      (!Config->Entry.empty() || 
(87
!Config->Shared87
&&
!Config->Relocatable46
));
1370
89
  if (Config->Entry.empty() && 
!Config->Relocatable87
)
1371
85
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"41
:
"_start"44
;
1372
89
1373
89
  // Handle --trace-symbol.
1374
89
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1375
0
    Symtab->trace(Arg->getValue());
1376
89
1377
89
  // Add all files to the symbol table. This will add almost all
1378
89
  // symbols that we need to the symbol table.
1379
89
  for (InputFile *F : Files)
1380
125
    Symtab->addFile<ELFT>(F);
1381
89
1382
89
  // Now that we have every file, we can decide if we will need a
1383
89
  // dynamic symbol table.
1384
89
  // We need one if we were asked to export dynamic symbols or if we are
1385
89
  // producing a shared library.
1386
89
  // We also need one if any shared libraries are used and for pie executables
1387
89
  // (probably because the dynamic linker needs it).
1388
89
  Config->HasDynSymTab =
1389
89
      !SharedFiles.empty() || 
Config->Pic72
||
Config->ExportDynamic32
;
1390
89
1391
89
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1392
89
  // are undefined symbols for them, so we add these to trigger that logic.
1393
89
  for (StringRef Sym : Script->ReferencedSymbols)
1394
4
    Symtab->addUndefined<ELFT>(Sym);
1395
89
1396
89
  // Handle the `--undefined <sym>` options.
1397
89
  for (StringRef S : Config->Undefined)
1398
0
    handleUndefined<ELFT>(S);
1399
89
1400
89
  // If an entry symbol is in a static archive, pull out that file now.
1401
89
  handleUndefined<ELFT>(Config->Entry);
1402
89
1403
89
  // If any of our inputs are bitcode files, the LTO code generator may create
1404
89
  // references to certain library functions that might not be explicit in the
1405
89
  // bitcode file's symbol table. If any of those library functions are defined
1406
89
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1407
89
  // compile those archive members by adding them to the link beforehand.
1408
89
  //
1409
89
  // However, adding all libcall symbols to the link can have undesired
1410
89
  // consequences. For example, the libgcc implementation of
1411
89
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1412
89
  // that aborts the program if the Linux kernel does not support 64-bit
1413
89
  // atomics, which would prevent the program from running even if it does not
1414
89
  // use 64-bit atomics.
1415
89
  //
1416
89
  // Therefore, we only add libcall symbols to the link before LTO if we have
1417
89
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1418
89
  // libcall symbols will be added to the link after LTO when we add the LTO
1419
89
  // object file to the link.
1420
89
  if (!BitcodeFiles.empty())
1421
0
    for (const char *S : LibcallRoutineNames)
1422
0
      handleLibcall<ELFT>(S);
1423
89
1424
89
  // Return if there were name resolution errors.
1425
89
  if (errorCount())
1426
4
    return;
1427
85
1428
85
  // Now when we read all script files, we want to finalize order of linker
1429
85
  // script commands, which can be not yet final because of INSERT commands.
1430
85
  Script->processInsertCommands();
1431
85
1432
85
  // We want to declare linker script's symbols early,
1433
85
  // so that we can version them.
1434
85
  // They also might be exported if referenced by DSOs.
1435
85
  Script->declareSymbols();
1436
85
1437
85
  // Handle the -exclude-libs option.
1438
85
  if (Args.hasArg(OPT_exclude_libs))
1439
0
    excludeLibs<ELFT>(Args);
1440
85
1441
85
  // Create ElfHeader early. We need a dummy section in
1442
85
  // addReservedSymbols to mark the created symbols as not absolute.
1443
85
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1444
85
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1445
85
1446
85
  // We need to create some reserved symbols such as _end. Create them.
1447
85
  if (!Config->Relocatable)
1448
83
    addReservedSymbols();
1449
85
1450
85
  // Apply version scripts.
1451
85
  //
1452
85
  // For a relocatable output, version scripts don't make sense, and
1453
85
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1454
85
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1455
85
  if (!Config->Relocatable)
1456
83
    Symtab->scanVersionScript();
1457
85
1458
85
  // Create wrapped symbols for -wrap option.
1459
85
  for (auto *Arg : Args.filtered(OPT_wrap))
1460
0
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1461
85
1462
85
  // Do link-time optimization if given files are LLVM bitcode files.
1463
85
  // This compiles bitcode files into real object files.
1464
85
  //
1465
85
  // With this the symbol table should be complete. After this, no new names
1466
85
  // except a few linker-synthesized ones will be added to the symbol table.
1467
85
  Symtab->addCombinedLTOObject<ELFT>();
1468
85
  if (errorCount())
1469
0
    return;
1470
85
1471
85
  // If -thinlto-index-only is given, we should create only "index
1472
85
  // files" and not object files. Index file creation is already done
1473
85
  // in addCombinedLTOObject, so we are done if that's the case.
1474
85
  if (Config->ThinLTOIndexOnly)
1475
0
    return;
1476
85
1477
85
  // Apply symbol renames for -wrap.
1478
85
  Symtab->applySymbolWrap();
1479
85
1480
85
  // Now that we have a complete list of input files.
1481
85
  // Beyond this point, no new files are added.
1482
85
  // Aggregate all input sections into one place.
1483
85
  for (InputFile *F : ObjectFiles)
1484
103
    for (InputSectionBase *S : F->getSections())
1485
748
      if (S && 
S != &InputSection::Discarded347
)
1486
347
        InputSections.push_back(S);
1487
85
  for (BinaryFile *F : BinaryFiles)
1488
0
    for (InputSectionBase *S : F->getSections())
1489
0
      InputSections.push_back(cast<InputSection>(S));
1490
85
1491
85
  // We do not want to emit debug sections if --strip-all
1492
85
  // or -strip-debug are given.
1493
85
  if (Config->Strip != StripPolicy::None)
1494
0
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1495
0
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1496
0
    });
1497
85
1498
85
  Config->EFlags = Target->calcEFlags();
1499
85
1500
85
  if (Config->EMachine == EM_ARM) {
1501
0
    // FIXME: These warnings can be removed when lld only uses these features
1502
0
    // when the input objects have been compiled with an architecture that
1503
0
    // supports them.
1504
0
    if (Config->ARMHasBlx == false)
1505
0
      warn("lld uses blx instruction, no object with architecture supporting "
1506
0
           "feature detected.");
1507
0
    if (Config->ARMJ1J2BranchEncoding == false)
1508
0
      warn("lld uses extended branch encoding, no object with architecture "
1509
0
           "supporting feature detected.");
1510
0
    if (Config->ARMHasMovtMovw == false)
1511
0
      warn("lld may use movt/movw, no object with architecture supporting "
1512
0
           "feature detected.");
1513
0
  }
1514
85
1515
85
  // This adds a .comment section containing a version string. We have to add it
1516
85
  // before decompressAndMergeSections because the .comment section is a
1517
85
  // mergeable section.
1518
85
  if (!Config->Relocatable)
1519
83
    InputSections.push_back(createCommentSection());
1520
85
1521
85
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1522
85
  // and identical code folding.
1523
85
  decompressSections();
1524
85
  splitSections<ELFT>();
1525
85
  markLive<ELFT>();
1526
85
  demoteSymbols<ELFT>();
1527
85
  mergeSections();
1528
85
  if (Config->ICF != ICFLevel::None) {
1529
0
    findKeepUniqueSections<ELFT>(Args);
1530
0
    doIcf<ELFT>();
1531
0
  }
1532
85
1533
85
  // Read the callgraph now that we know what was gced or icfed
1534
85
  if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1535
0
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1536
0
      readCallGraph(*Buffer);
1537
85
1538
85
  // Write the result to the file.
1539
85
  writeResult<ELFT>();
1540
85
}