Coverage Report

Created: 2019-05-22 02:55

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