Coverage Report

Created: 2018-06-25 02:00

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