Coverage Report

Created: 2018-10-23 15:26

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