Coverage Report

Created: 2019-07-24 05:18

/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 "ICF.h"
28
#include "InputFiles.h"
29
#include "InputSection.h"
30
#include "LinkerScript.h"
31
#include "MarkLive.h"
32
#include "OutputSections.h"
33
#include "ScriptParser.h"
34
#include "SymbolTable.h"
35
#include "Symbols.h"
36
#include "SyntheticSections.h"
37
#include "Target.h"
38
#include "Writer.h"
39
#include "lld/Common/Args.h"
40
#include "lld/Common/Driver.h"
41
#include "lld/Common/ErrorHandler.h"
42
#include "lld/Common/Filesystem.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/GlobPattern.h"
54
#include "llvm/Support/LEB128.h"
55
#include "llvm/Support/Path.h"
56
#include "llvm/Support/TarWriter.h"
57
#include "llvm/Support/TargetSelect.h"
58
#include "llvm/Support/raw_ostream.h"
59
#include <cstdlib>
60
#include <utility>
61
62
using namespace llvm;
63
using namespace llvm::ELF;
64
using namespace llvm::object;
65
using namespace llvm::sys;
66
using namespace llvm::support;
67
68
using namespace lld;
69
using namespace lld::elf;
70
71
Configuration *elf::config;
72
LinkerDriver *elf::driver;
73
74
static void setConfigs(opt::InputArgList &args);
75
static void readConfigs(opt::InputArgList &args);
76
77
bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
78
3.03k
               raw_ostream &error) {
79
3.03k
  errorHandler().logName = args::getFilenameWithoutExe(args[0]);
80
3.03k
  errorHandler().errorLimitExceededMsg =
81
3.03k
      "too many errors emitted, stopping now (use "
82
3.03k
      "-error-limit=0 to see all errors)";
83
3.03k
  errorHandler().errorOS = &error;
84
3.03k
  errorHandler().exitEarly = canExitEarly;
85
3.03k
  errorHandler().colorDiagnostics = error.has_colors();
86
3.03k
87
3.03k
  inputSections.clear();
88
3.03k
  outputSections.clear();
89
3.03k
  binaryFiles.clear();
90
3.03k
  bitcodeFiles.clear();
91
3.03k
  objectFiles.clear();
92
3.03k
  sharedFiles.clear();
93
3.03k
94
3.03k
  config = make<Configuration>();
95
3.03k
  driver = make<LinkerDriver>();
96
3.03k
  script = make<LinkerScript>();
97
3.03k
  symtab = make<SymbolTable>();
98
3.03k
99
3.03k
  tar = nullptr;
100
3.03k
  memset(&in, 0, sizeof(in));
101
3.03k
102
3.03k
  partitions = {Partition()};
103
3.03k
104
3.03k
  SharedFile::vernauxNum = 0;
105
3.03k
106
3.03k
  config->progName = args[0];
107
3.03k
108
3.03k
  driver->main(args);
109
3.03k
110
3.03k
  // Exit immediately if we don't need to return to the caller.
111
3.03k
  // This saves time because the overhead of calling destructors
112
3.03k
  // for all globally-allocated objects is not negligible.
113
3.03k
  if (canExitEarly)
114
0
    exitLld(errorCount() ? 1 : 0);
115
3.03k
116
3.03k
  freeArena();
117
3.03k
  return !errorCount();
118
3.03k
}
119
120
// Parses a linker -m option.
121
43
static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
122
43
  uint8_t osabi = 0;
123
43
  StringRef s = emul;
124
43
  if (s.endswith("_fbsd")) {
125
4
    s = s.drop_back(5);
126
4
    osabi = ELFOSABI_FREEBSD;
127
4
  }
128
43
129
43
  std::pair<ELFKind, uint16_t> ret =
130
43
      StringSwitch<std::pair<ELFKind, uint16_t>>(s)
131
43
          .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
132
43
                 {ELF64LEKind, EM_AARCH64})
133
43
          .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
134
43
          .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
135
43
          .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
136
43
          .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
137
43
          .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
138
43
          .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
139
43
          .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
140
43
          .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
141
43
          .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
142
43
          .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
143
43
          .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
144
43
          .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
145
43
          .Case("elf_i386", {ELF32LEKind, EM_386})
146
43
          .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
147
43
          .Default({ELFNoneKind, EM_NONE});
148
43
149
43
  if (ret.first == ELFNoneKind)
150
2
    error("unknown emulation: " + emul);
151
43
  return std::make_tuple(ret.first, ret.second, osabi);
152
43
}
153
154
// Returns slices of MB by parsing MB as an archive file.
155
// Each slice consists of a member file in the archive.
156
std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
157
29
    MemoryBufferRef mb) {
158
29
  std::unique_ptr<Archive> file =
159
29
      CHECK(Archive::create(mb),
160
29
            mb.getBufferIdentifier() + ": failed to parse archive");
161
29
162
29
  std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
163
29
  Error err = Error::success();
164
29
  bool addToTar = file->isThin() && 
tar2
;
165
34
  for (const ErrorOr<Archive::Child> &cOrErr : file->children(err)) {
166
34
    Archive::Child c =
167
34
        CHECK(cOrErr, mb.getBufferIdentifier() +
168
34
                          ": could not get the child of the archive");
169
34
    MemoryBufferRef mbref =
170
34
        CHECK(c.getMemoryBufferRef(),
171
34
              mb.getBufferIdentifier() +
172
34
                  ": could not get the buffer for a child of the archive");
173
34
    if (addToTar)
174
1
      tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
175
34
    v.push_back(std::make_pair(mbref, c.getChildOffset()));
176
34
  }
177
29
  if (err)
178
0
    fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
179
0
          toString(std::move(err)));
180
29
181
29
  // Take ownership of memory buffers created for members of thin archives.
182
29
  for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
183
2
    make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
184
29
185
29
  return v;
186
29
}
187
188
// Opens a file and create a file object. Path has to be resolved already.
189
4.30k
void LinkerDriver::addFile(StringRef path, bool withLOption) {
190
4.30k
  using namespace sys::fs;
191
4.30k
192
4.30k
  Optional<MemoryBufferRef> buffer = readFile(path);
193
4.30k
  if (!buffer.hasValue())
194
90
    return;
195
4.21k
  MemoryBufferRef mbref = *buffer;
196
4.21k
197
4.21k
  if (config->formatBinary) {
198
8
    files.push_back(make<BinaryFile>(mbref));
199
8
    return;
200
8
  }
201
4.20k
202
4.20k
  switch (identify_magic(mbref.getBuffer())) {
203
4.20k
  case file_magic::unknown:
204
95
    readLinkerScript(mbref);
205
95
    return;
206
4.20k
  case file_magic::archive: {
207
146
    // Handle -whole-archive.
208
146
    if (inWholeArchive) {
209
19
      for (const auto &p : getArchiveMembers(mbref))
210
22
        files.push_back(createObjectFile(p.first, path, p.second));
211
19
      return;
212
19
    }
213
127
214
127
    std::unique_ptr<Archive> file =
215
127
        CHECK(Archive::create(mbref), path + ": failed to parse archive");
216
127
217
127
    // If an archive file has no symbol table, it is likely that a user
218
127
    // is attempting LTO and using a default ar command that doesn't
219
127
    // understand the LLVM bitcode file. It is a pretty common error, so
220
127
    // we'll handle it as if it had a symbol table.
221
127
    if (!file->isEmpty() && !file->hasSymbolTable()) {
222
6
      // Check if all members are bitcode files. If not, ignore, which is the
223
6
      // default action without the LTO hack described above.
224
6
      for (const std::pair<MemoryBufferRef, uint64_t> &p :
225
6
           getArchiveMembers(mbref))
226
7
        if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
227
2
          error(path + ": archive has no index; run ranlib to add one");
228
2
          return;
229
2
        }
230
6
231
6
      for (const std::pair<MemoryBufferRef, uint64_t> &p :
232
4
           getArchiveMembers(mbref))
233
5
        files.push_back(make<LazyObjFile>(p.first, path, p.second));
234
4
      return;
235
121
    }
236
121
237
121
    // Handle the regular case.
238
121
    files.push_back(make<ArchiveFile>(std::move(file)));
239
121
    return;
240
121
  }
241
413
  case file_magic::elf_shared_object:
242
413
    if (config->isStatic || 
config->relocatable412
) {
243
2
      error("attempted static link of dynamic object " + path);
244
2
      return;
245
2
    }
246
411
247
411
    // DSOs usually have DT_SONAME tags in their ELF headers, and the
248
411
    // sonames are used to identify DSOs. But if they are missing,
249
411
    // they are identified by filenames. We don't know whether the new
250
411
    // file has a DT_SONAME or not because we haven't parsed it yet.
251
411
    // Here, we set the default soname for the file because we might
252
411
    // need it later.
253
411
    //
254
411
    // If a file was specified by -lfoo, the directory part is not
255
411
    // significant, as a user did not specify it. This behavior is
256
411
    // compatible with GNU.
257
411
    files.push_back(
258
411
        make<SharedFile>(mbref, withLOption ? 
path::filename(path)16
:
path395
));
259
411
    return;
260
3.55k
  case file_magic::bitcode:
261
3.55k
  case file_magic::elf_relocatable:
262
3.55k
    if (inLib)
263
25
      files.push_back(make<LazyObjFile>(mbref, "", 0));
264
3.52k
    else
265
3.52k
      files.push_back(createObjectFile(mbref));
266
3.55k
    break;
267
3.55k
  default:
268
2
    error(path + ": unknown file type");
269
4.20k
  }
270
4.20k
}
271
272
// Add a given library by searching it from input search paths.
273
36
void LinkerDriver::addLibrary(StringRef name) {
274
36
  if (Optional<std::string> path = searchLibrary(name))
275
27
    addFile(*path, /*withLOption=*/true);
276
9
  else
277
9
    error("unable to find library -l" + name);
278
36
}
279
280
// This function is called on startup. We need this for LTO since
281
// LTO calls LLVM functions to compile bitcode files to native code.
282
// Technically this can be delayed until we read bitcode files, but
283
// we don't bother to do lazily because the initialization is fast.
284
3.02k
static void initLLVM() {
285
3.02k
  InitializeAllTargets();
286
3.02k
  InitializeAllTargetMCs();
287
3.02k
  InitializeAllAsmPrinters();
288
3.02k
  InitializeAllAsmParsers();
289
3.02k
}
290
291
// Some command line options or some combinations of them are not allowed.
292
// This function checks for such errors.
293
2.86k
static void checkOptions() {
294
2.86k
  // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
295
2.86k
  // table which is a relatively new feature.
296
2.86k
  if (config->emachine == EM_MIPS && 
config->gnuHash202
)
297
2
    error("the .gnu.hash section is not compatible with the MIPS target");
298
2.86k
299
2.86k
  if (config->fixCortexA53Errata843419 && 
config->emachine != EM_AARCH649
)
300
1
    error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
301
2.86k
302
2.86k
  if (config->tocOptimize && 
config->emachine != EM_PPC64147
)
303
1
    error("--toc-optimize is only supported on the PowerPC64 target");
304
2.86k
305
2.86k
  if (config->pie && 
config->shared85
)
306
1
    error("-shared and -pie may not be used together");
307
2.86k
308
2.86k
  if (!config->shared && 
!config->filterList.empty()1.90k
)
309
1
    error("-F may not be used without -shared");
310
2.86k
311
2.86k
  if (!config->shared && 
!config->auxiliaryList.empty()1.90k
)
312
1
    error("-f may not be used without -shared");
313
2.86k
314
2.86k
  if (!config->relocatable && 
!config->defineCommon2.77k
)
315
1
    error("-no-define-common not supported in non relocatable output");
316
2.86k
317
2.86k
  if (config->zText && 
config->zIfuncNoplt2.85k
)
318
1
    error("-z text and -z ifunc-noplt may not be used together");
319
2.86k
320
2.86k
  if (config->relocatable) {
321
93
    if (config->shared)
322
1
      error("-r and -shared may not be used together");
323
93
    if (config->gcSections)
324
1
      error("-r and --gc-sections may not be used together");
325
93
    if (config->gdbIndex)
326
1
      error("-r and --gdb-index may not be used together");
327
93
    if (config->icf != ICFLevel::None)
328
1
      error("-r and --icf may not be used together");
329
93
    if (config->pie)
330
1
      error("-r and -pie may not be used together");
331
93
  }
332
2.86k
333
2.86k
  if (config->executeOnly) {
334
3
    if (config->emachine != EM_AARCH64)
335
0
      error("-execute-only is only supported on AArch64 targets");
336
3
337
3
    if (config->singleRoRx && 
!script->hasSectionsCommand2
)
338
0
      error("-execute-only and -no-rosegment cannot be used together");
339
3
  }
340
2.86k
341
2.86k
  if (config->zRetpolineplt && 
config->requireCET11
)
342
0
    error("--require-cet may not be used with -z retpolineplt");
343
2.86k
344
2.86k
  if (config->emachine != EM_AARCH64) {
345
2.74k
    if (config->pacPlt)
346
1
      error("--pac-plt only supported on AArch64");
347
2.74k
    if (config->forceBTI)
348
1
      error("--force-bti only supported on AArch64");
349
2.74k
  }
350
2.86k
}
351
352
3.02k
static const char *getReproduceOption(opt::InputArgList &args) {
353
3.02k
  if (auto *arg = args.getLastArg(OPT_reproduce))
354
9
    return arg->getValue();
355
3.01k
  return getenv("LLD_REPRODUCE");
356
3.01k
}
357
358
39.3k
static bool hasZOption(opt::InputArgList &args, StringRef key) {
359
39.3k
  for (auto *arg : args.filtered(OPT_z))
360
1.49k
    if (key == arg->getValue())
361
34
      return true;
362
39.3k
  
return false39.3k
;
363
39.3k
}
364
365
static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
366
21.1k
                     bool Default) {
367
21.1k
  for (auto *arg : args.filtered_reverse(OPT_z)) {
368
807
    if (k1 == arg->getValue())
369
15
      return true;
370
792
    if (k2 == arg->getValue())
371
28
      return false;
372
792
  }
373
21.1k
  
return Default21.1k
;
374
21.1k
}
375
376
117
static bool isKnownZFlag(StringRef s) {
377
117
  return s == "combreloc" || 
s == "copyreloc"116
||
s == "defs"116
||
378
117
         
s == "execstack"113
||
s == "global"112
||
s == "hazardplt"111
||
379
117
         
s == "ifunc-noplt"105
||
s == "initfirst"102
||
s == "interpose"101
||
380
117
         
s == "keep-text-section-prefix"100
||
s == "lazy"99
||
s == "muldefs"98
||
381
117
         
s == "nocombreloc"96
||
s == "nocopyreloc"95
||
s == "nodefaultlib"93
||
382
117
         
s == "nodelete"92
||
s == "nodlopen"91
||
s == "noexecstack"90
||
383
117
         
s == "nokeep-text-section-prefix"89
||
s == "norelro"88
||
s == "notext"81
||
384
117
         
s == "now"64
||
s == "origin"59
||
s == "relro"58
||
s == "retpolineplt"53
||
385
117
         
s == "rodynamic"42
||
s == "text"39
||
s == "wxneeded"37
||
386
117
         
s.startswith("common-page-size")35
||
s.startswith("max-page-size=")28
||
387
117
         
s.startswith("stack-size=")8
;
388
117
}
389
390
// Report an error for an unknown -z option.
391
3.03k
static void checkZOptions(opt::InputArgList &args) {
392
3.03k
  for (auto *arg : args.filtered(OPT_z))
393
117
    if (!isKnownZFlag(arg->getValue()))
394
4
      error("unknown -z value: " + StringRef(arg->getValue()));
395
3.03k
}
396
397
3.03k
void LinkerDriver::main(ArrayRef<const char *> argsArr) {
398
3.03k
  ELFOptTable parser;
399
3.03k
  opt::InputArgList args = parser.parse(argsArr.slice(1));
400
3.03k
401
3.03k
  // Interpret this flag early because error() depends on them.
402
3.03k
  errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
403
3.03k
  checkZOptions(args);
404
3.03k
405
3.03k
  // Handle -help
406
3.03k
  if (args.hasArg(OPT_help)) {
407
2
    printHelp();
408
2
    return;
409
2
  }
410
3.02k
411
3.02k
  // Handle -v or -version.
412
3.02k
  //
413
3.02k
  // A note about "compatible with GNU linkers" message: this is a hack for
414
3.02k
  // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
415
3.02k
  // still the newest version in March 2017) or earlier to recognize LLD as
416
3.02k
  // a GNU compatible linker. As long as an output for the -v option
417
3.02k
  // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
418
3.02k
  //
419
3.02k
  // This is somewhat ugly hack, but in reality, we had no choice other
420
3.02k
  // than doing this. Considering the very long release cycle of Libtool,
421
3.02k
  // it is not easy to improve it to recognize LLD as a GNU compatible
422
3.02k
  // linker in a timely manner. Even if we can make it, there are still a
423
3.02k
  // lot of "configure" scripts out there that are generated by old version
424
3.02k
  // of Libtool. We cannot convince every software developer to migrate to
425
3.02k
  // the latest version and re-generate scripts. So we have this hack.
426
3.02k
  if (args.hasArg(OPT_v) || 
args.hasArg(OPT_version)3.02k
)
427
8
    message(getLLDVersion() + " (compatible with GNU linkers)");
428
3.02k
429
3.02k
  if (const char *path = getReproduceOption(args)) {
430
10
    // Note that --reproduce is a debug option so you can ignore it
431
10
    // if you are trying to understand the whole picture of the code.
432
10
    Expected<std::unique_ptr<TarWriter>> errOrWriter =
433
10
        TarWriter::create(path, path::stem(path));
434
10
    if (errOrWriter) {
435
10
      tar = std::move(*errOrWriter);
436
10
      tar->append("response.txt", createResponseFile(args));
437
10
      tar->append("version.txt", getLLDVersion() + "\n");
438
10
    } else {
439
0
      error("--reproduce: " + toString(errOrWriter.takeError()));
440
0
    }
441
10
  }
442
3.02k
443
3.02k
  readConfigs(args);
444
3.02k
445
3.02k
  // The behavior of -v or --version is a bit strange, but this is
446
3.02k
  // needed for compatibility with GNU linkers.
447
3.02k
  if (args.hasArg(OPT_v) && 
!args.hasArg(OPT_INPUT)4
)
448
1
    return;
449
3.02k
  if (args.hasArg(OPT_version))
450
4
    return;
451
3.02k
452
3.02k
  initLLVM();
453
3.02k
  createFiles(args);
454
3.02k
  if (errorCount())
455
155
    return;
456
2.86k
457
2.86k
  inferMachineType();
458
2.86k
  setConfigs(args);
459
2.86k
  checkOptions();
460
2.86k
  if (errorCount())
461
16
    return;
462
2.85k
463
2.85k
  // The Target instance handles target-specific stuff, such as applying
464
2.85k
  // relocations or writing a PLT section. It also contains target-dependent
465
2.85k
  // values such as a default image base address.
466
2.85k
  target = getTarget();
467
2.85k
468
2.85k
  switch (config->ekind) {
469
2.85k
  case ELF32LEKind:
470
392
    link<ELF32LE>(args);
471
392
    return;
472
2.85k
  case ELF32BEKind:
473
158
    link<ELF32BE>(args);
474
158
    return;
475
2.85k
  case ELF64LEKind:
476
2.19k
    link<ELF64LE>(args);
477
2.19k
    return;
478
2.85k
  case ELF64BEKind:
479
112
    link<ELF64BE>(args);
480
112
    return;
481
2.85k
  default:
482
0
    llvm_unreachable("unknown Config->EKind");
483
2.85k
  }
484
2.85k
}
485
486
3.02k
static std::string getRpath(opt::InputArgList &args) {
487
3.02k
  std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
488
3.02k
  return llvm::join(v.begin(), v.end(), ":");
489
3.02k
}
490
491
// Determines what we should do if there are remaining unresolved
492
// symbols after the name resolution.
493
3.02k
static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
494
3.02k
  UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
495
3.02k
                                              OPT_warn_unresolved_symbols, true)
496
3.02k
                                     ? 
UnresolvedPolicy::ReportError3.02k
497
3.02k
                                     : 
UnresolvedPolicy::Warn8
;
498
3.02k
499
3.02k
  // Process the last of -unresolved-symbols, -no-undefined or -z defs.
500
10.9k
  for (auto *arg : llvm::reverse(args)) {
501
10.9k
    switch (arg->getOption().getID()) {
502
10.9k
    case OPT_unresolved_symbols: {
503
31
      StringRef s = arg->getValue();
504
31
      if (s == "ignore-all" || 
s == "ignore-in-object-files"10
)
505
23
        return UnresolvedPolicy::Ignore;
506
8
      if (s == "ignore-in-shared-libs" || 
s == "report-all"5
)
507
6
        return errorOrWarn;
508
2
      error("unknown --unresolved-symbols value: " + s);
509
2
      continue;
510
2
    }
511
2
    case OPT_no_undefined:
512
2
      return errorOrWarn;
513
117
    case OPT_z:
514
117
      if (StringRef(arg->getValue()) == "defs")
515
3
        return errorOrWarn;
516
114
      continue;
517
10.9k
    }
518
10.9k
  }
519
3.02k
520
3.02k
  // -shared implies -unresolved-symbols=ignore-all because missing
521
3.02k
  // symbols are likely to be resolved at runtime using other DSOs.
522
3.02k
  
if (2.99k
config->shared2.99k
)
523
971
    return UnresolvedPolicy::Ignore;
524
2.02k
  return errorOrWarn;
525
2.02k
}
526
527
3.02k
static Target2Policy getTarget2(opt::InputArgList &args) {
528
3.02k
  StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
529
3.02k
  if (s == "rel")
530
1
    return Target2Policy::Rel;
531
3.02k
  if (s == "abs")
532
1
    return Target2Policy::Abs;
533
3.02k
  if (s == "got-rel")
534
3.02k
    return Target2Policy::GotRel;
535
0
  error("unknown --target2 option: " + s);
536
0
  return Target2Policy::GotRel;
537
0
}
538
539
3.02k
static bool isOutputFormatBinary(opt::InputArgList &args) {
540
3.02k
  StringRef s = args.getLastArgValue(OPT_oformat, "elf");
541
3.02k
  if (s == "binary")
542
5
    return true;
543
3.02k
  if (!s.startswith("elf"))
544
1
    error("unknown --oformat value: " + s);
545
3.02k
  return false;
546
3.02k
}
547
548
3.02k
static DiscardPolicy getDiscard(opt::InputArgList &args) {
549
3.02k
  if (args.hasArg(OPT_relocatable))
550
94
    return DiscardPolicy::None;
551
2.93k
552
2.93k
  auto *arg =
553
2.93k
      args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
554
2.93k
  if (!arg)
555
2.92k
    return DiscardPolicy::Default;
556
6
  if (arg->getOption().getID() == OPT_discard_all)
557
3
    return DiscardPolicy::All;
558
3
  if (arg->getOption().getID() == OPT_discard_locals)
559
1
    return DiscardPolicy::Locals;
560
2
  return DiscardPolicy::None;
561
2
}
562
563
3.02k
static StringRef getDynamicLinker(opt::InputArgList &args) {
564
3.02k
  auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
565
3.02k
  if (!arg || 
arg->getOption().getID() == OPT_no_dynamic_linker14
)
566
3.01k
    return "";
567
13
  return arg->getValue();
568
13
}
569
570
3.02k
static ICFLevel getICF(opt::InputArgList &args) {
571
3.02k
  auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
572
3.02k
  if (!arg || 
arg->getOption().getID() == OPT_icf_none63
)
573
2.96k
    return ICFLevel::None;
574
62
  if (arg->getOption().getID() == OPT_icf_safe)
575
4
    return ICFLevel::Safe;
576
58
  return ICFLevel::All;
577
58
}
578
579
3.02k
static StripPolicy getStrip(opt::InputArgList &args) {
580
3.02k
  if (args.hasArg(OPT_relocatable))
581
94
    return StripPolicy::None;
582
2.93k
583
2.93k
  auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
584
2.93k
  if (!arg)
585
2.92k
    return StripPolicy::None;
586
7
  if (arg->getOption().getID() == OPT_strip_all)
587
4
    return StripPolicy::All;
588
3
  return StripPolicy::Debug;
589
3
}
590
591
static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
592
68
                                    const opt::Arg &arg) {
593
68
  uint64_t va = 0;
594
68
  if (s.startswith("0x"))
595
52
    s = s.drop_front(2);
596
68
  if (!to_integer(s, va, 16))
597
5
    error("invalid argument: " + arg.getAsString(args));
598
68
  return va;
599
68
}
600
601
3.02k
static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
602
3.02k
  StringMap<uint64_t> ret;
603
3.02k
  for (auto *arg : args.filtered(OPT_section_start)) {
604
20
    StringRef name;
605
20
    StringRef addr;
606
20
    std::tie(name, addr) = StringRef(arg->getValue()).split('=');
607
20
    ret[name] = parseSectionAddress(addr, args, *arg);
608
20
  }
609
3.02k
610
3.02k
  if (auto *arg = args.getLastArg(OPT_Ttext))
611
29
    ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
612
3.02k
  if (auto *arg = args.getLastArg(OPT_Tdata))
613
10
    ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
614
3.02k
  if (auto *arg = args.getLastArg(OPT_Tbss))
615
9
    ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
616
3.02k
  return ret;
617
3.02k
}
618
619
3.02k
static SortSectionPolicy getSortSection(opt::InputArgList &args) {
620
3.02k
  StringRef s = args.getLastArgValue(OPT_sort_section);
621
3.02k
  if (s == "alignment")
622
3
    return SortSectionPolicy::Alignment;
623
3.02k
  if (s == "name")
624
3
    return SortSectionPolicy::Name;
625
3.02k
  if (!s.empty())
626
0
    error("unknown --sort-section rule: " + s);
627
3.02k
  return SortSectionPolicy::Default;
628
3.02k
}
629
630
3.02k
static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
631
3.02k
  StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
632
3.02k
  if (s == "warn")
633
1
    return OrphanHandlingPolicy::Warn;
634
3.02k
  if (s == "error")
635
1
    return OrphanHandlingPolicy::Error;
636
3.02k
  if (s != "place")
637
1
    error("unknown --orphan-handling mode: " + s);
638
3.02k
  return OrphanHandlingPolicy::Place;
639
3.02k
}
640
641
// Parse --build-id or --build-id=<style>. We handle "tree" as a
642
// synonym for "sha1" because all our hash functions including
643
// -build-id=sha1 are actually tree hashes for performance reasons.
644
static std::pair<BuildIdKind, std::vector<uint8_t>>
645
3.02k
getBuildId(opt::InputArgList &args) {
646
3.02k
  auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
647
3.02k
  if (!arg)
648
3.00k
    return {BuildIdKind::None, {}};
649
20
650
20
  if (arg->getOption().getID() == OPT_build_id)
651
5
    return {BuildIdKind::Fast, {}};
652
15
653
15
  StringRef s = arg->getValue();
654
15
  if (s == "fast")
655
1
    return {BuildIdKind::Fast, {}};
656
14
  if (s == "md5")
657
3
    return {BuildIdKind::Md5, {}};
658
11
  if (s == "sha1" || 
s == "tree"8
)
659
5
    return {BuildIdKind::Sha1, {}};
660
6
  if (s == "uuid")
661
1
    return {BuildIdKind::Uuid, {}};
662
5
  if (s.startswith("0x"))
663
3
    return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
664
2
665
2
  if (s != "none")
666
0
    error("unknown --build-id style: " + s);
667
2
  return {BuildIdKind::None, {}};
668
2
}
669
670
3.02k
static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
671
3.02k
  StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
672
3.02k
  if (s == "android")
673
5
    return {true, false};
674
3.02k
  if (s == "relr")
675
4
    return {false, true};
676
3.01k
  if (s == "android+relr")
677
1
    return {true, true};
678
3.01k
679
3.01k
  if (s != "none")
680
0
    error("unknown -pack-dyn-relocs format: " + s);
681
3.01k
  return {false, false};
682
3.01k
}
683
684
11
static void readCallGraph(MemoryBufferRef mb) {
685
11
  // Build a map from symbol name to section
686
11
  DenseMap<StringRef, Symbol *> map;
687
11
  for (InputFile *file : objectFiles)
688
11
    for (Symbol *sym : file->getSymbols())
689
71
      map[sym->getName()] = sym;
690
11
691
108
  auto findSection = [&](StringRef name) -> InputSectionBase * {
692
108
    Symbol *sym = map.lookup(name);
693
108
    if (!sym) {
694
4
      if (config->warnSymbolOrdering)
695
2
        warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
696
4
      return nullptr;
697
4
    }
698
104
    maybeWarnUnorderableSymbol(sym);
699
104
700
104
    if (Defined *dr = dyn_cast_or_null<Defined>(sym))
701
102
      return dyn_cast_or_null<InputSectionBase>(dr->section);
702
2
    return nullptr;
703
2
  };
704
11
705
59
  for (StringRef line : args::getLines(mb)) {
706
59
    SmallVector<StringRef, 3> fields;
707
59
    line.split(fields, ' ');
708
59
    uint64_t count;
709
59
710
59
    if (fields.size() != 3 || 
!to_integer(fields[2], count)58
) {
711
2
      error(mb.getBufferIdentifier() + ": parse error");
712
2
      return;
713
2
    }
714
57
715
57
    if (InputSectionBase *from = findSection(fields[0]))
716
51
      if (InputSectionBase *to = findSection(fields[1]))
717
47
        config->callGraphProfile[std::make_pair(from, to)] += count;
718
57
  }
719
11
}
720
721
2.71k
template <class ELFT> static void readCallGraphsFromObjectFiles() {
722
3.32k
  for (auto file : objectFiles) {
723
3.32k
    auto *obj = cast<ObjFile<ELFT>>(file);
724
3.32k
725
3.32k
    for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
726
16
      auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
727
16
      auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
728
16
      if (!fromSym || !toSym)
729
4
        continue;
730
12
731
12
      auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
732
12
      auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
733
12
      if (from && to)
734
12
        config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
735
12
    }
736
3.32k
  }
737
2.71k
}
Driver.cpp:void readCallGraphsFromObjectFiles<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
721
375
template <class ELFT> static void readCallGraphsFromObjectFiles() {
722
435
  for (auto file : objectFiles) {
723
435
    auto *obj = cast<ObjFile<ELFT>>(file);
724
435
725
435
    for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
726
0
      auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
727
0
      auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
728
0
      if (!fromSym || !toSym)
729
0
        continue;
730
0
731
0
      auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
732
0
      auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
733
0
      if (from && to)
734
0
        config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
735
0
    }
736
435
  }
737
375
}
Driver.cpp:void readCallGraphsFromObjectFiles<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
721
157
template <class ELFT> static void readCallGraphsFromObjectFiles() {
722
210
  for (auto file : objectFiles) {
723
210
    auto *obj = cast<ObjFile<ELFT>>(file);
724
210
725
210
    for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
726
0
      auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
727
0
      auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
728
0
      if (!fromSym || !toSym)
729
0
        continue;
730
0
731
0
      auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
732
0
      auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
733
0
      if (from && to)
734
0
        config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
735
0
    }
736
210
  }
737
157
}
Driver.cpp:void readCallGraphsFromObjectFiles<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
721
2.07k
template <class ELFT> static void readCallGraphsFromObjectFiles() {
722
2.54k
  for (auto file : objectFiles) {
723
2.54k
    auto *obj = cast<ObjFile<ELFT>>(file);
724
2.54k
725
2.54k
    for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
726
16
      auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
727
16
      auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
728
16
      if (!fromSym || !toSym)
729
4
        continue;
730
12
731
12
      auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
732
12
      auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
733
12
      if (from && to)
734
12
        config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
735
12
    }
736
2.54k
  }
737
2.07k
}
Driver.cpp:void readCallGraphsFromObjectFiles<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
721
108
template <class ELFT> static void readCallGraphsFromObjectFiles() {
722
137
  for (auto file : objectFiles) {
723
137
    auto *obj = cast<ObjFile<ELFT>>(file);
724
137
725
137
    for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
726
0
      auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
727
0
      auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
728
0
      if (!fromSym || !toSym)
729
0
        continue;
730
0
731
0
      auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
732
0
      auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
733
0
      if (from && to)
734
0
        config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
735
0
    }
736
137
  }
737
108
}
738
739
3.02k
static bool getCompressDebugSections(opt::InputArgList &args) {
740
3.02k
  StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
741
3.02k
  if (s == "none")
742
3.02k
    return false;
743
7
  if (s != "zlib")
744
1
    error("unknown --compress-debug-sections value: " + s);
745
7
  if (!zlib::isAvailable())
746
0
    error("--compress-debug-sections: zlib is not available");
747
7
  return true;
748
7
}
749
750
static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
751
6.05k
                                                        unsigned id) {
752
6.05k
  auto *arg = args.getLastArg(id);
753
6.05k
  if (!arg)
754
6.05k
    return {"", ""};
755
5
756
5
  StringRef s = arg->getValue();
757
5
  std::pair<StringRef, StringRef> ret = s.split(';');
758
5
  if (ret.second.empty())
759
2
    error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
760
5
  return ret;
761
5
}
762
763
// Parse the symbol ordering file and warn for any duplicate entries.
764
35
static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
765
35
  SetVector<StringRef> names;
766
35
  for (StringRef s : args::getLines(mb))
767
84
    if (!names.insert(s) && 
config->warnSymbolOrdering4
)
768
4
      warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
769
35
770
35
  return names.takeVector();
771
35
}
772
773
15
static void parseClangOption(StringRef opt, const Twine &msg) {
774
15
  std::string err;
775
15
  raw_string_ostream os(err);
776
15
777
15
  const char *argv[] = {config->progName.data(), opt.data()};
778
15
  if (cl::ParseCommandLineOptions(2, argv, "", &os))
779
13
    return;
780
2
  os.flush();
781
2
  error(msg + ": " + StringRef(err).trim());
782
2
}
783
784
// Initializes Config members by the command line options.
785
3.02k
static void readConfigs(opt::InputArgList &args) {
786
3.02k
  errorHandler().verbose = args.hasArg(OPT_verbose);
787
3.02k
  errorHandler().fatalWarnings =
788
3.02k
      args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
789
3.02k
  errorHandler().vsDiagnostics =
790
3.02k
      args.hasArg(OPT_visual_studio_diagnostics_format, false);
791
3.02k
  threadsEnabled = args.hasFlag(OPT_threads, OPT_no_threads, true);
792
3.02k
793
3.02k
  config->allowMultipleDefinition =
794
3.02k
      args.hasFlag(OPT_allow_multiple_definition,
795
3.02k
                   OPT_no_allow_multiple_definition, false) ||
796
3.02k
      
hasZOption(args, "muldefs")3.02k
;
797
3.02k
  config->allowShlibUndefined =
798
3.02k
      args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
799
3.02k
                   args.hasArg(OPT_shared));
800
3.02k
  config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
801
3.02k
  config->bsymbolic = args.hasArg(OPT_Bsymbolic);
802
3.02k
  config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions);
803
3.02k
  config->checkSections =
804
3.02k
      args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
805
3.02k
  config->chroot = args.getLastArgValue(OPT_chroot);
806
3.02k
  config->compressDebugSections = getCompressDebugSections(args);
807
3.02k
  config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false);
808
3.02k
  config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
809
3.02k
                                      !args.hasArg(OPT_relocatable));
810
3.02k
  config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
811
3.02k
  config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
812
3.02k
  config->disableVerify = args.hasArg(OPT_disable_verify);
813
3.02k
  config->discard = getDiscard(args);
814
3.02k
  config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
815
3.02k
  config->dynamicLinker = getDynamicLinker(args);
816
3.02k
  config->ehFrameHdr =
817
3.02k
      args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
818
3.02k
  config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
819
3.02k
  config->emitRelocs = args.hasArg(OPT_emit_relocs);
820
3.02k
  config->callGraphProfileSort = args.hasFlag(
821
3.02k
      OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
822
3.02k
  config->enableNewDtags =
823
3.02k
      args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
824
3.02k
  config->entry = args.getLastArgValue(OPT_entry);
825
3.02k
  config->executeOnly =
826
3.02k
      args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
827
3.02k
  config->exportDynamic =
828
3.02k
      args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
829
3.02k
  config->filterList = args::getStrings(args, OPT_filter);
830
3.02k
  config->fini = args.getLastArgValue(OPT_fini, "_fini");
831
3.02k
  config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419);
832
3.02k
  config->forceBTI = args.hasArg(OPT_force_bti);
833
3.02k
  config->requireCET = args.hasArg(OPT_require_cet);
834
3.02k
  config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
835
3.02k
  config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
836
3.02k
  config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
837
3.02k
  config->icf = getICF(args);
838
3.02k
  config->ignoreDataAddressEquality =
839
3.02k
      args.hasArg(OPT_ignore_data_address_equality);
840
3.02k
  config->ignoreFunctionAddressEquality =
841
3.02k
      args.hasArg(OPT_ignore_function_address_equality);
842
3.02k
  config->init = args.getLastArgValue(OPT_init, "_init");
843
3.02k
  config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
844
3.02k
  config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
845
3.02k
  config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
846
3.02k
  config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
847
3.02k
  config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager);
848
3.02k
  config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
849
3.02k
  config->ltoo = args::getInteger(args, OPT_lto_O, 2);
850
3.02k
  config->ltoObjPath = args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
851
3.02k
  config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
852
3.02k
  config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
853
3.02k
  config->mapFile = args.getLastArgValue(OPT_Map);
854
3.02k
  config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
855
3.02k
  config->mergeArmExidx =
856
3.02k
      args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
857
3.02k
  config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
858
3.02k
  config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
859
3.02k
  config->nostdlib = args.hasArg(OPT_nostdlib);
860
3.02k
  config->oFormatBinary = isOutputFormatBinary(args);
861
3.02k
  config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
862
3.02k
  config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
863
3.02k
  config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
864
3.02k
  config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
865
3.02k
  config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
866
3.02k
  config->optimize = args::getInteger(args, OPT_O, 1);
867
3.02k
  config->orphanHandling = getOrphanHandling(args);
868
3.02k
  config->outputFile = args.getLastArgValue(OPT_o);
869
3.02k
  config->pacPlt = args.hasArg(OPT_pac_plt);
870
3.02k
  config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
871
3.02k
  config->printIcfSections =
872
3.02k
      args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
873
3.02k
  config->printGcSections =
874
3.02k
      args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
875
3.02k
  config->printSymbolOrder =
876
3.02k
      args.getLastArgValue(OPT_print_symbol_order);
877
3.02k
  config->rpath = getRpath(args);
878
3.02k
  config->relocatable = args.hasArg(OPT_relocatable);
879
3.02k
  config->saveTemps = args.hasArg(OPT_save_temps);
880
3.02k
  config->searchPaths = args::getStrings(args, OPT_library_path);
881
3.02k
  config->sectionStartMap = getSectionStartMap(args);
882
3.02k
  config->shared = args.hasArg(OPT_shared);
883
3.02k
  config->singleRoRx = args.hasArg(OPT_no_rosegment);
884
3.02k
  config->soName = args.getLastArgValue(OPT_soname);
885
3.02k
  config->sortSection = getSortSection(args);
886
3.02k
  config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
887
3.02k
  config->strip = getStrip(args);
888
3.02k
  config->sysroot = args.getLastArgValue(OPT_sysroot);
889
3.02k
  config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
890
3.02k
  config->target2 = getTarget2(args);
891
3.02k
  config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
892
3.02k
  config->thinLTOCachePolicy = CHECK(
893
3.02k
      parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
894
3.02k
      "--thinlto-cache-policy: invalid cache policy");
895
3.02k
  config->thinLTOEmitImportsFiles =
896
3.02k
      args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
897
3.02k
  config->thinLTOIndexOnly = args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
898
3.02k
                             
args.hasArg(OPT_plugin_opt_thinlto_index_only_eq)3.01k
;
899
3.02k
  config->thinLTOIndexOnlyArg =
900
3.02k
      args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
901
3.02k
  config->thinLTOJobs = args::getInteger(args, OPT_thinlto_jobs, -1u);
902
3.02k
  config->thinLTOObjectSuffixReplace =
903
3.02k
      getOldNewOptions(args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
904
3.02k
  config->thinLTOPrefixReplace =
905
3.02k
      getOldNewOptions(args, OPT_plugin_opt_thinlto_prefix_replace_eq);
906
3.02k
  config->trace = args.hasArg(OPT_trace);
907
3.02k
  config->undefined = args::getStrings(args, OPT_undefined);
908
3.02k
  config->undefinedVersion =
909
3.02k
      args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
910
3.02k
  config->useAndroidRelrTags = args.hasFlag(
911
3.02k
      OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
912
3.02k
  config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
913
3.02k
  config->warnBackrefs =
914
3.02k
      args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
915
3.02k
  config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
916
3.02k
  config->warnIfuncTextrel =
917
3.02k
      args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
918
3.02k
  config->warnSymbolOrdering =
919
3.02k
      args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
920
3.02k
  config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
921
3.02k
  config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
922
3.02k
  config->zExecstack = getZFlag(args, "execstack", "noexecstack", false);
923
3.02k
  config->zGlobal = hasZOption(args, "global");
924
3.02k
  config->zHazardplt = hasZOption(args, "hazardplt");
925
3.02k
  config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
926
3.02k
  config->zInitfirst = hasZOption(args, "initfirst");
927
3.02k
  config->zInterpose = hasZOption(args, "interpose");
928
3.02k
  config->zKeepTextSectionPrefix = getZFlag(
929
3.02k
      args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
930
3.02k
  config->zNodefaultlib = hasZOption(args, "nodefaultlib");
931
3.02k
  config->zNodelete = hasZOption(args, "nodelete");
932
3.02k
  config->zNodlopen = hasZOption(args, "nodlopen");
933
3.02k
  config->zNow = getZFlag(args, "now", "lazy", false);
934
3.02k
  config->zOrigin = hasZOption(args, "origin");
935
3.02k
  config->zRelro = getZFlag(args, "relro", "norelro", true);
936
3.02k
  config->zRetpolineplt = hasZOption(args, "retpolineplt");
937
3.02k
  config->zRodynamic = hasZOption(args, "rodynamic");
938
3.02k
  config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
939
3.02k
  config->zText = getZFlag(args, "text", "notext", true);
940
3.02k
  config->zWxneeded = hasZOption(args, "wxneeded");
941
3.02k
942
3.02k
  // Parse LTO options.
943
3.02k
  if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
944
1
    parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
945
1
                     arg->getSpelling());
946
3.02k
947
3.02k
  for (auto *arg : args.filtered(OPT_plugin_opt))
948
5
    parseClangOption(arg->getValue(), arg->getSpelling());
949
3.02k
950
3.02k
  // Parse -mllvm options.
951
3.02k
  for (auto *arg : args.filtered(OPT_mllvm))
952
9
    parseClangOption(arg->getValue(), arg->getSpelling());
953
3.02k
954
3.02k
  if (config->ltoo > 3)
955
4
    error("invalid optimization level for LTO: " + Twine(config->ltoo));
956
3.02k
  if (config->ltoPartitions == 0)
957
2
    error("--lto-partitions: number of threads must be > 0");
958
3.02k
  if (config->thinLTOJobs == 0)
959
2
    error("--thinlto-jobs: number of threads must be > 0");
960
3.02k
961
3.02k
  if (config->splitStackAdjustSize < 0)
962
1
    error("--split-stack-adjust-size: size must be >= 0");
963
3.02k
964
3.02k
  // Parse ELF{32,64}{LE,BE} and CPU type.
965
3.02k
  if (auto *arg = args.getLastArg(OPT_m)) {
966
43
    StringRef s = arg->getValue();
967
43
    std::tie(config->ekind, config->emachine, config->osabi) =
968
43
        parseEmulation(s);
969
43
    config->mipsN32Abi = (s == "elf32btsmipn32" || 
s == "elf32ltsmipn32"41
);
970
43
    config->emulation = s;
971
43
  }
972
3.02k
973
3.02k
  // Parse -hash-style={sysv,gnu,both}.
974
3.02k
  if (auto *arg = args.getLastArg(OPT_hash_style)) {
975
150
    StringRef s = arg->getValue();
976
150
    if (s == "sysv")
977
135
      config->sysvHash = true;
978
15
    else if (s == "gnu")
979
10
      config->gnuHash = true;
980
5
    else if (s == "both")
981
5
      config->sysvHash = config->gnuHash = true;
982
0
    else
983
0
      error("unknown -hash-style: " + s);
984
150
  }
985
3.02k
986
3.02k
  if (args.hasArg(OPT_print_map))
987
9
    config->mapFile = "-";
988
3.02k
989
3.02k
  // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
990
3.02k
  // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
991
3.02k
  // it.
992
3.02k
  if (config->nmagic || 
config->omagic3.02k
)
993
11
    config->zRelro = false;
994
3.02k
995
3.02k
  std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
996
3.02k
997
3.02k
  std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
998
3.02k
      getPackDynRelocs(args);
999
3.02k
1000
3.02k
  if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1001
35
    if (args.hasArg(OPT_call_graph_ordering_file))
1002
2
      error("--symbol-ordering-file and --call-graph-order-file "
1003
2
            "may not be used together");
1004
35
    if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1005
35
      config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1006
35
      // Also need to disable CallGraphProfileSort to prevent
1007
35
      // LLD order symbols with CGProfile
1008
35
      config->callGraphProfileSort = false;
1009
35
    }
1010
35
  }
1011
3.02k
1012
3.02k
  // If --retain-symbol-file is used, we'll keep only the symbols listed in
1013
3.02k
  // the file and discard all others.
1014
3.02k
  if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1015
3
    config->defaultSymbolVersion = VER_NDX_LOCAL;
1016
3
    if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1017
3
      for (StringRef s : args::getLines(*buffer))
1018
4
        config->versionScriptGlobals.push_back(
1019
4
            {s, /*IsExternCpp*/ false, /*HasWildcard*/ false});
1020
3
  }
1021
3.02k
1022
3.02k
  bool hasExportDynamic =
1023
3.02k
      args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
1024
3.02k
1025
3.02k
  // Parses -dynamic-list and -export-dynamic-symbol. They make some
1026
3.02k
  // symbols private. Note that -export-dynamic takes precedence over them
1027
3.02k
  // as it says all symbols should be exported.
1028
3.02k
  if (!hasExportDynamic) {
1029
2.99k
    for (auto *arg : args.filtered(OPT_dynamic_list))
1030
26
      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1031
26
        readDynamicList(*buffer);
1032
2.99k
1033
2.99k
    for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1034
5
      config->dynamicList.push_back(
1035
5
          {arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
1036
2.99k
  }
1037
3.02k
1038
3.02k
  // If --export-dynamic-symbol=foo is given and symbol foo is defined in
1039
3.02k
  // an object file in an archive file, that object file should be pulled
1040
3.02k
  // out and linked. (It doesn't have to behave like that from technical
1041
3.02k
  // point of view, but this is needed for compatibility with GNU.)
1042
3.02k
  for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1043
7
    config->undefined.push_back(arg->getValue());
1044
3.02k
1045
3.02k
  for (auto *arg : args.filtered(OPT_version_script))
1046
94
    if (Optional<std::string> path = searchScript(arg->getValue())) {
1047
93
      if (Optional<MemoryBufferRef> buffer = readFile(*path))
1048
93
        readVersionScript(*buffer);
1049
93
    } else {
1050
1
      error(Twine("cannot find version script ") + arg->getValue());
1051
1
    }
1052
3.02k
}
1053
1054
// Some Config members do not directly correspond to any particular
1055
// command line options, but computed based on other Config values.
1056
// This function initialize such members. See Config.h for the details
1057
// of these values.
1058
2.86k
static void setConfigs(opt::InputArgList &args) {
1059
2.86k
  ELFKind k = config->ekind;
1060
2.86k
  uint16_t m = config->emachine;
1061
2.86k
1062
2.86k
  config->copyRelocs = (config->relocatable || 
config->emitRelocs2.77k
);
1063
2.86k
  config->is64 = (k == ELF64LEKind || 
k == ELF64BEKind665
);
1064
2.86k
  config->isLE = (k == ELF32LEKind || 
k == ELF64LEKind2.47k
);
1065
2.86k
  config->endianness = config->isLE ? 
endianness::little2.59k
:
endianness::big272
;
1066
2.86k
  config->isMips64EL = (k == ELF64LEKind && 
m == EM_MIPS2.20k
);
1067
2.86k
  config->isPic = config->pie || 
config->shared2.78k
;
1068
2.86k
  config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1069
2.86k
  config->wordsize = config->is64 ? 
82.31k
:
4553
;
1070
2.86k
1071
2.86k
  // ELF defines two different ways to store relocation addends as shown below:
1072
2.86k
  //
1073
2.86k
  //  Rel:  Addends are stored to the location where relocations are applied.
1074
2.86k
  //  Rela: Addends are stored as part of relocation entry.
1075
2.86k
  //
1076
2.86k
  // In other words, Rela makes it easy to read addends at the price of extra
1077
2.86k
  // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1078
2.86k
  // different mechanisms in the first place, but this is how the spec is
1079
2.86k
  // defined.
1080
2.86k
  //
1081
2.86k
  // You cannot choose which one, Rel or Rela, you want to use. Instead each
1082
2.86k
  // ABI defines which one you need to use. The following expression expresses
1083
2.86k
  // that.
1084
2.86k
  config->isRela = m == EM_AARCH64 || 
m == EM_AMDGPU2.74k
||
m == EM_HEXAGON2.73k
||
1085
2.86k
                   
m == EM_PPC2.73k
||
m == EM_PPC642.70k
||
m == EM_RISCV2.54k
||
1086
2.86k
                   
m == EM_X86_642.45k
;
1087
2.86k
1088
2.86k
  // If the output uses REL relocations we must store the dynamic relocation
1089
2.86k
  // addends to the output sections. We also store addends for RELA relocations
1090
2.86k
  // if --apply-dynamic-relocs is used.
1091
2.86k
  // We default to not writing the addends when using RELA relocations since
1092
2.86k
  // any standard conforming tool can find it in r_addend.
1093
2.86k
  config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1094
2.86k
                                      OPT_no_apply_dynamic_relocs, false) ||
1095
2.86k
                         
!config->isRela2.86k
;
1096
2.86k
1097
2.86k
  config->tocOptimize =
1098
2.86k
      args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1099
2.86k
}
1100
1101
// Returns a value of "-format" option.
1102
9
static bool isFormatBinary(StringRef s) {
1103
9
  if (s == "binary")
1104
7
    return true;
1105
2
  if (s == "elf" || s == "default")
1106
1
    return false;
1107
1
  error("unknown -format value: " + s +
1108
1
        " (supported formats: elf, default, binary)");
1109
1
  return false;
1110
1
}
1111
1112
3.02k
void LinkerDriver::createFiles(opt::InputArgList &args) {
1113
3.02k
  // For --{push,pop}-state.
1114
3.02k
  std::vector<std::tuple<bool, bool, bool>> stack;
1115
3.02k
1116
3.02k
  // Iterate over argv to process input files and positional arguments.
1117
11.0k
  for (auto *arg : args) {
1118
11.0k
    switch (arg->getOption().getID()) {
1119
11.0k
    case OPT_library:
1120
34
      addLibrary(arg->getValue());
1121
34
      break;
1122
11.0k
    case OPT_INPUT:
1123
4.22k
      addFile(arg->getValue(), /*withLOption=*/false);
1124
4.22k
      break;
1125
11.0k
    case OPT_defsym: {
1126
153
      StringRef from;
1127
153
      StringRef to;
1128
153
      std::tie(from, to) = StringRef(arg->getValue()).split('=');
1129
153
      if (from.empty() || 
to.empty()152
)
1130
3
        error("-defsym: syntax error: " + StringRef(arg->getValue()));
1131
150
      else
1132
150
        readDefsym(from, MemoryBufferRef(to, "-defsym"));
1133
153
      break;
1134
11.0k
    }
1135
11.0k
    case OPT_script:
1136
545
      if (Optional<std::string> path = searchScript(arg->getValue())) {
1137
544
        if (Optional<MemoryBufferRef> mb = readFile(*path))
1138
544
          readLinkerScript(*mb);
1139
544
        break;
1140
544
      }
1141
1
      error(Twine("cannot find linker script ") + arg->getValue());
1142
1
      break;
1143
22
    case OPT_as_needed:
1144
22
      config->asNeeded = true;
1145
22
      break;
1146
9
    case OPT_format:
1147
9
      config->formatBinary = isFormatBinary(arg->getValue());
1148
9
      break;
1149
2
    case OPT_no_as_needed:
1150
2
      config->asNeeded = false;
1151
2
      break;
1152
40
    case OPT_Bstatic:
1153
40
    case OPT_omagic:
1154
40
    case OPT_nmagic:
1155
40
      config->isStatic = true;
1156
40
      break;
1157
40
    case OPT_Bdynamic:
1158
8
      config->isStatic = false;
1159
8
      break;
1160
40
    case OPT_whole_archive:
1161
18
      inWholeArchive = true;
1162
18
      break;
1163
40
    case OPT_no_whole_archive:
1164
3
      inWholeArchive = false;
1165
3
      break;
1166
40
    case OPT_just_symbols:
1167
3
      if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1168
3
        files.push_back(createObjectFile(*mb));
1169
3
        files.back()->justSymbols = true;
1170
3
      }
1171
3
      break;
1172
40
    case OPT_start_group:
1173
8
      if (InputFile::isInGroup)
1174
1
        error("nested --start-group");
1175
8
      InputFile::isInGroup = true;
1176
8
      break;
1177
40
    case OPT_end_group:
1178
6
      if (!InputFile::isInGroup)
1179
1
        error("stray --end-group");
1180
6
      InputFile::isInGroup = false;
1181
6
      ++InputFile::nextGroupId;
1182
6
      break;
1183
40
    case OPT_start_lib:
1184
20
      if (inLib)
1185
1
        error("nested --start-lib");
1186
20
      if (InputFile::isInGroup)
1187
2
        error("may not nest --start-lib in --start-group");
1188
20
      inLib = true;
1189
20
      InputFile::isInGroup = true;
1190
20
      break;
1191
40
    case OPT_end_lib:
1192
12
      if (!inLib)
1193
1
        error("stray --end-lib");
1194
12
      inLib = false;
1195
12
      InputFile::isInGroup = false;
1196
12
      ++InputFile::nextGroupId;
1197
12
      break;
1198
40
    case OPT_push_state:
1199
6
      stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1200
6
      break;
1201
40
    case OPT_pop_state:
1202
4
      if (stack.empty()) {
1203
1
        error("unbalanced --push-state/--pop-state");
1204
1
        break;
1205
1
      }
1206
3
      std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1207
3
      stack.pop_back();
1208
3
      break;
1209
11.0k
    }
1210
11.0k
  }
1211
3.02k
1212
3.02k
  if (files.empty() && 
errorCount() == 052
)
1213
2
    error("no input files");
1214
3.02k
}
1215
1216
// If -m <machine_type> was not given, infer it from object files.
1217
2.86k
void LinkerDriver::inferMachineType() {
1218
2.86k
  if (config->ekind != ELFNoneKind)
1219
66
    return;
1220
2.80k
1221
2.82k
  
for (InputFile *f : files)2.80k
{
1222
2.82k
    if (f->ekind == ELFNoneKind)
1223
28
      continue;
1224
2.80k
    config->ekind = f->ekind;
1225
2.80k
    config->emachine = f->emachine;
1226
2.80k
    config->osabi = f->osabi;
1227
2.80k
    config->mipsN32Abi = config->emachine == EM_MIPS && 
isMipsN32Abi(f)186
;
1228
2.80k
    return;
1229
2.80k
  }
1230
2.80k
  error("target emulation unknown: -m or at least one .o file required");
1231
1
}
1232
1233
// Parse -z max-page-size=<value>. The default value is defined by
1234
// each target.
1235
2.75k
static uint64_t getMaxPageSize(opt::InputArgList &args) {
1236
2.75k
  uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1237
2.75k
                                       target->defaultMaxPageSize);
1238
2.75k
  if (!isPowerOf2_64(val))
1239
1
    error("max-page-size: value isn't a power of 2");
1240
2.75k
  if (config->nmagic || 
config->omagic2.74k
) {
1241
11
    if (val != target->defaultMaxPageSize)
1242
4
      warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1243
11
    return 1;
1244
11
  }
1245
2.74k
  return val;
1246
2.74k
}
1247
1248
// Parse -z common-page-size=<value>. The default value is defined by
1249
// each target.
1250
2.75k
static uint64_t getCommonPageSize(opt::InputArgList &args) {
1251
2.75k
  uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1252
2.75k
                                       target->defaultCommonPageSize);
1253
2.75k
  if (!isPowerOf2_64(val))
1254
0
    error("common-page-size: value isn't a power of 2");
1255
2.75k
  if (config->nmagic || 
config->omagic2.74k
) {
1256
11
    if (val != target->defaultCommonPageSize)
1257
4
      warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1258
11
    return 1;
1259
11
  }
1260
2.74k
  // commonPageSize can't be larger than maxPageSize.
1261
2.74k
  if (val > config->maxPageSize)
1262
1
    val = config->maxPageSize;
1263
2.74k
  return val;
1264
2.74k
}
1265
1266
// Parses -image-base option.
1267
2.75k
static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1268
2.75k
  // Because we are using "Config->maxPageSize" here, this function has to be
1269
2.75k
  // called after the variable is initialized.
1270
2.75k
  auto *arg = args.getLastArg(OPT_image_base);
1271
2.75k
  if (!arg)
1272
2.74k
    return None;
1273
9
1274
9
  StringRef s = arg->getValue();
1275
9
  uint64_t v;
1276
9
  if (!to_integer(s, v)) {
1277
1
    error("-image-base: number expected, but got " + s);
1278
1
    return 0;
1279
1
  }
1280
8
  if ((v % config->maxPageSize) != 0)
1281
2
    warn("-image-base: address isn't multiple of page size: " + s);
1282
8
  return v;
1283
8
}
1284
1285
// Parses `--exclude-libs=lib,lib,...`.
1286
// The library names may be delimited by commas or colons.
1287
8
static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1288
8
  DenseSet<StringRef> ret;
1289
8
  for (auto *arg : args.filtered(OPT_exclude_libs)) {
1290
8
    StringRef s = arg->getValue();
1291
15
    for (;;) {
1292
15
      size_t pos = s.find_first_of(",:");
1293
15
      if (pos == StringRef::npos)
1294
8
        break;
1295
7
      ret.insert(s.substr(0, pos));
1296
7
      s = s.substr(pos + 1);
1297
7
    }
1298
8
    ret.insert(s);
1299
8
  }
1300
8
  return ret;
1301
8
}
1302
1303
// Handles the -exclude-libs option. If a static library file is specified
1304
// by the -exclude-libs option, all public symbols from the archive become
1305
// private unless otherwise specified by version scripts or something.
1306
// A special library name "ALL" means all archive files.
1307
//
1308
// This is not a popular option, but some programs such as bionic libc use it.
1309
8
static void excludeLibs(opt::InputArgList &args) {
1310
8
  DenseSet<StringRef> libs = getExcludeLibs(args);
1311
8
  bool all = libs.count("ALL");
1312
8
1313
23
  auto visit = [&](InputFile *file) {
1314
23
    if (!file->archiveName.empty())
1315
13
      if (all || 
libs.count(path::filename(file->archiveName))8
)
1316
11
        for (Symbol *sym : file->getSymbols())
1317
25
          if (!sym->isLocal() && 
sym->file == file19
)
1318
14
            sym->versionId = VER_NDX_LOCAL;
1319
23
  };
1320
8
1321
8
  for (InputFile *file : objectFiles)
1322
16
    visit(file);
1323
8
1324
8
  for (BitcodeFile *file : bitcodeFiles)
1325
7
    visit(file);
1326
8
}
1327
1328
// Force Sym to be entered in the output. Used for -u or equivalent.
1329
1.47k
static void handleUndefined(Symbol *sym) {
1330
1.47k
  // Since a symbol may not be used inside the program, LTO may
1331
1.47k
  // eliminate it. Mark the symbol as "used" to prevent it.
1332
1.47k
  sym->isUsedInRegularObj = true;
1333
1.47k
1334
1.47k
  if (sym->isLazy())
1335
24
    sym->fetch();
1336
1.47k
}
1337
1338
// As an extention to GNU linkers, lld supports a variant of `-u`
1339
// which accepts wildcard patterns. All symbols that match a given
1340
// pattern are handled as if they were given by `-u`.
1341
5
static void handleUndefinedGlob(StringRef arg) {
1342
5
  Expected<GlobPattern> pat = GlobPattern::create(arg);
1343
5
  if (!pat) {
1344
1
    error("--undefined-glob: " + toString(pat.takeError()));
1345
1
    return;
1346
1
  }
1347
4
1348
4
  std::vector<Symbol *> syms;
1349
20
  symtab->forEachSymbol([&](Symbol *sym) {
1350
20
    // Calling Sym->fetch() from here is not safe because it may
1351
20
    // add new symbols to the symbol table, invalidating the
1352
20
    // current iterator. So we just keep a note.
1353
20
    if (pat->match(sym->getName()))
1354
8
      syms.push_back(sym);
1355
20
  });
1356
4
1357
4
  for (Symbol *sym : syms)
1358
8
    handleUndefined(sym);
1359
4
}
1360
1361
89.0k
static void handleLibcall(StringRef name) {
1362
89.0k
  Symbol *sym = symtab->find(name);
1363
89.0k
  if (!sym || 
!sym->isLazy()4
)
1364
89.0k
    return;
1365
4
1366
4
  MemoryBufferRef mb;
1367
4
  if (auto *lo = dyn_cast<LazyObject>(sym))
1368
2
    mb = lo->file->mb;
1369
2
  else
1370
2
    mb = cast<LazyArchive>(sym)->getMemberBuffer();
1371
4
1372
4
  if (isBitcode(mb))
1373
2
    sym->fetch();
1374
4
}
1375
1376
// Replaces common symbols with defined symbols reside in .bss sections.
1377
// This function is called after all symbol names are resolved. As a
1378
// result, the passes after the symbol resolution won't see any
1379
// symbols of type CommonSymbol.
1380
2.75k
static void replaceCommonSymbols() {
1381
17.0k
  symtab->forEachSymbol([](Symbol *sym) {
1382
17.0k
    auto *s = dyn_cast<CommonSymbol>(sym);
1383
17.0k
    if (!s)
1384
16.9k
      return;
1385
101
1386
101
    auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1387
101
    bss->file = s->file;
1388
101
    bss->markDead();
1389
101
    inputSections.push_back(bss);
1390
101
    s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1391
101
                       /*value=*/0, s->size, bss});
1392
101
  });
1393
2.75k
}
1394
1395
// If all references to a DSO happen to be weak, the DSO is not added
1396
// to DT_NEEDED. If that happens, we need to eliminate shared symbols
1397
// created from the DSO. Otherwise, they become dangling references
1398
// that point to a non-existent DSO.
1399
2.75k
static void demoteSharedSymbols() {
1400
17.0k
  symtab->forEachSymbol([](Symbol *sym) {
1401
17.0k
    auto *s = dyn_cast<SharedSymbol>(sym);
1402
17.0k
    if (!s || 
s->getFile().isNeeded796
)
1403
16.9k
      return;
1404
30
1405
30
    bool used = s->used;
1406
30
    s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1407
30
    s->used = used;
1408
30
  });
1409
2.75k
}
1410
1411
// The section referred to by `s` is considered address-significant. Set the
1412
// keepUnique flag on the section if appropriate.
1413
400
static void markAddrsig(Symbol *s) {
1414
400
  if (auto *d = dyn_cast_or_null<Defined>(s))
1415
320
    if (d->section)
1416
306
      // We don't need to keep text sections unique under --icf=all even if they
1417
306
      // are address-significant.
1418
306
      if (config->icf == ICFLevel::Safe || 
!(d->section->flags & SHF_EXECINSTR)240
)
1419
111
        d->section->keepUnique = true;
1420
400
}
1421
1422
// Record sections that define symbols mentioned in --keep-unique <symbol>
1423
// and symbols referred to by address-significance tables. These sections are
1424
// ineligible for ICF.
1425
template <class ELFT>
1426
61
static void findKeepUniqueSections(opt::InputArgList &args) {
1427
61
  for (auto *arg : args.filtered(OPT_keep_unique)) {
1428
3
    StringRef name = arg->getValue();
1429
3
    auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1430
3
    if (!d || 
!d->section2
) {
1431
1
      warn("could not find symbol " + name + " to keep unique");
1432
1
      continue;
1433
1
    }
1434
2
    d->section->keepUnique = true;
1435
2
  }
1436
61
1437
61
  // --icf=all --ignore-data-address-equality means that we can ignore
1438
61
  // the dynsym and address-significance tables entirely.
1439
61
  if (config->icf == ICFLevel::All && 
config->ignoreDataAddressEquality57
)
1440
3
    return;
1441
58
1442
58
  // Symbols in the dynsym could be address-significant in other executables
1443
58
  // or DSOs, so we conservatively mark them as address-significant.
1444
220
  
symtab->forEachSymbol([&](Symbol *sym) 58
{
1445
220
    if (sym->includeInDynsym())
1446
47
      markAddrsig(sym);
1447
220
  });
Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::Symbol*)::operator()(lld::elf::Symbol*) const
Line
Count
Source
1444
11
  symtab->forEachSymbol([&](Symbol *sym) {
1445
11
    if (sym->includeInDynsym())
1446
4
      markAddrsig(sym);
1447
11
  });
Unexecuted instantiation: Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::Symbol*)::operator()(lld::elf::Symbol*) const
Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::Symbol*)::operator()(lld::elf::Symbol*) const
Line
Count
Source
1444
209
  symtab->forEachSymbol([&](Symbol *sym) {
1445
209
    if (sym->includeInDynsym())
1446
43
      markAddrsig(sym);
1447
209
  });
Unexecuted instantiation: Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::Symbol*)::operator()(lld::elf::Symbol*) const
1448
58
1449
58
  // Visit the address-significance table in each object file and mark each
1450
58
  // referenced symbol as address-significant.
1451
75
  for (InputFile *f : objectFiles) {
1452
75
    auto *obj = cast<ObjFile<ELFT>>(f);
1453
75
    ArrayRef<Symbol *> syms = obj->getSymbols();
1454
75
    if (obj->addrsigSec) {
1455
5
      ArrayRef<uint8_t> contents =
1456
5
          check(obj->getObj().getSectionContents(obj->addrsigSec));
1457
5
      const uint8_t *cur = contents.begin();
1458
45
      while (cur != contents.end()) {
1459
40
        unsigned size;
1460
40
        const char *err;
1461
40
        uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1462
40
        if (err)
1463
0
          fatal(toString(f) + ": could not decode addrsig section: " + err);
1464
40
        markAddrsig(syms[symIndex]);
1465
40
        cur += size;
1466
40
      }
1467
70
    } else {
1468
70
      // If an object file does not have an address-significance table,
1469
70
      // conservatively mark all of its symbols as address-significant.
1470
70
      for (Symbol *s : syms)
1471
313
        markAddrsig(s);
1472
70
    }
1473
75
  }
1474
58
}
Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)
Line
Count
Source
1426
3
static void findKeepUniqueSections(opt::InputArgList &args) {
1427
3
  for (auto *arg : args.filtered(OPT_keep_unique)) {
1428
0
    StringRef name = arg->getValue();
1429
0
    auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1430
0
    if (!d || !d->section) {
1431
0
      warn("could not find symbol " + name + " to keep unique");
1432
0
      continue;
1433
0
    }
1434
0
    d->section->keepUnique = true;
1435
0
  }
1436
3
1437
3
  // --icf=all --ignore-data-address-equality means that we can ignore
1438
3
  // the dynsym and address-significance tables entirely.
1439
3
  if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1440
0
    return;
1441
3
1442
3
  // Symbols in the dynsym could be address-significant in other executables
1443
3
  // or DSOs, so we conservatively mark them as address-significant.
1444
3
  symtab->forEachSymbol([&](Symbol *sym) {
1445
3
    if (sym->includeInDynsym())
1446
3
      markAddrsig(sym);
1447
3
  });
1448
3
1449
3
  // Visit the address-significance table in each object file and mark each
1450
3
  // referenced symbol as address-significant.
1451
3
  for (InputFile *f : objectFiles) {
1452
3
    auto *obj = cast<ObjFile<ELFT>>(f);
1453
3
    ArrayRef<Symbol *> syms = obj->getSymbols();
1454
3
    if (obj->addrsigSec) {
1455
0
      ArrayRef<uint8_t> contents =
1456
0
          check(obj->getObj().getSectionContents(obj->addrsigSec));
1457
0
      const uint8_t *cur = contents.begin();
1458
0
      while (cur != contents.end()) {
1459
0
        unsigned size;
1460
0
        const char *err;
1461
0
        uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1462
0
        if (err)
1463
0
          fatal(toString(f) + ": could not decode addrsig section: " + err);
1464
0
        markAddrsig(syms[symIndex]);
1465
0
        cur += size;
1466
0
      }
1467
3
    } else {
1468
3
      // If an object file does not have an address-significance table,
1469
3
      // conservatively mark all of its symbols as address-significant.
1470
3
      for (Symbol *s : syms)
1471
25
        markAddrsig(s);
1472
3
    }
1473
3
  }
1474
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
1426
58
static void findKeepUniqueSections(opt::InputArgList &args) {
1427
58
  for (auto *arg : args.filtered(OPT_keep_unique)) {
1428
3
    StringRef name = arg->getValue();
1429
3
    auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1430
3
    if (!d || 
!d->section2
) {
1431
1
      warn("could not find symbol " + name + " to keep unique");
1432
1
      continue;
1433
1
    }
1434
2
    d->section->keepUnique = true;
1435
2
  }
1436
58
1437
58
  // --icf=all --ignore-data-address-equality means that we can ignore
1438
58
  // the dynsym and address-significance tables entirely.
1439
58
  if (config->icf == ICFLevel::All && 
config->ignoreDataAddressEquality54
)
1440
3
    return;
1441
55
1442
55
  // Symbols in the dynsym could be address-significant in other executables
1443
55
  // or DSOs, so we conservatively mark them as address-significant.
1444
55
  symtab->forEachSymbol([&](Symbol *sym) {
1445
55
    if (sym->includeInDynsym())
1446
55
      markAddrsig(sym);
1447
55
  });
1448
55
1449
55
  // Visit the address-significance table in each object file and mark each
1450
55
  // referenced symbol as address-significant.
1451
72
  for (InputFile *f : objectFiles) {
1452
72
    auto *obj = cast<ObjFile<ELFT>>(f);
1453
72
    ArrayRef<Symbol *> syms = obj->getSymbols();
1454
72
    if (obj->addrsigSec) {
1455
5
      ArrayRef<uint8_t> contents =
1456
5
          check(obj->getObj().getSectionContents(obj->addrsigSec));
1457
5
      const uint8_t *cur = contents.begin();
1458
45
      while (cur != contents.end()) {
1459
40
        unsigned size;
1460
40
        const char *err;
1461
40
        uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1462
40
        if (err)
1463
0
          fatal(toString(f) + ": could not decode addrsig section: " + err);
1464
40
        markAddrsig(syms[symIndex]);
1465
40
        cur += size;
1466
40
      }
1467
67
    } else {
1468
67
      // If an object file does not have an address-significance table,
1469
67
      // conservatively mark all of its symbols as address-significant.
1470
67
      for (Symbol *s : syms)
1471
288
        markAddrsig(s);
1472
67
    }
1473
72
  }
1474
55
}
Unexecuted instantiation: Driver.cpp:void findKeepUniqueSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)
1475
1476
// This function reads a symbol partition specification section. These sections
1477
// are used to control which partition a symbol is allocated to. See
1478
// https://lld.llvm.org/Partitions.html for more details on partitions.
1479
template <typename ELFT>
1480
21
static void readSymbolPartitionSection(InputSectionBase *s) {
1481
21
  // Read the relocation that refers to the partition's entry point symbol.
1482
21
  Symbol *sym;
1483
21
  if (s->areRelocsRela)
1484
17
    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1485
4
  else
1486
4
    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1487
21
  if (!isa<Defined>(sym) || !sym->includeInDynsym())
1488
0
    return;
1489
21
1490
21
  StringRef partName = reinterpret_cast<const char *>(s->data().data());
1491
28
  for (Partition &part : partitions) {
1492
28
    if (part.name == partName) {
1493
3
      sym->partition = part.getNumber();
1494
3
      return;
1495
3
    }
1496
28
  }
1497
21
1498
21
  // Forbid partitions from being used on incompatible targets, and forbid them
1499
21
  // from being used together with various linker features that assume a single
1500
21
  // set of output sections.
1501
21
  
if (18
script->hasSectionsCommand18
)
1502
1
    error(toString(s->file) +
1503
1
          ": partitions cannot be used with the SECTIONS command");
1504
18
  if (script->hasPhdrsCommands())
1505
1
    error(toString(s->file) +
1506
1
          ": partitions cannot be used with the PHDRS command");
1507
18
  if (!config->sectionStartMap.empty())
1508
4
    error(toString(s->file) + ": partitions cannot be used with "
1509
4
                              "--section-start, -Ttext, -Tdata or -Tbss");
1510
18
  if (config->emachine == EM_MIPS)
1511
1
    error(toString(s->file) + ": partitions cannot be used on this target");
1512
18
1513
18
  // Impose a limit of no more than 254 partitions. This limit comes from the
1514
18
  // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1515
18
  // the amount of space devoted to the partition number in RankFlags.
1516
18
  if (partitions.size() == 254)
1517
0
    fatal("may not have more than 254 partitions");
1518
18
1519
18
  partitions.emplace_back();
1520
18
  Partition &newPart = partitions.back();
1521
18
  newPart.name = partName;
1522
18
  sym->partition = newPart.getNumber();
1523
18
}
Driver.cpp:void readSymbolPartitionSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::InputSectionBase*)
Line
Count
Source
1480
4
static void readSymbolPartitionSection(InputSectionBase *s) {
1481
4
  // Read the relocation that refers to the partition's entry point symbol.
1482
4
  Symbol *sym;
1483
4
  if (s->areRelocsRela)
1484
0
    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1485
4
  else
1486
4
    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1487
4
  if (!isa<Defined>(sym) || !sym->includeInDynsym())
1488
0
    return;
1489
4
1490
4
  StringRef partName = reinterpret_cast<const char *>(s->data().data());
1491
5
  for (Partition &part : partitions) {
1492
5
    if (part.name == partName) {
1493
0
      sym->partition = part.getNumber();
1494
0
      return;
1495
0
    }
1496
5
  }
1497
4
1498
4
  // Forbid partitions from being used on incompatible targets, and forbid them
1499
4
  // from being used together with various linker features that assume a single
1500
4
  // set of output sections.
1501
4
  if (script->hasSectionsCommand)
1502
0
    error(toString(s->file) +
1503
0
          ": partitions cannot be used with the SECTIONS command");
1504
4
  if (script->hasPhdrsCommands())
1505
0
    error(toString(s->file) +
1506
0
          ": partitions cannot be used with the PHDRS command");
1507
4
  if (!config->sectionStartMap.empty())
1508
0
    error(toString(s->file) + ": partitions cannot be used with "
1509
0
                              "--section-start, -Ttext, -Tdata or -Tbss");
1510
4
  if (config->emachine == EM_MIPS)
1511
1
    error(toString(s->file) + ": partitions cannot be used on this target");
1512
4
1513
4
  // Impose a limit of no more than 254 partitions. This limit comes from the
1514
4
  // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1515
4
  // the amount of space devoted to the partition number in RankFlags.
1516
4
  if (partitions.size() == 254)
1517
0
    fatal("may not have more than 254 partitions");
1518
4
1519
4
  partitions.emplace_back();
1520
4
  Partition &newPart = partitions.back();
1521
4
  newPart.name = partName;
1522
4
  sym->partition = newPart.getNumber();
1523
4
}
Unexecuted instantiation: Driver.cpp:void readSymbolPartitionSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::InputSectionBase*)
Driver.cpp:void readSymbolPartitionSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::InputSectionBase*)
Line
Count
Source
1480
17
static void readSymbolPartitionSection(InputSectionBase *s) {
1481
17
  // Read the relocation that refers to the partition's entry point symbol.
1482
17
  Symbol *sym;
1483
17
  if (s->areRelocsRela)
1484
17
    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1485
0
  else
1486
0
    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1487
17
  if (!isa<Defined>(sym) || !sym->includeInDynsym())
1488
0
    return;
1489
17
1490
17
  StringRef partName = reinterpret_cast<const char *>(s->data().data());
1491
23
  for (Partition &part : partitions) {
1492
23
    if (part.name == partName) {
1493
3
      sym->partition = part.getNumber();
1494
3
      return;
1495
3
    }
1496
23
  }
1497
17
1498
17
  // Forbid partitions from being used on incompatible targets, and forbid them
1499
17
  // from being used together with various linker features that assume a single
1500
17
  // set of output sections.
1501
17
  
if (14
script->hasSectionsCommand14
)
1502
1
    error(toString(s->file) +
1503
1
          ": partitions cannot be used with the SECTIONS command");
1504
14
  if (script->hasPhdrsCommands())
1505
1
    error(toString(s->file) +
1506
1
          ": partitions cannot be used with the PHDRS command");
1507
14
  if (!config->sectionStartMap.empty())
1508
4
    error(toString(s->file) + ": partitions cannot be used with "
1509
4
                              "--section-start, -Ttext, -Tdata or -Tbss");
1510
14
  if (config->emachine == EM_MIPS)
1511
0
    error(toString(s->file) + ": partitions cannot be used on this target");
1512
14
1513
14
  // Impose a limit of no more than 254 partitions. This limit comes from the
1514
14
  // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1515
14
  // the amount of space devoted to the partition number in RankFlags.
1516
14
  if (partitions.size() == 254)
1517
0
    fatal("may not have more than 254 partitions");
1518
14
1519
14
  partitions.emplace_back();
1520
14
  Partition &newPart = partitions.back();
1521
14
  newPart.name = partName;
1522
14
  sym->partition = newPart.getNumber();
1523
14
}
Unexecuted instantiation: Driver.cpp:void readSymbolPartitionSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::InputSectionBase*)
1524
1525
168
static Symbol *addUndefined(StringRef name) {
1526
168
  return symtab->addSymbol(
1527
168
      Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1528
168
}
1529
1530
// This function is where all the optimizations of link-time
1531
// optimization takes place. When LTO is in use, some input files are
1532
// not in native object file format but in the LLVM bitcode format.
1533
// This function compiles bitcode files into a few big native files
1534
// using LLVM functions and replaces bitcode symbols with the results.
1535
// Because all bitcode files that the program consists of are passed to
1536
// the compiler at once, it can do a whole-program optimization.
1537
2.78k
template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1538
2.78k
  // Compile bitcode files and replace bitcode symbols.
1539
2.78k
  lto.reset(new BitcodeCompiler);
1540
2.78k
  for (BitcodeFile *file : bitcodeFiles)
1541
253
    lto->add(*file);
1542
2.78k
1543
2.78k
  for (InputFile *file : lto->compile()) {
1544
214
    auto *obj = cast<ObjFile<ELFT>>(file);
1545
214
    obj->parse(/*ignoreComdats=*/true);
1546
214
    for (Symbol *sym : obj->getGlobalSymbols())
1547
263
      sym->parseSymbolVersion();
1548
214
    objectFiles.push_back(file);
1549
214
  }
1550
2.78k
}
void lld::elf::LinkerDriver::compileBitcodeFiles<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
1537
376
template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1538
376
  // Compile bitcode files and replace bitcode symbols.
1539
376
  lto.reset(new BitcodeCompiler);
1540
376
  for (BitcodeFile *file : bitcodeFiles)
1541
2
    lto->add(*file);
1542
376
1543
376
  for (InputFile *file : lto->compile()) {
1544
2
    auto *obj = cast<ObjFile<ELFT>>(file);
1545
2
    obj->parse(/*ignoreComdats=*/true);
1546
2
    for (Symbol *sym : obj->getGlobalSymbols())
1547
1
      sym->parseSymbolVersion();
1548
2
    objectFiles.push_back(file);
1549
2
  }
1550
376
}
void lld::elf::LinkerDriver::compileBitcodeFiles<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
1537
157
template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1538
157
  // Compile bitcode files and replace bitcode symbols.
1539
157
  lto.reset(new BitcodeCompiler);
1540
157
  for (BitcodeFile *file : bitcodeFiles)
1541
0
    lto->add(*file);
1542
157
1543
157
  for (InputFile *file : lto->compile()) {
1544
0
    auto *obj = cast<ObjFile<ELFT>>(file);
1545
0
    obj->parse(/*ignoreComdats=*/true);
1546
0
    for (Symbol *sym : obj->getGlobalSymbols())
1547
0
      sym->parseSymbolVersion();
1548
0
    objectFiles.push_back(file);
1549
0
  }
1550
157
}
void lld::elf::LinkerDriver::compileBitcodeFiles<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
1537
2.13k
template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1538
2.13k
  // Compile bitcode files and replace bitcode symbols.
1539
2.13k
  lto.reset(new BitcodeCompiler);
1540
2.13k
  for (BitcodeFile *file : bitcodeFiles)
1541
251
    lto->add(*file);
1542
2.13k
1543
2.13k
  for (InputFile *file : lto->compile()) {
1544
212
    auto *obj = cast<ObjFile<ELFT>>(file);
1545
212
    obj->parse(/*ignoreComdats=*/true);
1546
212
    for (Symbol *sym : obj->getGlobalSymbols())
1547
262
      sym->parseSymbolVersion();
1548
212
    objectFiles.push_back(file);
1549
212
  }
1550
2.13k
}
void lld::elf::LinkerDriver::compileBitcodeFiles<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
1537
108
template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1538
108
  // Compile bitcode files and replace bitcode symbols.
1539
108
  lto.reset(new BitcodeCompiler);
1540
108
  for (BitcodeFile *file : bitcodeFiles)
1541
0
    lto->add(*file);
1542
108
1543
108
  for (InputFile *file : lto->compile()) {
1544
0
    auto *obj = cast<ObjFile<ELFT>>(file);
1545
0
    obj->parse(/*ignoreComdats=*/true);
1546
0
    for (Symbol *sym : obj->getGlobalSymbols())
1547
0
      sym->parseSymbolVersion();
1548
0
    objectFiles.push_back(file);
1549
0
  }
1550
108
}
1551
1552
// The --wrap option is a feature to rename symbols so that you can write
1553
// wrappers for existing functions. If you pass `-wrap=foo`, all
1554
// occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1555
// expected to write `wrap_foo` function as a wrapper). The original
1556
// symbol becomes accessible as `real_foo`, so you can call that from your
1557
// wrapper.
1558
//
1559
// This data structure is instantiated for each -wrap option.
1560
struct WrappedSymbol {
1561
  Symbol *sym;
1562
  Symbol *real;
1563
  Symbol *wrap;
1564
};
1565
1566
// Handles -wrap option.
1567
//
1568
// This function instantiates wrapper symbols. At this point, they seem
1569
// like they are not being used at all, so we explicitly set some flags so
1570
// that LTO won't eliminate them.
1571
2.97k
static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1572
2.97k
  std::vector<WrappedSymbol> v;
1573
2.97k
  DenseSet<StringRef> seen;
1574
2.97k
1575
2.97k
  for (auto *arg : args.filtered(OPT_wrap)) {
1576
20
    StringRef name = arg->getValue();
1577
20
    if (!seen.insert(name).second)
1578
1
      continue;
1579
19
1580
19
    Symbol *sym = symtab->find(name);
1581
19
    if (!sym)
1582
4
      continue;
1583
15
1584
15
    Symbol *real = addUndefined(saver.save("__real_" + name));
1585
15
    Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
1586
15
    v.push_back({sym, real, wrap});
1587
15
1588
15
    // We want to tell LTO not to inline symbols to be overwritten
1589
15
    // because LTO doesn't know the final symbol contents after renaming.
1590
15
    real->canInline = false;
1591
15
    sym->canInline = false;
1592
15
1593
15
    // Tell LTO not to eliminate these symbols.
1594
15
    sym->isUsedInRegularObj = true;
1595
15
    wrap->isUsedInRegularObj = true;
1596
15
  }
1597
2.97k
  return v;
1598
2.97k
}
1599
1600
// Do renaming for -wrap by updating pointers to symbols.
1601
//
1602
// When this function is executed, only InputFiles and symbol table
1603
// contain pointers to symbol objects. We visit them to replace pointers,
1604
// so that wrapped symbols are swapped as instructed by the command line.
1605
15
static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1606
15
  DenseMap<Symbol *, Symbol *> map;
1607
15
  for (const WrappedSymbol &w : wrapped) {
1608
15
    map[w.sym] = w.wrap;
1609
15
    map[w.real] = w.sym;
1610
15
  }
1611
15
1612
15
  // Update pointers in input files.
1613
22
  parallelForEach(objectFiles, [&](InputFile *file) {
1614
22
    MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1615
123
    for (size_t i = 0, e = syms.size(); i != e; 
++i101
)
1616
101
      if (Symbol *s = map.lookup(syms[i]))
1617
32
        syms[i] = s;
1618
22
  });
1619
15
1620
15
  // Update pointers in the symbol table.
1621
15
  for (const WrappedSymbol &w : wrapped)
1622
15
    symtab->wrap(w.sym, w.real, w.wrap);
1623
15
}
1624
1625
// To enable CET (x86's hardware-assited control flow enforcement), each
1626
// source file must be compiled with -fcf-protection. Object files compiled
1627
// with the flag contain feature flags indicating that they are compatible
1628
// with CET. We enable the feature only when all object files are compatible
1629
// with CET.
1630
//
1631
// This function returns the merged feature flags. If 0, we cannot enable CET.
1632
// This is also the case with AARCH64's BTI and PAC which use the similar
1633
// GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
1634
//
1635
// Note that the CET-aware PLT is not implemented yet. We do error
1636
// check only.
1637
2.75k
template <class ELFT> static uint32_t getAndFeatures() {
1638
2.75k
  if (config->emachine != EM_386 && 
config->emachine != EM_X86_642.61k
&&
1639
2.75k
      
config->emachine != EM_AARCH64771
)
1640
648
    return 0;
1641
2.10k
1642
2.10k
  uint32_t ret = -1;
1643
2.54k
  for (InputFile *f : objectFiles) {
1644
2.54k
    uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1645
2.54k
    if (config->forceBTI && 
!(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)4
) {
1646
2
      warn(toString(f) + ": --force-bti: file does not have BTI property");
1647
2
      features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1648
2.54k
    } else if (!features && 
config->requireCET2.50k
)
1649
2
      error(toString(f) + ": --require-cet: file is not compatible with CET");
1650
2.54k
    ret &= features;
1651
2.54k
  }
1652
2.10k
1653
2.10k
  // Force enable pointer authentication Plt, we don't warn in this case as
1654
2.10k
  // this does not require support in the object for correctness.
1655
2.10k
  if (config->pacPlt)
1656
2
    ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1657
2.10k
1658
2.10k
  return ret;
1659
2.10k
}
Driver.cpp:unsigned int getAndFeatures<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
1637
376
template <class ELFT> static uint32_t getAndFeatures() {
1638
376
  if (config->emachine != EM_386 && 
config->emachine != EM_X86_64240
&&
1639
376
      
config->emachine != EM_AARCH64236
)
1640
236
    return 0;
1641
140
1642
140
  uint32_t ret = -1;
1643
152
  for (InputFile *f : objectFiles) {
1644
152
    uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1645
152
    if (config->forceBTI && 
!(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)0
) {
1646
0
      warn(toString(f) + ": --force-bti: file does not have BTI property");
1647
0
      features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1648
152
    } else if (!features && 
config->requireCET144
)
1649
1
      error(toString(f) + ": --require-cet: file is not compatible with CET");
1650
152
    ret &= features;
1651
152
  }
1652
140
1653
140
  // Force enable pointer authentication Plt, we don't warn in this case as
1654
140
  // this does not require support in the object for correctness.
1655
140
  if (config->pacPlt)
1656
0
    ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1657
140
1658
140
  return ret;
1659
140
}
Driver.cpp:unsigned int getAndFeatures<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
1637
157
template <class ELFT> static uint32_t getAndFeatures() {
1638
157
  if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1639
157
      config->emachine != EM_AARCH64)
1640
157
    return 0;
1641
0
1642
0
  uint32_t ret = -1;
1643
0
  for (InputFile *f : objectFiles) {
1644
0
    uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1645
0
    if (config->forceBTI && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1646
0
      warn(toString(f) + ": --force-bti: file does not have BTI property");
1647
0
      features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1648
0
    } else if (!features && config->requireCET)
1649
0
      error(toString(f) + ": --require-cet: file is not compatible with CET");
1650
0
    ret &= features;
1651
0
  }
1652
0
1653
0
  // Force enable pointer authentication Plt, we don't warn in this case as
1654
0
  // this does not require support in the object for correctness.
1655
0
  if (config->pacPlt)
1656
0
    ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1657
0
1658
0
  return ret;
1659
0
}
Driver.cpp:unsigned int getAndFeatures<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
1637
2.11k
template <class ELFT> static uint32_t getAndFeatures() {
1638
2.11k
  if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1639
2.11k
      
config->emachine != EM_AARCH64270
)
1640
147
    return 0;
1641
1.96k
1642
1.96k
  uint32_t ret = -1;
1643
2.39k
  for (InputFile *f : objectFiles) {
1644
2.39k
    uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1645
2.39k
    if (config->forceBTI && 
!(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)4
) {
1646
2
      warn(toString(f) + ": --force-bti: file does not have BTI property");
1647
2
      features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1648
2.39k
    } else if (!features && 
config->requireCET2.36k
)
1649
1
      error(toString(f) + ": --require-cet: file is not compatible with CET");
1650
2.39k
    ret &= features;
1651
2.39k
  }
1652
1.96k
1653
1.96k
  // Force enable pointer authentication Plt, we don't warn in this case as
1654
1.96k
  // this does not require support in the object for correctness.
1655
1.96k
  if (config->pacPlt)
1656
2
    ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1657
1.96k
1658
1.96k
  return ret;
1659
1.96k
}
Driver.cpp:unsigned int getAndFeatures<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
1637
108
template <class ELFT> static uint32_t getAndFeatures() {
1638
108
  if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1639
108
      config->emachine != EM_AARCH64)
1640
108
    return 0;
1641
0
1642
0
  uint32_t ret = -1;
1643
0
  for (InputFile *f : objectFiles) {
1644
0
    uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1645
0
    if (config->forceBTI && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1646
0
      warn(toString(f) + ": --force-bti: file does not have BTI property");
1647
0
      features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1648
0
    } else if (!features && config->requireCET)
1649
0
      error(toString(f) + ": --require-cet: file is not compatible with CET");
1650
0
    ret &= features;
1651
0
  }
1652
0
1653
0
  // Force enable pointer authentication Plt, we don't warn in this case as
1654
0
  // this does not require support in the object for correctness.
1655
0
  if (config->pacPlt)
1656
0
    ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1657
0
1658
0
  return ret;
1659
0
}
1660
1661
static const char *libcallRoutineNames[] = {
1662
#define HANDLE_LIBCALL(code, name) name,
1663
#include "llvm/IR/RuntimeLibcalls.def"
1664
#undef HANDLE_LIBCALL
1665
};
1666
1667
// Do actual linking. Note that when this function is called,
1668
// all linker scripts have already been parsed.
1669
2.85k
template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1670
2.85k
  // If a -hash-style option was not given, set to a default value,
1671
2.85k
  // which varies depending on the target.
1672
2.85k
  if (!args.hasArg(OPT_hash_style)) {
1673
2.70k
    if (config->emachine == EM_MIPS)
1674
200
      config->sysvHash = true;
1675
2.50k
    else
1676
2.50k
      config->sysvHash = config->gnuHash = true;
1677
2.70k
  }
1678
2.85k
1679
2.85k
  // Default output filename is "a.out" by the Unix tradition.
1680
2.85k
  if (config->outputFile.empty())
1681
14
    config->outputFile = "a.out";
1682
2.85k
1683
2.85k
  // Fail early if the output file or map file is not writable. If a user has a
1684
2.85k
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1685
2.85k
  // find that it failed because there was a mistake in their command-line.
1686
2.85k
  if (auto e = tryCreateFile(config->outputFile))
1687
8
    error("cannot open output file " + config->outputFile + ": " + e.message());
1688
2.85k
  if (auto e = tryCreateFile(config->mapFile))
1689
3
    error("cannot open map file " + config->mapFile + ": " + e.message());
1690
2.85k
  if (errorCount())
1691
11
    return;
1692
2.84k
1693
2.84k
  // Use default entry point name if no name was given via the command
1694
2.84k
  // line nor linker scripts. For some reason, MIPS entry point name is
1695
2.84k
  // different from others.
1696
2.84k
  config->warnMissingEntry =
1697
2.84k
      (!config->entry.empty() || 
(2.76k
!config->shared2.76k
&&
!config->relocatable1.80k
));
1698
2.84k
  if (config->entry.empty() && 
!config->relocatable2.76k
)
1699
2.67k
    config->entry = (config->emachine == EM_MIPS) ? 
"__start"165
:
"_start"2.50k
;
1700
2.84k
1701
2.84k
  // Handle --trace-symbol.
1702
2.84k
  for (auto *arg : args.filtered(OPT_trace_symbol))
1703
35
    symtab->insert(arg->getValue())->traced = true;
1704
2.84k
1705
2.84k
  // Add all files to the symbol table. This will add almost all
1706
2.84k
  // symbols that we need to the symbol table. This process might
1707
2.84k
  // add files to the link, via autolinking, these files are always
1708
2.84k
  // appended to the Files vector.
1709
6.81k
  for (size_t i = 0; i < files.size(); 
++i3.97k
)
1710
3.97k
    parseFile(files[i]);
1711
2.84k
1712
2.84k
  // Now that we have every file, we can decide if we will need a
1713
2.84k
  // dynamic symbol table.
1714
2.84k
  // We need one if we were asked to export dynamic symbols or if we are
1715
2.84k
  // producing a shared library.
1716
2.84k
  // We also need one if any shared libraries are used and for pie executables
1717
2.84k
  // (probably because the dynamic linker needs it).
1718
2.84k
  config->hasDynSymTab =
1719
2.84k
      !sharedFiles.empty() || 
config->isPic2.46k
||
config->exportDynamic1.50k
;
1720
2.84k
1721
2.84k
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1722
2.84k
  // are undefined symbols for them, so we add these to trigger that logic.
1723
2.84k
  for (StringRef name : script->referencedSymbols)
1724
138
    addUndefined(name);
1725
2.84k
1726
2.84k
  // Handle the `--undefined <sym>` options.
1727
2.84k
  for (StringRef arg : config->undefined)
1728
28
    if (Symbol *sym = symtab->find(arg))
1729
23
      handleUndefined(sym);
1730
2.84k
1731
2.84k
  // If an entry symbol is in a static archive, pull out that file now.
1732
2.84k
  if (Symbol *sym = symtab->find(config->entry))
1733
1.44k
    handleUndefined(sym);
1734
2.84k
1735
2.84k
  // Handle the `--undefined-glob <pattern>` options.
1736
2.84k
  for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1737
5
    handleUndefinedGlob(pat);
1738
2.84k
1739
2.84k
  // If any of our inputs are bitcode files, the LTO code generator may create
1740
2.84k
  // references to certain library functions that might not be explicit in the
1741
2.84k
  // bitcode file's symbol table. If any of those library functions are defined
1742
2.84k
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1743
2.84k
  // compile those archive members by adding them to the link beforehand.
1744
2.84k
  //
1745
2.84k
  // However, adding all libcall symbols to the link can have undesired
1746
2.84k
  // consequences. For example, the libgcc implementation of
1747
2.84k
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1748
2.84k
  // that aborts the program if the Linux kernel does not support 64-bit
1749
2.84k
  // atomics, which would prevent the program from running even if it does not
1750
2.84k
  // use 64-bit atomics.
1751
2.84k
  //
1752
2.84k
  // Therefore, we only add libcall symbols to the link before LTO if we have
1753
2.84k
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1754
2.84k
  // libcall symbols will be added to the link after LTO when we add the LTO
1755
2.84k
  // object file to the link.
1756
2.84k
  if (!bitcodeFiles.empty())
1757
181
    for (const char *s : libcallRoutineNames)
1758
89.0k
      handleLibcall(s);
1759
2.84k
1760
2.84k
  // Return if there were name resolution errors.
1761
2.84k
  if (errorCount())
1762
61
    return;
1763
2.78k
1764
2.78k
  // Now when we read all script files, we want to finalize order of linker
1765
2.78k
  // script commands, which can be not yet final because of INSERT commands.
1766
2.78k
  script->processInsertCommands();
1767
2.78k
1768
2.78k
  // We want to declare linker script's symbols early,
1769
2.78k
  // so that we can version them.
1770
2.78k
  // They also might be exported if referenced by DSOs.
1771
2.78k
  script->declareSymbols();
1772
2.78k
1773
2.78k
  // Handle the -exclude-libs option.
1774
2.78k
  if (args.hasArg(OPT_exclude_libs))
1775
8
    excludeLibs(args);
1776
2.78k
1777
2.78k
  // Create elfHeader early. We need a dummy section in
1778
2.78k
  // addReservedSymbols to mark the created symbols as not absolute.
1779
2.78k
  Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1780
2.78k
  Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1781
2.78k
1782
2.78k
  // Create wrapped symbols for -wrap option.
1783
2.78k
  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1784
2.78k
1785
2.78k
  // We need to create some reserved symbols such as _end. Create them.
1786
2.78k
  if (!config->relocatable)
1787
2.69k
    addReservedSymbols();
1788
2.78k
1789
2.78k
  // Apply version scripts.
1790
2.78k
  //
1791
2.78k
  // For a relocatable output, version scripts don't make sense, and
1792
2.78k
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1793
2.78k
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1794
2.78k
  if (!config->relocatable)
1795
2.69k
    symtab->scanVersionScript();
1796
2.78k
1797
2.78k
  // Do link-time optimization if given files are LLVM bitcode files.
1798
2.78k
  // This compiles bitcode files into real object files.
1799
2.78k
  //
1800
2.78k
  // With this the symbol table should be complete. After this, no new names
1801
2.78k
  // except a few linker-synthesized ones will be added to the symbol table.
1802
2.78k
  compileBitcodeFiles<ELFT>();
1803
2.78k
  if (errorCount())
1804
12
    return;
1805
2.76k
1806
2.76k
  // If -thinlto-index-only is given, we should create only "index
1807
2.76k
  // files" and not object files. Index file creation is already done
1808
2.76k
  // in addCombinedLTOObject, so we are done if that's the case.
1809
2.76k
  if (config->thinLTOIndexOnly)
1810
12
    return;
1811
2.75k
1812
2.75k
  // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1813
2.75k
  // an output file in bitcode and exit, so that you can just get a
1814
2.75k
  // combined bitcode file.
1815
2.75k
  if (config->emitLLVM)
1816
1
    return;
1817
2.75k
1818
2.75k
  // Apply symbol renames for -wrap.
1819
2.75k
  if (!wrapped.empty())
1820
13
    wrapSymbols(wrapped);
1821
2.75k
1822
2.75k
  // Now that we have a complete list of input files.
1823
2.75k
  // Beyond this point, no new files are added.
1824
2.75k
  // Aggregate all input sections into one place.
1825
2.75k
  for (InputFile *f : objectFiles)
1826
3.37k
    for (InputSectionBase *s : f->getSections())
1827
350k
      if (s && 
s != &InputSection::discarded337k
)
1828
337k
        inputSections.push_back(s);
1829
2.75k
  for (BinaryFile *f : binaryFiles)
1830
6
    for (InputSectionBase *s : f->getSections())
1831
6
      inputSections.push_back(cast<InputSection>(s));
1832
2.75k
1833
337k
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
337k
    if (s->type == SHT_LLVM_SYMPART) {
1835
21
      readSymbolPartitionSection<ELFT>(s);
1836
21
      return true;
1837
21
    }
1838
337k
1839
337k
    // We do not want to emit debug sections if --strip-all
1840
337k
    // or -strip-debug are given.
1841
337k
    return config->strip != StripPolicy::None &&
1842
337k
           
(12
s->name.startswith(".debug")12
||
s->name.startswith(".zdebug")6
);
1843
337k
  });
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
Line
Count
Source
1833
1.37k
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
1.37k
    if (s->type == SHT_LLVM_SYMPART) {
1835
4
      readSymbolPartitionSection<ELFT>(s);
1836
4
      return true;
1837
4
    }
1838
1.37k
1839
1.37k
    // We do not want to emit debug sections if --strip-all
1840
1.37k
    // or -strip-debug are given.
1841
1.37k
    return config->strip != StripPolicy::None &&
1842
1.37k
           
(0
s->name.startswith(".debug")0
||
s->name.startswith(".zdebug")0
);
1843
1.37k
  });
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
Line
Count
Source
1833
964
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
964
    if (s->type == SHT_LLVM_SYMPART) {
1835
0
      readSymbolPartitionSection<ELFT>(s);
1836
0
      return true;
1837
0
    }
1838
964
1839
964
    // We do not want to emit debug sections if --strip-all
1840
964
    // or -strip-debug are given.
1841
964
    return config->strip != StripPolicy::None &&
1842
964
           
(0
s->name.startswith(".debug")0
||
s->name.startswith(".zdebug")0
);
1843
964
  });
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
1833
334k
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
334k
    if (s->type == SHT_LLVM_SYMPART) {
1835
17
      readSymbolPartitionSection<ELFT>(s);
1836
17
      return true;
1837
17
    }
1838
334k
1839
334k
    // We do not want to emit debug sections if --strip-all
1840
334k
    // or -strip-debug are given.
1841
334k
    return config->strip != StripPolicy::None &&
1842
334k
           
(12
s->name.startswith(".debug")12
||
s->name.startswith(".zdebug")6
);
1843
334k
  });
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
Line
Count
Source
1833
401
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
401
    if (s->type == SHT_LLVM_SYMPART) {
1835
0
      readSymbolPartitionSection<ELFT>(s);
1836
0
      return true;
1837
0
    }
1838
401
1839
401
    // We do not want to emit debug sections if --strip-all
1840
401
    // or -strip-debug are given.
1841
401
    return config->strip != StripPolicy::None &&
1842
401
           
(0
s->name.startswith(".debug")0
||
s->name.startswith(".zdebug")0
);
1843
401
  });
1844
2.75k
1845
2.75k
  // Now that the number of partitions is fixed, save a pointer to the main
1846
2.75k
  // partition.
1847
2.75k
  mainPart = &partitions[0];
1848
2.75k
1849
2.75k
  // Read .note.gnu.property sections from input object files which
1850
2.75k
  // contain a hint to tweak linker's and loader's behaviors.
1851
2.75k
  config->andFeatures = getAndFeatures<ELFT>();
1852
2.75k
1853
2.75k
  // The Target instance handles target-specific stuff, such as applying
1854
2.75k
  // relocations or writing a PLT section. It also contains target-dependent
1855
2.75k
  // values such as a default image base address.
1856
2.75k
  target = getTarget();
1857
2.75k
1858
2.75k
  config->eflags = target->calcEFlags();
1859
2.75k
  // maxPageSize (sometimes called abi page size) is the maximum page size that
1860
2.75k
  // the output can be run on. For example if the OS can use 4k or 64k page
1861
2.75k
  // sizes then maxPageSize must be 64k for the output to be useable on both.
1862
2.75k
  // All important alignment decisions must use this value.
1863
2.75k
  config->maxPageSize = getMaxPageSize(args);
1864
2.75k
  // commonPageSize is the most common page size that the output will be run on.
1865
2.75k
  // For example if an OS can use 4k or 64k page sizes and 4k is more common
1866
2.75k
  // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1867
2.75k
  // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1868
2.75k
  // is limited to writing trap instructions on the last executable segment.
1869
2.75k
  config->commonPageSize = getCommonPageSize(args);
1870
2.75k
1871
2.75k
  config->imageBase = getImageBase(args);
1872
2.75k
1873
2.75k
  if (config->emachine == EM_ARM) {
1874
159
    // FIXME: These warnings can be removed when lld only uses these features
1875
159
    // when the input objects have been compiled with an architecture that
1876
159
    // supports them.
1877
159
    if (config->armHasBlx == false)
1878
94
      warn("lld uses blx instruction, no object with architecture supporting "
1879
94
           "feature detected");
1880
159
  }
1881
2.75k
1882
2.75k
  // This adds a .comment section containing a version string. We have to add it
1883
2.75k
  // before mergeSections because the .comment section is a mergeable section.
1884
2.75k
  if (!config->relocatable)
1885
2.66k
    inputSections.push_back(createCommentSection());
1886
2.75k
1887
2.75k
  // Replace common symbols with regular symbols.
1888
2.75k
  replaceCommonSymbols();
1889
2.75k
1890
2.75k
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1891
2.75k
  // and identical code folding.
1892
2.75k
  splitSections<ELFT>();
1893
2.75k
  markLive<ELFT>();
1894
2.75k
  demoteSharedSymbols();
1895
2.75k
  mergeSections();
1896
2.75k
  if (config->icf != ICFLevel::None) {
1897
61
    findKeepUniqueSections<ELFT>(args);
1898
61
    doIcf<ELFT>();
1899
61
  }
1900
2.75k
1901
2.75k
  // Read the callgraph now that we know what was gced or icfed
1902
2.75k
  if (config->callGraphProfileSort) {
1903
2.71k
    if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1904
11
      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1905
11
        readCallGraph(*buffer);
1906
2.71k
    readCallGraphsFromObjectFiles<ELFT>();
1907
2.71k
  }
1908
2.75k
1909
2.75k
  // Write the result to the file.
1910
2.75k
  writeResult<ELFT>();
1911
2.75k
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)
Line
Count
Source
1669
392
template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1670
392
  // If a -hash-style option was not given, set to a default value,
1671
392
  // which varies depending on the target.
1672
392
  if (!args.hasArg(OPT_hash_style)) {
1673
354
    if (config->emachine == EM_MIPS)
1674
24
      config->sysvHash = true;
1675
330
    else
1676
330
      config->sysvHash = config->gnuHash = true;
1677
354
  }
1678
392
1679
392
  // Default output filename is "a.out" by the Unix tradition.
1680
392
  if (config->outputFile.empty())
1681
1
    config->outputFile = "a.out";
1682
392
1683
392
  // Fail early if the output file or map file is not writable. If a user has a
1684
392
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1685
392
  // find that it failed because there was a mistake in their command-line.
1686
392
  if (auto e = tryCreateFile(config->outputFile))
1687
0
    error("cannot open output file " + config->outputFile + ": " + e.message());
1688
392
  if (auto e = tryCreateFile(config->mapFile))
1689
0
    error("cannot open map file " + config->mapFile + ": " + e.message());
1690
392
  if (errorCount())
1691
0
    return;
1692
392
1693
392
  // Use default entry point name if no name was given via the command
1694
392
  // line nor linker scripts. For some reason, MIPS entry point name is
1695
392
  // different from others.
1696
392
  config->warnMissingEntry =
1697
392
      (!config->entry.empty() || 
(376
!config->shared376
&&
!config->relocatable257
));
1698
392
  if (config->entry.empty() && 
!config->relocatable376
)
1699
365
    config->entry = (config->emachine == EM_MIPS) ? 
"__start"15
:
"_start"350
;
1700
392
1701
392
  // Handle --trace-symbol.
1702
392
  for (auto *arg : args.filtered(OPT_trace_symbol))
1703
0
    symtab->insert(arg->getValue())->traced = true;
1704
392
1705
392
  // Add all files to the symbol table. This will add almost all
1706
392
  // symbols that we need to the symbol table. This process might
1707
392
  // add files to the link, via autolinking, these files are always
1708
392
  // appended to the Files vector.
1709
927
  for (size_t i = 0; i < files.size(); 
++i535
)
1710
535
    parseFile(files[i]);
1711
392
1712
392
  // Now that we have every file, we can decide if we will need a
1713
392
  // dynamic symbol table.
1714
392
  // We need one if we were asked to export dynamic symbols or if we are
1715
392
  // producing a shared library.
1716
392
  // We also need one if any shared libraries are used and for pie executables
1717
392
  // (probably because the dynamic linker needs it).
1718
392
  config->hasDynSymTab =
1719
392
      !sharedFiles.empty() || 
config->isPic340
||
config->exportDynamic210
;
1720
392
1721
392
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1722
392
  // are undefined symbols for them, so we add these to trigger that logic.
1723
392
  for (StringRef name : script->referencedSymbols)
1724
30
    addUndefined(name);
1725
392
1726
392
  // Handle the `--undefined <sym>` options.
1727
392
  for (StringRef arg : config->undefined)
1728
0
    if (Symbol *sym = symtab->find(arg))
1729
0
      handleUndefined(sym);
1730
392
1731
392
  // If an entry symbol is in a static archive, pull out that file now.
1732
392
  if (Symbol *sym = symtab->find(config->entry))
1733
236
    handleUndefined(sym);
1734
392
1735
392
  // Handle the `--undefined-glob <pattern>` options.
1736
392
  for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1737
0
    handleUndefinedGlob(pat);
1738
392
1739
392
  // If any of our inputs are bitcode files, the LTO code generator may create
1740
392
  // references to certain library functions that might not be explicit in the
1741
392
  // bitcode file's symbol table. If any of those library functions are defined
1742
392
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1743
392
  // compile those archive members by adding them to the link beforehand.
1744
392
  //
1745
392
  // However, adding all libcall symbols to the link can have undesired
1746
392
  // consequences. For example, the libgcc implementation of
1747
392
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1748
392
  // that aborts the program if the Linux kernel does not support 64-bit
1749
392
  // atomics, which would prevent the program from running even if it does not
1750
392
  // use 64-bit atomics.
1751
392
  //
1752
392
  // Therefore, we only add libcall symbols to the link before LTO if we have
1753
392
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1754
392
  // libcall symbols will be added to the link after LTO when we add the LTO
1755
392
  // object file to the link.
1756
392
  if (!bitcodeFiles.empty())
1757
3
    for (const char *s : libcallRoutineNames)
1758
1.47k
      handleLibcall(s);
1759
392
1760
392
  // Return if there were name resolution errors.
1761
392
  if (errorCount())
1762
16
    return;
1763
376
1764
376
  // Now when we read all script files, we want to finalize order of linker
1765
376
  // script commands, which can be not yet final because of INSERT commands.
1766
376
  script->processInsertCommands();
1767
376
1768
376
  // We want to declare linker script's symbols early,
1769
376
  // so that we can version them.
1770
376
  // They also might be exported if referenced by DSOs.
1771
376
  script->declareSymbols();
1772
376
1773
376
  // Handle the -exclude-libs option.
1774
376
  if (args.hasArg(OPT_exclude_libs))
1775
0
    excludeLibs(args);
1776
376
1777
376
  // Create elfHeader early. We need a dummy section in
1778
376
  // addReservedSymbols to mark the created symbols as not absolute.
1779
376
  Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1780
376
  Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1781
376
1782
376
  // Create wrapped symbols for -wrap option.
1783
376
  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1784
376
1785
376
  // We need to create some reserved symbols such as _end. Create them.
1786
376
  if (!config->relocatable)
1787
365
    addReservedSymbols();
1788
376
1789
376
  // Apply version scripts.
1790
376
  //
1791
376
  // For a relocatable output, version scripts don't make sense, and
1792
376
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1793
376
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1794
376
  if (!config->relocatable)
1795
365
    symtab->scanVersionScript();
1796
376
1797
376
  // Do link-time optimization if given files are LLVM bitcode files.
1798
376
  // This compiles bitcode files into real object files.
1799
376
  //
1800
376
  // With this the symbol table should be complete. After this, no new names
1801
376
  // except a few linker-synthesized ones will be added to the symbol table.
1802
376
  compileBitcodeFiles<ELFT>();
1803
376
  if (errorCount())
1804
0
    return;
1805
376
1806
376
  // If -thinlto-index-only is given, we should create only "index
1807
376
  // files" and not object files. Index file creation is already done
1808
376
  // in addCombinedLTOObject, so we are done if that's the case.
1809
376
  if (config->thinLTOIndexOnly)
1810
0
    return;
1811
376
1812
376
  // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1813
376
  // an output file in bitcode and exit, so that you can just get a
1814
376
  // combined bitcode file.
1815
376
  if (config->emitLLVM)
1816
0
    return;
1817
376
1818
376
  // Apply symbol renames for -wrap.
1819
376
  if (!wrapped.empty())
1820
0
    wrapSymbols(wrapped);
1821
376
1822
376
  // Now that we have a complete list of input files.
1823
376
  // Beyond this point, no new files are added.
1824
376
  // Aggregate all input sections into one place.
1825
376
  for (InputFile *f : objectFiles)
1826
436
    for (InputSectionBase *s : f->getSections())
1827
3.12k
      if (s && 
s != &InputSection::discarded1.40k
)
1828
1.37k
        inputSections.push_back(s);
1829
376
  for (BinaryFile *f : binaryFiles)
1830
0
    for (InputSectionBase *s : f->getSections())
1831
0
      inputSections.push_back(cast<InputSection>(s));
1832
376
1833
376
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
376
    if (s->type == SHT_LLVM_SYMPART) {
1835
376
      readSymbolPartitionSection<ELFT>(s);
1836
376
      return true;
1837
376
    }
1838
376
1839
376
    // We do not want to emit debug sections if --strip-all
1840
376
    // or -strip-debug are given.
1841
376
    return config->strip != StripPolicy::None &&
1842
376
           (s->name.startswith(".debug") || s->name.startswith(".zdebug"));
1843
376
  });
1844
376
1845
376
  // Now that the number of partitions is fixed, save a pointer to the main
1846
376
  // partition.
1847
376
  mainPart = &partitions[0];
1848
376
1849
376
  // Read .note.gnu.property sections from input object files which
1850
376
  // contain a hint to tweak linker's and loader's behaviors.
1851
376
  config->andFeatures = getAndFeatures<ELFT>();
1852
376
1853
376
  // The Target instance handles target-specific stuff, such as applying
1854
376
  // relocations or writing a PLT section. It also contains target-dependent
1855
376
  // values such as a default image base address.
1856
376
  target = getTarget();
1857
376
1858
376
  config->eflags = target->calcEFlags();
1859
376
  // maxPageSize (sometimes called abi page size) is the maximum page size that
1860
376
  // the output can be run on. For example if the OS can use 4k or 64k page
1861
376
  // sizes then maxPageSize must be 64k for the output to be useable on both.
1862
376
  // All important alignment decisions must use this value.
1863
376
  config->maxPageSize = getMaxPageSize(args);
1864
376
  // commonPageSize is the most common page size that the output will be run on.
1865
376
  // For example if an OS can use 4k or 64k page sizes and 4k is more common
1866
376
  // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1867
376
  // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1868
376
  // is limited to writing trap instructions on the last executable segment.
1869
376
  config->commonPageSize = getCommonPageSize(args);
1870
376
1871
376
  config->imageBase = getImageBase(args);
1872
376
1873
376
  if (config->emachine == EM_ARM) {
1874
159
    // FIXME: These warnings can be removed when lld only uses these features
1875
159
    // when the input objects have been compiled with an architecture that
1876
159
    // supports them.
1877
159
    if (config->armHasBlx == false)
1878
94
      warn("lld uses blx instruction, no object with architecture supporting "
1879
94
           "feature detected");
1880
159
  }
1881
376
1882
376
  // This adds a .comment section containing a version string. We have to add it
1883
376
  // before mergeSections because the .comment section is a mergeable section.
1884
376
  if (!config->relocatable)
1885
365
    inputSections.push_back(createCommentSection());
1886
376
1887
376
  // Replace common symbols with regular symbols.
1888
376
  replaceCommonSymbols();
1889
376
1890
376
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1891
376
  // and identical code folding.
1892
376
  splitSections<ELFT>();
1893
376
  markLive<ELFT>();
1894
376
  demoteSharedSymbols();
1895
376
  mergeSections();
1896
376
  if (config->icf != ICFLevel::None) {
1897
3
    findKeepUniqueSections<ELFT>(args);
1898
3
    doIcf<ELFT>();
1899
3
  }
1900
376
1901
376
  // Read the callgraph now that we know what was gced or icfed
1902
376
  if (config->callGraphProfileSort) {
1903
375
    if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1904
0
      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1905
0
        readCallGraph(*buffer);
1906
375
    readCallGraphsFromObjectFiles<ELFT>();
1907
375
  }
1908
376
1909
376
  // Write the result to the file.
1910
376
  writeResult<ELFT>();
1911
376
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)
Line
Count
Source
1669
158
template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1670
158
  // If a -hash-style option was not given, set to a default value,
1671
158
  // which varies depending on the target.
1672
158
  if (!args.hasArg(OPT_hash_style)) {
1673
158
    if (config->emachine == EM_MIPS)
1674
127
      config->sysvHash = true;
1675
31
    else
1676
31
      config->sysvHash = config->gnuHash = true;
1677
158
  }
1678
158
1679
158
  // Default output filename is "a.out" by the Unix tradition.
1680
158
  if (config->outputFile.empty())
1681
1
    config->outputFile = "a.out";
1682
158
1683
158
  // Fail early if the output file or map file is not writable. If a user has a
1684
158
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1685
158
  // find that it failed because there was a mistake in their command-line.
1686
158
  if (auto e = tryCreateFile(config->outputFile))
1687
0
    error("cannot open output file " + config->outputFile + ": " + e.message());
1688
158
  if (auto e = tryCreateFile(config->mapFile))
1689
0
    error("cannot open map file " + config->mapFile + ": " + e.message());
1690
158
  if (errorCount())
1691
0
    return;
1692
158
1693
158
  // Use default entry point name if no name was given via the command
1694
158
  // line nor linker scripts. For some reason, MIPS entry point name is
1695
158
  // different from others.
1696
158
  config->warnMissingEntry =
1697
158
      (!config->entry.empty() || 
(151
!config->shared151
&&
!config->relocatable90
));
1698
158
  if (config->entry.empty() && 
!config->relocatable151
)
1699
140
    config->entry = (config->emachine == EM_MIPS) ? 
"__start"109
:
"_start"31
;
1700
158
1701
158
  // Handle --trace-symbol.
1702
158
  for (auto *arg : args.filtered(OPT_trace_symbol))
1703
0
    symtab->insert(arg->getValue())->traced = true;
1704
158
1705
158
  // Add all files to the symbol table. This will add almost all
1706
158
  // symbols that we need to the symbol table. This process might
1707
158
  // add files to the link, via autolinking, these files are always
1708
158
  // appended to the Files vector.
1709
398
  for (size_t i = 0; i < files.size(); 
++i240
)
1710
240
    parseFile(files[i]);
1711
158
1712
158
  // Now that we have every file, we can decide if we will need a
1713
158
  // dynamic symbol table.
1714
158
  // We need one if we were asked to export dynamic symbols or if we are
1715
158
  // producing a shared library.
1716
158
  // We also need one if any shared libraries are used and for pie executables
1717
158
  // (probably because the dynamic linker needs it).
1718
158
  config->hasDynSymTab =
1719
158
      !sharedFiles.empty() || 
config->isPic129
||
config->exportDynamic71
;
1720
158
1721
158
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1722
158
  // are undefined symbols for them, so we add these to trigger that logic.
1723
158
  for (StringRef name : script->referencedSymbols)
1724
0
    addUndefined(name);
1725
158
1726
158
  // Handle the `--undefined <sym>` options.
1727
158
  for (StringRef arg : config->undefined)
1728
0
    if (Symbol *sym = symtab->find(arg))
1729
0
      handleUndefined(sym);
1730
158
1731
158
  // If an entry symbol is in a static archive, pull out that file now.
1732
158
  if (Symbol *sym = symtab->find(config->entry))
1733
88
    handleUndefined(sym);
1734
158
1735
158
  // Handle the `--undefined-glob <pattern>` options.
1736
158
  for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1737
0
    handleUndefinedGlob(pat);
1738
158
1739
158
  // If any of our inputs are bitcode files, the LTO code generator may create
1740
158
  // references to certain library functions that might not be explicit in the
1741
158
  // bitcode file's symbol table. If any of those library functions are defined
1742
158
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1743
158
  // compile those archive members by adding them to the link beforehand.
1744
158
  //
1745
158
  // However, adding all libcall symbols to the link can have undesired
1746
158
  // consequences. For example, the libgcc implementation of
1747
158
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1748
158
  // that aborts the program if the Linux kernel does not support 64-bit
1749
158
  // atomics, which would prevent the program from running even if it does not
1750
158
  // use 64-bit atomics.
1751
158
  //
1752
158
  // Therefore, we only add libcall symbols to the link before LTO if we have
1753
158
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1754
158
  // libcall symbols will be added to the link after LTO when we add the LTO
1755
158
  // object file to the link.
1756
158
  if (!bitcodeFiles.empty())
1757
0
    for (const char *s : libcallRoutineNames)
1758
0
      handleLibcall(s);
1759
158
1760
158
  // Return if there were name resolution errors.
1761
158
  if (errorCount())
1762
1
    return;
1763
157
1764
157
  // Now when we read all script files, we want to finalize order of linker
1765
157
  // script commands, which can be not yet final because of INSERT commands.
1766
157
  script->processInsertCommands();
1767
157
1768
157
  // We want to declare linker script's symbols early,
1769
157
  // so that we can version them.
1770
157
  // They also might be exported if referenced by DSOs.
1771
157
  script->declareSymbols();
1772
157
1773
157
  // Handle the -exclude-libs option.
1774
157
  if (args.hasArg(OPT_exclude_libs))
1775
0
    excludeLibs(args);
1776
157
1777
157
  // Create elfHeader early. We need a dummy section in
1778
157
  // addReservedSymbols to mark the created symbols as not absolute.
1779
157
  Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1780
157
  Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1781
157
1782
157
  // Create wrapped symbols for -wrap option.
1783
157
  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1784
157
1785
157
  // We need to create some reserved symbols such as _end. Create them.
1786
157
  if (!config->relocatable)
1787
146
    addReservedSymbols();
1788
157
1789
157
  // Apply version scripts.
1790
157
  //
1791
157
  // For a relocatable output, version scripts don't make sense, and
1792
157
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1793
157
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1794
157
  if (!config->relocatable)
1795
146
    symtab->scanVersionScript();
1796
157
1797
157
  // Do link-time optimization if given files are LLVM bitcode files.
1798
157
  // This compiles bitcode files into real object files.
1799
157
  //
1800
157
  // With this the symbol table should be complete. After this, no new names
1801
157
  // except a few linker-synthesized ones will be added to the symbol table.
1802
157
  compileBitcodeFiles<ELFT>();
1803
157
  if (errorCount())
1804
0
    return;
1805
157
1806
157
  // If -thinlto-index-only is given, we should create only "index
1807
157
  // files" and not object files. Index file creation is already done
1808
157
  // in addCombinedLTOObject, so we are done if that's the case.
1809
157
  if (config->thinLTOIndexOnly)
1810
0
    return;
1811
157
1812
157
  // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1813
157
  // an output file in bitcode and exit, so that you can just get a
1814
157
  // combined bitcode file.
1815
157
  if (config->emitLLVM)
1816
0
    return;
1817
157
1818
157
  // Apply symbol renames for -wrap.
1819
157
  if (!wrapped.empty())
1820
0
    wrapSymbols(wrapped);
1821
157
1822
157
  // Now that we have a complete list of input files.
1823
157
  // Beyond this point, no new files are added.
1824
157
  // Aggregate all input sections into one place.
1825
157
  for (InputFile *f : objectFiles)
1826
210
    for (InputSectionBase *s : f->getSections())
1827
1.74k
      if (s && 
s != &InputSection::discarded974
)
1828
964
        inputSections.push_back(s);
1829
157
  for (BinaryFile *f : binaryFiles)
1830
0
    for (InputSectionBase *s : f->getSections())
1831
0
      inputSections.push_back(cast<InputSection>(s));
1832
157
1833
157
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
157
    if (s->type == SHT_LLVM_SYMPART) {
1835
157
      readSymbolPartitionSection<ELFT>(s);
1836
157
      return true;
1837
157
    }
1838
157
1839
157
    // We do not want to emit debug sections if --strip-all
1840
157
    // or -strip-debug are given.
1841
157
    return config->strip != StripPolicy::None &&
1842
157
           (s->name.startswith(".debug") || s->name.startswith(".zdebug"));
1843
157
  });
1844
157
1845
157
  // Now that the number of partitions is fixed, save a pointer to the main
1846
157
  // partition.
1847
157
  mainPart = &partitions[0];
1848
157
1849
157
  // Read .note.gnu.property sections from input object files which
1850
157
  // contain a hint to tweak linker's and loader's behaviors.
1851
157
  config->andFeatures = getAndFeatures<ELFT>();
1852
157
1853
157
  // The Target instance handles target-specific stuff, such as applying
1854
157
  // relocations or writing a PLT section. It also contains target-dependent
1855
157
  // values such as a default image base address.
1856
157
  target = getTarget();
1857
157
1858
157
  config->eflags = target->calcEFlags();
1859
157
  // maxPageSize (sometimes called abi page size) is the maximum page size that
1860
157
  // the output can be run on. For example if the OS can use 4k or 64k page
1861
157
  // sizes then maxPageSize must be 64k for the output to be useable on both.
1862
157
  // All important alignment decisions must use this value.
1863
157
  config->maxPageSize = getMaxPageSize(args);
1864
157
  // commonPageSize is the most common page size that the output will be run on.
1865
157
  // For example if an OS can use 4k or 64k page sizes and 4k is more common
1866
157
  // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1867
157
  // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1868
157
  // is limited to writing trap instructions on the last executable segment.
1869
157
  config->commonPageSize = getCommonPageSize(args);
1870
157
1871
157
  config->imageBase = getImageBase(args);
1872
157
1873
157
  if (config->emachine == EM_ARM) {
1874
0
    // FIXME: These warnings can be removed when lld only uses these features
1875
0
    // when the input objects have been compiled with an architecture that
1876
0
    // supports them.
1877
0
    if (config->armHasBlx == false)
1878
0
      warn("lld uses blx instruction, no object with architecture supporting "
1879
0
           "feature detected");
1880
0
  }
1881
157
1882
157
  // This adds a .comment section containing a version string. We have to add it
1883
157
  // before mergeSections because the .comment section is a mergeable section.
1884
157
  if (!config->relocatable)
1885
146
    inputSections.push_back(createCommentSection());
1886
157
1887
157
  // Replace common symbols with regular symbols.
1888
157
  replaceCommonSymbols();
1889
157
1890
157
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1891
157
  // and identical code folding.
1892
157
  splitSections<ELFT>();
1893
157
  markLive<ELFT>();
1894
157
  demoteSharedSymbols();
1895
157
  mergeSections();
1896
157
  if (config->icf != ICFLevel::None) {
1897
0
    findKeepUniqueSections<ELFT>(args);
1898
0
    doIcf<ELFT>();
1899
0
  }
1900
157
1901
157
  // Read the callgraph now that we know what was gced or icfed
1902
157
  if (config->callGraphProfileSort) {
1903
157
    if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1904
0
      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1905
0
        readCallGraph(*buffer);
1906
157
    readCallGraphsFromObjectFiles<ELFT>();
1907
157
  }
1908
157
1909
157
  // Write the result to the file.
1910
157
  writeResult<ELFT>();
1911
157
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)
Line
Count
Source
1669
2.19k
template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1670
2.19k
  // If a -hash-style option was not given, set to a default value,
1671
2.19k
  // which varies depending on the target.
1672
2.19k
  if (!args.hasArg(OPT_hash_style)) {
1673
2.08k
    if (config->emachine == EM_MIPS)
1674
3
      config->sysvHash = true;
1675
2.07k
    else
1676
2.07k
      config->sysvHash = config->gnuHash = true;
1677
2.08k
  }
1678
2.19k
1679
2.19k
  // Default output filename is "a.out" by the Unix tradition.
1680
2.19k
  if (config->outputFile.empty())
1681
12
    config->outputFile = "a.out";
1682
2.19k
1683
2.19k
  // Fail early if the output file or map file is not writable. If a user has a
1684
2.19k
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1685
2.19k
  // find that it failed because there was a mistake in their command-line.
1686
2.19k
  if (auto e = tryCreateFile(config->outputFile))
1687
8
    error("cannot open output file " + config->outputFile + ": " + e.message());
1688
2.19k
  if (auto e = tryCreateFile(config->mapFile))
1689
3
    error("cannot open map file " + config->mapFile + ": " + e.message());
1690
2.19k
  if (errorCount())
1691
11
    return;
1692
2.17k
1693
2.17k
  // Use default entry point name if no name was given via the command
1694
2.17k
  // line nor linker scripts. For some reason, MIPS entry point name is
1695
2.17k
  // different from others.
1696
2.17k
  config->warnMissingEntry =
1697
2.17k
      (!config->entry.empty() || 
(2.12k
!config->shared2.12k
&&
!config->relocatable1.39k
));
1698
2.17k
  if (config->entry.empty() && 
!config->relocatable2.12k
)
1699
2.06k
    config->entry = (config->emachine == EM_MIPS) ? 
"__start"0
: "_start";
1700
2.17k
1701
2.17k
  // Handle --trace-symbol.
1702
2.17k
  for (auto *arg : args.filtered(OPT_trace_symbol))
1703
35
    symtab->insert(arg->getValue())->traced = true;
1704
2.17k
1705
2.17k
  // Add all files to the symbol table. This will add almost all
1706
2.17k
  // symbols that we need to the symbol table. This process might
1707
2.17k
  // add files to the link, via autolinking, these files are always
1708
2.17k
  // appended to the Files vector.
1709
5.22k
  for (size_t i = 0; i < files.size(); 
++i3.04k
)
1710
3.04k
    parseFile(files[i]);
1711
2.17k
1712
2.17k
  // Now that we have every file, we can decide if we will need a
1713
2.17k
  // dynamic symbol table.
1714
2.17k
  // We need one if we were asked to export dynamic symbols or if we are
1715
2.17k
  // producing a shared library.
1716
2.17k
  // We also need one if any shared libraries are used and for pie executables
1717
2.17k
  // (probably because the dynamic linker needs it).
1718
2.17k
  config->hasDynSymTab =
1719
2.17k
      !sharedFiles.empty() || 
config->isPic1.90k
||
config->exportDynamic1.16k
;
1720
2.17k
1721
2.17k
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1722
2.17k
  // are undefined symbols for them, so we add these to trigger that logic.
1723
2.17k
  for (StringRef name : script->referencedSymbols)
1724
104
    addUndefined(name);
1725
2.17k
1726
2.17k
  // Handle the `--undefined <sym>` options.
1727
2.17k
  for (StringRef arg : config->undefined)
1728
28
    if (Symbol *sym = symtab->find(arg))
1729
23
      handleUndefined(sym);
1730
2.17k
1731
2.17k
  // If an entry symbol is in a static archive, pull out that file now.
1732
2.17k
  if (Symbol *sym = symtab->find(config->entry))
1733
1.07k
    handleUndefined(sym);
1734
2.17k
1735
2.17k
  // Handle the `--undefined-glob <pattern>` options.
1736
2.17k
  for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1737
5
    handleUndefinedGlob(pat);
1738
2.17k
1739
2.17k
  // If any of our inputs are bitcode files, the LTO code generator may create
1740
2.17k
  // references to certain library functions that might not be explicit in the
1741
2.17k
  // bitcode file's symbol table. If any of those library functions are defined
1742
2.17k
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1743
2.17k
  // compile those archive members by adding them to the link beforehand.
1744
2.17k
  //
1745
2.17k
  // However, adding all libcall symbols to the link can have undesired
1746
2.17k
  // consequences. For example, the libgcc implementation of
1747
2.17k
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1748
2.17k
  // that aborts the program if the Linux kernel does not support 64-bit
1749
2.17k
  // atomics, which would prevent the program from running even if it does not
1750
2.17k
  // use 64-bit atomics.
1751
2.17k
  //
1752
2.17k
  // Therefore, we only add libcall symbols to the link before LTO if we have
1753
2.17k
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1754
2.17k
  // libcall symbols will be added to the link after LTO when we add the LTO
1755
2.17k
  // object file to the link.
1756
2.17k
  if (!bitcodeFiles.empty())
1757
178
    for (const char *s : libcallRoutineNames)
1758
87.5k
      handleLibcall(s);
1759
2.17k
1760
2.17k
  // Return if there were name resolution errors.
1761
2.17k
  if (errorCount())
1762
40
    return;
1763
2.13k
1764
2.13k
  // Now when we read all script files, we want to finalize order of linker
1765
2.13k
  // script commands, which can be not yet final because of INSERT commands.
1766
2.13k
  script->processInsertCommands();
1767
2.13k
1768
2.13k
  // We want to declare linker script's symbols early,
1769
2.13k
  // so that we can version them.
1770
2.13k
  // They also might be exported if referenced by DSOs.
1771
2.13k
  script->declareSymbols();
1772
2.13k
1773
2.13k
  // Handle the -exclude-libs option.
1774
2.13k
  if (args.hasArg(OPT_exclude_libs))
1775
8
    excludeLibs(args);
1776
2.13k
1777
2.13k
  // Create elfHeader early. We need a dummy section in
1778
2.13k
  // addReservedSymbols to mark the created symbols as not absolute.
1779
2.13k
  Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1780
2.13k
  Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1781
2.13k
1782
2.13k
  // Create wrapped symbols for -wrap option.
1783
2.13k
  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1784
2.13k
1785
2.13k
  // We need to create some reserved symbols such as _end. Create them.
1786
2.13k
  if (!config->relocatable)
1787
2.07k
    addReservedSymbols();
1788
2.13k
1789
2.13k
  // Apply version scripts.
1790
2.13k
  //
1791
2.13k
  // For a relocatable output, version scripts don't make sense, and
1792
2.13k
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1793
2.13k
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1794
2.13k
  if (!config->relocatable)
1795
2.07k
    symtab->scanVersionScript();
1796
2.13k
1797
2.13k
  // Do link-time optimization if given files are LLVM bitcode files.
1798
2.13k
  // This compiles bitcode files into real object files.
1799
2.13k
  //
1800
2.13k
  // With this the symbol table should be complete. After this, no new names
1801
2.13k
  // except a few linker-synthesized ones will be added to the symbol table.
1802
2.13k
  compileBitcodeFiles<ELFT>();
1803
2.13k
  if (errorCount())
1804
12
    return;
1805
2.12k
1806
2.12k
  // If -thinlto-index-only is given, we should create only "index
1807
2.12k
  // files" and not object files. Index file creation is already done
1808
2.12k
  // in addCombinedLTOObject, so we are done if that's the case.
1809
2.12k
  if (config->thinLTOIndexOnly)
1810
12
    return;
1811
2.11k
1812
2.11k
  // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1813
2.11k
  // an output file in bitcode and exit, so that you can just get a
1814
2.11k
  // combined bitcode file.
1815
2.11k
  if (config->emitLLVM)
1816
1
    return;
1817
2.11k
1818
2.11k
  // Apply symbol renames for -wrap.
1819
2.11k
  if (!wrapped.empty())
1820
13
    wrapSymbols(wrapped);
1821
2.11k
1822
2.11k
  // Now that we have a complete list of input files.
1823
2.11k
  // Beyond this point, no new files are added.
1824
2.11k
  // Aggregate all input sections into one place.
1825
2.11k
  for (InputFile *f : objectFiles)
1826
2.58k
    for (InputSectionBase *s : f->getSections())
1827
344k
      if (s && 
s != &InputSection::discarded335k
)
1828
334k
        inputSections.push_back(s);
1829
2.11k
  for (BinaryFile *f : binaryFiles)
1830
6
    for (InputSectionBase *s : f->getSections())
1831
6
      inputSections.push_back(cast<InputSection>(s));
1832
2.11k
1833
2.11k
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
2.11k
    if (s->type == SHT_LLVM_SYMPART) {
1835
2.11k
      readSymbolPartitionSection<ELFT>(s);
1836
2.11k
      return true;
1837
2.11k
    }
1838
2.11k
1839
2.11k
    // We do not want to emit debug sections if --strip-all
1840
2.11k
    // or -strip-debug are given.
1841
2.11k
    return config->strip != StripPolicy::None &&
1842
2.11k
           (s->name.startswith(".debug") || s->name.startswith(".zdebug"));
1843
2.11k
  });
1844
2.11k
1845
2.11k
  // Now that the number of partitions is fixed, save a pointer to the main
1846
2.11k
  // partition.
1847
2.11k
  mainPart = &partitions[0];
1848
2.11k
1849
2.11k
  // Read .note.gnu.property sections from input object files which
1850
2.11k
  // contain a hint to tweak linker's and loader's behaviors.
1851
2.11k
  config->andFeatures = getAndFeatures<ELFT>();
1852
2.11k
1853
2.11k
  // The Target instance handles target-specific stuff, such as applying
1854
2.11k
  // relocations or writing a PLT section. It also contains target-dependent
1855
2.11k
  // values such as a default image base address.
1856
2.11k
  target = getTarget();
1857
2.11k
1858
2.11k
  config->eflags = target->calcEFlags();
1859
2.11k
  // maxPageSize (sometimes called abi page size) is the maximum page size that
1860
2.11k
  // the output can be run on. For example if the OS can use 4k or 64k page
1861
2.11k
  // sizes then maxPageSize must be 64k for the output to be useable on both.
1862
2.11k
  // All important alignment decisions must use this value.
1863
2.11k
  config->maxPageSize = getMaxPageSize(args);
1864
2.11k
  // commonPageSize is the most common page size that the output will be run on.
1865
2.11k
  // For example if an OS can use 4k or 64k page sizes and 4k is more common
1866
2.11k
  // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1867
2.11k
  // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1868
2.11k
  // is limited to writing trap instructions on the last executable segment.
1869
2.11k
  config->commonPageSize = getCommonPageSize(args);
1870
2.11k
1871
2.11k
  config->imageBase = getImageBase(args);
1872
2.11k
1873
2.11k
  if (config->emachine == EM_ARM) {
1874
0
    // FIXME: These warnings can be removed when lld only uses these features
1875
0
    // when the input objects have been compiled with an architecture that
1876
0
    // supports them.
1877
0
    if (config->armHasBlx == false)
1878
0
      warn("lld uses blx instruction, no object with architecture supporting "
1879
0
           "feature detected");
1880
0
  }
1881
2.11k
1882
2.11k
  // This adds a .comment section containing a version string. We have to add it
1883
2.11k
  // before mergeSections because the .comment section is a mergeable section.
1884
2.11k
  if (!config->relocatable)
1885
2.05k
    inputSections.push_back(createCommentSection());
1886
2.11k
1887
2.11k
  // Replace common symbols with regular symbols.
1888
2.11k
  replaceCommonSymbols();
1889
2.11k
1890
2.11k
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1891
2.11k
  // and identical code folding.
1892
2.11k
  splitSections<ELFT>();
1893
2.11k
  markLive<ELFT>();
1894
2.11k
  demoteSharedSymbols();
1895
2.11k
  mergeSections();
1896
2.11k
  if (config->icf != ICFLevel::None) {
1897
58
    findKeepUniqueSections<ELFT>(args);
1898
58
    doIcf<ELFT>();
1899
58
  }
1900
2.11k
1901
2.11k
  // Read the callgraph now that we know what was gced or icfed
1902
2.11k
  if (config->callGraphProfileSort) {
1903
2.07k
    if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1904
11
      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1905
11
        readCallGraph(*buffer);
1906
2.07k
    readCallGraphsFromObjectFiles<ELFT>();
1907
2.07k
  }
1908
2.11k
1909
2.11k
  // Write the result to the file.
1910
2.11k
  writeResult<ELFT>();
1911
2.11k
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)
Line
Count
Source
1669
112
template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1670
112
  // If a -hash-style option was not given, set to a default value,
1671
112
  // which varies depending on the target.
1672
112
  if (!args.hasArg(OPT_hash_style)) {
1673
110
    if (config->emachine == EM_MIPS)
1674
46
      config->sysvHash = true;
1675
64
    else
1676
64
      config->sysvHash = config->gnuHash = true;
1677
110
  }
1678
112
1679
112
  // Default output filename is "a.out" by the Unix tradition.
1680
112
  if (config->outputFile.empty())
1681
0
    config->outputFile = "a.out";
1682
112
1683
112
  // Fail early if the output file or map file is not writable. If a user has a
1684
112
  // long link, e.g. due to a large LTO link, they do not wish to run it and
1685
112
  // find that it failed because there was a mistake in their command-line.
1686
112
  if (auto e = tryCreateFile(config->outputFile))
1687
0
    error("cannot open output file " + config->outputFile + ": " + e.message());
1688
112
  if (auto e = tryCreateFile(config->mapFile))
1689
0
    error("cannot open map file " + config->mapFile + ": " + e.message());
1690
112
  if (errorCount())
1691
0
    return;
1692
112
1693
112
  // Use default entry point name if no name was given via the command
1694
112
  // line nor linker scripts. For some reason, MIPS entry point name is
1695
112
  // different from others.
1696
112
  config->warnMissingEntry =
1697
112
      (!config->entry.empty() || 
(109
!config->shared109
&&
!config->relocatable65
));
1698
112
  if (config->entry.empty() && 
!config->relocatable109
)
1699
106
    config->entry = (config->emachine == EM_MIPS) ? 
"__start"41
:
"_start"65
;
1700
112
1701
112
  // Handle --trace-symbol.
1702
112
  for (auto *arg : args.filtered(OPT_trace_symbol))
1703
0
    symtab->insert(arg->getValue())->traced = true;
1704
112
1705
112
  // Add all files to the symbol table. This will add almost all
1706
112
  // symbols that we need to the symbol table. This process might
1707
112
  // add files to the link, via autolinking, these files are always
1708
112
  // appended to the Files vector.
1709
269
  for (size_t i = 0; i < files.size(); 
++i157
)
1710
157
    parseFile(files[i]);
1711
112
1712
112
  // Now that we have every file, we can decide if we will need a
1713
112
  // dynamic symbol table.
1714
112
  // We need one if we were asked to export dynamic symbols or if we are
1715
112
  // producing a shared library.
1716
112
  // We also need one if any shared libraries are used and for pie executables
1717
112
  // (probably because the dynamic linker needs it).
1718
112
  config->hasDynSymTab =
1719
112
      !sharedFiles.empty() || 
config->isPic97
||
config->exportDynamic55
;
1720
112
1721
112
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1722
112
  // are undefined symbols for them, so we add these to trigger that logic.
1723
112
  for (StringRef name : script->referencedSymbols)
1724
4
    addUndefined(name);
1725
112
1726
112
  // Handle the `--undefined <sym>` options.
1727
112
  for (StringRef arg : config->undefined)
1728
0
    if (Symbol *sym = symtab->find(arg))
1729
0
      handleUndefined(sym);
1730
112
1731
112
  // If an entry symbol is in a static archive, pull out that file now.
1732
112
  if (Symbol *sym = symtab->find(config->entry))
1733
44
    handleUndefined(sym);
1734
112
1735
112
  // Handle the `--undefined-glob <pattern>` options.
1736
112
  for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1737
0
    handleUndefinedGlob(pat);
1738
112
1739
112
  // If any of our inputs are bitcode files, the LTO code generator may create
1740
112
  // references to certain library functions that might not be explicit in the
1741
112
  // bitcode file's symbol table. If any of those library functions are defined
1742
112
  // in a bitcode file in an archive member, we need to arrange to use LTO to
1743
112
  // compile those archive members by adding them to the link beforehand.
1744
112
  //
1745
112
  // However, adding all libcall symbols to the link can have undesired
1746
112
  // consequences. For example, the libgcc implementation of
1747
112
  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1748
112
  // that aborts the program if the Linux kernel does not support 64-bit
1749
112
  // atomics, which would prevent the program from running even if it does not
1750
112
  // use 64-bit atomics.
1751
112
  //
1752
112
  // Therefore, we only add libcall symbols to the link before LTO if we have
1753
112
  // to, i.e. if the symbol's definition is in bitcode. Any other required
1754
112
  // libcall symbols will be added to the link after LTO when we add the LTO
1755
112
  // object file to the link.
1756
112
  if (!bitcodeFiles.empty())
1757
0
    for (const char *s : libcallRoutineNames)
1758
0
      handleLibcall(s);
1759
112
1760
112
  // Return if there were name resolution errors.
1761
112
  if (errorCount())
1762
4
    return;
1763
108
1764
108
  // Now when we read all script files, we want to finalize order of linker
1765
108
  // script commands, which can be not yet final because of INSERT commands.
1766
108
  script->processInsertCommands();
1767
108
1768
108
  // We want to declare linker script's symbols early,
1769
108
  // so that we can version them.
1770
108
  // They also might be exported if referenced by DSOs.
1771
108
  script->declareSymbols();
1772
108
1773
108
  // Handle the -exclude-libs option.
1774
108
  if (args.hasArg(OPT_exclude_libs))
1775
0
    excludeLibs(args);
1776
108
1777
108
  // Create elfHeader early. We need a dummy section in
1778
108
  // addReservedSymbols to mark the created symbols as not absolute.
1779
108
  Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1780
108
  Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1781
108
1782
108
  // Create wrapped symbols for -wrap option.
1783
108
  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1784
108
1785
108
  // We need to create some reserved symbols such as _end. Create them.
1786
108
  if (!config->relocatable)
1787
105
    addReservedSymbols();
1788
108
1789
108
  // Apply version scripts.
1790
108
  //
1791
108
  // For a relocatable output, version scripts don't make sense, and
1792
108
  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1793
108
  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1794
108
  if (!config->relocatable)
1795
105
    symtab->scanVersionScript();
1796
108
1797
108
  // Do link-time optimization if given files are LLVM bitcode files.
1798
108
  // This compiles bitcode files into real object files.
1799
108
  //
1800
108
  // With this the symbol table should be complete. After this, no new names
1801
108
  // except a few linker-synthesized ones will be added to the symbol table.
1802
108
  compileBitcodeFiles<ELFT>();
1803
108
  if (errorCount())
1804
0
    return;
1805
108
1806
108
  // If -thinlto-index-only is given, we should create only "index
1807
108
  // files" and not object files. Index file creation is already done
1808
108
  // in addCombinedLTOObject, so we are done if that's the case.
1809
108
  if (config->thinLTOIndexOnly)
1810
0
    return;
1811
108
1812
108
  // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1813
108
  // an output file in bitcode and exit, so that you can just get a
1814
108
  // combined bitcode file.
1815
108
  if (config->emitLLVM)
1816
0
    return;
1817
108
1818
108
  // Apply symbol renames for -wrap.
1819
108
  if (!wrapped.empty())
1820
0
    wrapSymbols(wrapped);
1821
108
1822
108
  // Now that we have a complete list of input files.
1823
108
  // Beyond this point, no new files are added.
1824
108
  // Aggregate all input sections into one place.
1825
108
  for (InputFile *f : objectFiles)
1826
137
    for (InputSectionBase *s : f->getSections())
1827
940
      if (s && 
s != &InputSection::discarded409
)
1828
401
        inputSections.push_back(s);
1829
108
  for (BinaryFile *f : binaryFiles)
1830
0
    for (InputSectionBase *s : f->getSections())
1831
0
      inputSections.push_back(cast<InputSection>(s));
1832
108
1833
108
  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1834
108
    if (s->type == SHT_LLVM_SYMPART) {
1835
108
      readSymbolPartitionSection<ELFT>(s);
1836
108
      return true;
1837
108
    }
1838
108
1839
108
    // We do not want to emit debug sections if --strip-all
1840
108
    // or -strip-debug are given.
1841
108
    return config->strip != StripPolicy::None &&
1842
108
           (s->name.startswith(".debug") || s->name.startswith(".zdebug"));
1843
108
  });
1844
108
1845
108
  // Now that the number of partitions is fixed, save a pointer to the main
1846
108
  // partition.
1847
108
  mainPart = &partitions[0];
1848
108
1849
108
  // Read .note.gnu.property sections from input object files which
1850
108
  // contain a hint to tweak linker's and loader's behaviors.
1851
108
  config->andFeatures = getAndFeatures<ELFT>();
1852
108
1853
108
  // The Target instance handles target-specific stuff, such as applying
1854
108
  // relocations or writing a PLT section. It also contains target-dependent
1855
108
  // values such as a default image base address.
1856
108
  target = getTarget();
1857
108
1858
108
  config->eflags = target->calcEFlags();
1859
108
  // maxPageSize (sometimes called abi page size) is the maximum page size that
1860
108
  // the output can be run on. For example if the OS can use 4k or 64k page
1861
108
  // sizes then maxPageSize must be 64k for the output to be useable on both.
1862
108
  // All important alignment decisions must use this value.
1863
108
  config->maxPageSize = getMaxPageSize(args);
1864
108
  // commonPageSize is the most common page size that the output will be run on.
1865
108
  // For example if an OS can use 4k or 64k page sizes and 4k is more common
1866
108
  // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1867
108
  // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1868
108
  // is limited to writing trap instructions on the last executable segment.
1869
108
  config->commonPageSize = getCommonPageSize(args);
1870
108
1871
108
  config->imageBase = getImageBase(args);
1872
108
1873
108
  if (config->emachine == EM_ARM) {
1874
0
    // FIXME: These warnings can be removed when lld only uses these features
1875
0
    // when the input objects have been compiled with an architecture that
1876
0
    // supports them.
1877
0
    if (config->armHasBlx == false)
1878
0
      warn("lld uses blx instruction, no object with architecture supporting "
1879
0
           "feature detected");
1880
0
  }
1881
108
1882
108
  // This adds a .comment section containing a version string. We have to add it
1883
108
  // before mergeSections because the .comment section is a mergeable section.
1884
108
  if (!config->relocatable)
1885
105
    inputSections.push_back(createCommentSection());
1886
108
1887
108
  // Replace common symbols with regular symbols.
1888
108
  replaceCommonSymbols();
1889
108
1890
108
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1891
108
  // and identical code folding.
1892
108
  splitSections<ELFT>();
1893
108
  markLive<ELFT>();
1894
108
  demoteSharedSymbols();
1895
108
  mergeSections();
1896
108
  if (config->icf != ICFLevel::None) {
1897
0
    findKeepUniqueSections<ELFT>(args);
1898
0
    doIcf<ELFT>();
1899
0
  }
1900
108
1901
108
  // Read the callgraph now that we know what was gced or icfed
1902
108
  if (config->callGraphProfileSort) {
1903
108
    if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1904
0
      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1905
0
        readCallGraph(*buffer);
1906
108
    readCallGraphsFromObjectFiles<ELFT>();
1907
108
  }
1908
108
1909
108
  // Write the result to the file.
1910
108
  writeResult<ELFT>();
1911
108
}