Coverage Report

Created: 2019-01-21 03:01

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