Coverage Report

Created: 2018-01-17 17:22

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Driver.cpp ---------------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// The driver drives the entire linking process. It is responsible for
11
// parsing command line options and doing whatever it is instructed to do.
12
//
13
// One notable thing in the LLD's driver when compared to other linkers is
14
// that the LLD's driver is agnostic on the host operating system.
15
// Other linkers usually have implicit default values (such as a dynamic
16
// linker path or library paths) for each host OS.
17
//
18
// I don't think implicit default values are useful because they are
19
// usually explicitly specified by the compiler driver. They can even
20
// be harmful when you are doing cross-linking. Therefore, in LLD, we
21
// simply trust the compiler driver to pass all required options and
22
// don't try to make effort on our side.
23
//
24
//===----------------------------------------------------------------------===//
25
26
#include "Driver.h"
27
#include "Config.h"
28
#include "Filesystem.h"
29
#include "ICF.h"
30
#include "InputFiles.h"
31
#include "InputSection.h"
32
#include "LinkerScript.h"
33
#include "OutputSections.h"
34
#include "ScriptParser.h"
35
#include "Strings.h"
36
#include "SymbolTable.h"
37
#include "Symbols.h"
38
#include "SyntheticSections.h"
39
#include "Target.h"
40
#include "Writer.h"
41
#include "lld/Common/Args.h"
42
#include "lld/Common/Driver.h"
43
#include "lld/Common/ErrorHandler.h"
44
#include "lld/Common/Memory.h"
45
#include "lld/Common/Threads.h"
46
#include "lld/Common/Version.h"
47
#include "llvm/ADT/StringExtras.h"
48
#include "llvm/ADT/StringSwitch.h"
49
#include "llvm/Support/CommandLine.h"
50
#include "llvm/Support/Compression.h"
51
#include "llvm/Support/Path.h"
52
#include "llvm/Support/TarWriter.h"
53
#include "llvm/Support/TargetSelect.h"
54
#include "llvm/Support/raw_ostream.h"
55
#include <cstdlib>
56
#include <utility>
57
58
using namespace llvm;
59
using namespace llvm::ELF;
60
using namespace llvm::object;
61
using namespace llvm::sys;
62
63
using namespace lld;
64
using namespace lld::elf;
65
66
Configuration *elf::Config;
67
LinkerDriver *elf::Driver;
68
69
static void setConfigs();
70
71
bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
72
1.98k
               raw_ostream &Error) {
73
1.98k
  errorHandler().LogName = Args[0];
74
1.98k
  errorHandler().ErrorLimitExceededMsg =
75
1.98k
      "too many errors emitted, stopping now (use "
76
1.98k
      "-error-limit=0 to see all errors)";
77
1.98k
  errorHandler().ErrorOS = &Error;
78
1.98k
  errorHandler().ColorDiagnostics = Error.has_colors();
79
1.98k
  InputSections.clear();
80
1.98k
  OutputSections.clear();
81
1.98k
  Tar = nullptr;
82
1.98k
  BinaryFiles.clear();
83
1.98k
  BitcodeFiles.clear();
84
1.98k
  ObjectFiles.clear();
85
1.98k
  SharedFiles.clear();
86
1.98k
87
1.98k
  Config = make<Configuration>();
88
1.98k
  Driver = make<LinkerDriver>();
89
1.98k
  Script = make<LinkerScript>();
90
1.98k
  Symtab = make<SymbolTable>();
91
1.98k
  Config->Argv = {Args.begin(), Args.end()};
92
1.98k
93
1.98k
  Driver->main(Args, CanExitEarly);
94
1.98k
95
1.98k
  // Exit immediately if we don't need to return to the caller.
96
1.98k
  // This saves time because the overhead of calling destructors
97
1.98k
  // for all globally-allocated objects is not negligible.
98
1.98k
  if (Config->ExitEarly)
99
0
    exitLld(errorCount() ? 1 : 0);
100
1.98k
101
1.98k
  freeArena();
102
1.98k
  return !errorCount();
103
1.98k
}
104
105
// Parses a linker -m option.
106
109
static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
107
109
  uint8_t OSABI = 0;
108
109
  StringRef S = Emul;
109
109
  if (S.endswith("_fbsd")) {
110
4
    S = S.drop_back(5);
111
4
    OSABI = ELFOSABI_FREEBSD;
112
4
  }
113
109
114
109
  std::pair<ELFKind, uint16_t> Ret =
115
109
      StringSwitch<std::pair<ELFKind, uint16_t>>(S)
116
109
          .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
117
109
          .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
118
109
          .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
119
109
          .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
120
109
          .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
121
109
          .Case("elf32ppc", {ELF32BEKind, EM_PPC})
122
109
          .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
123
109
          .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
124
109
          .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
125
109
          .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
126
109
          .Case("elf_i386", {ELF32LEKind, EM_386})
127
109
          .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
128
109
          .Default({ELFNoneKind, EM_NONE});
129
109
130
109
  if (Ret.first == ELFNoneKind)
131
2
    error("unknown emulation: " + Emul);
132
109
  return std::make_tuple(Ret.first, Ret.second, OSABI);
133
109
}
134
135
// Returns slices of MB by parsing MB as an archive file.
136
// Each slice consists of a member file in the archive.
137
std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
138
21
    MemoryBufferRef MB) {
139
21
  std::unique_ptr<Archive> File =
140
21
      CHECK(Archive::create(MB),
141
21
            MB.getBufferIdentifier() + ": failed to parse archive");
142
21
143
21
  std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
144
21
  Error Err = Error::success();
145
21
  bool AddToTar = File->isThin() && 
Tar2
;
146
23
  for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
147
23
    Archive::Child C =
148
23
        CHECK(COrErr, MB.getBufferIdentifier() +
149
23
                          ": could not get the child of the archive");
150
23
    MemoryBufferRef MBRef =
151
23
        CHECK(C.getMemoryBufferRef(),
152
23
              MB.getBufferIdentifier() +
153
23
                  ": could not get the buffer for a child of the archive");
154
23
    if (AddToTar)
155
1
      Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
156
23
    V.push_back(std::make_pair(MBRef, C.getChildOffset()));
157
23
  }
158
21
  if (Err)
159
0
    fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
160
0
          toString(std::move(Err)));
161
21
162
21
  // Take ownership of memory buffers created for members of thin archives.
163
21
  for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
164
2
    make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
165
21
166
21
  return V;
167
21
}
168
169
// Opens a file and create a file object. Path has to be resolved already.
170
2.80k
void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
171
2.80k
  using namespace sys::fs;
172
2.80k
173
2.80k
  Optional<MemoryBufferRef> Buffer = readFile(Path);
174
2.80k
  if (!Buffer.hasValue())
175
88
    return;
176
2.71k
  MemoryBufferRef MBRef = *Buffer;
177
2.71k
178
2.71k
  if (InBinary) {
179
5
    Files.push_back(make<BinaryFile>(MBRef));
180
5
    return;
181
5
  }
182
2.71k
183
2.71k
  switch (identify_magic(MBRef.getBuffer())) {
184
2.71k
  case file_magic::unknown:
185
63
    readLinkerScript(MBRef);
186
63
    return;
187
2.71k
  case file_magic::archive: {
188
96
    // Handle -whole-archive.
189
96
    if (InWholeArchive) {
190
17
      for (const auto &P : getArchiveMembers(MBRef))
191
18
        Files.push_back(createObjectFile(P.first, Path, P.second));
192
17
      return;
193
17
    }
194
79
195
79
    std::unique_ptr<Archive> File =
196
79
        CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
197
79
198
79
    // If an archive file has no symbol table, it is likely that a user
199
79
    // is attempting LTO and using a default ar command that doesn't
200
79
    // understand the LLVM bitcode file. It is a pretty common error, so
201
79
    // we'll handle it as if it had a symbol table.
202
79
    if (!File->isEmpty() && 
!File->hasSymbolTable()77
) {
203
4
      for (const auto &P : getArchiveMembers(MBRef))
204
5
        Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
205
4
      return;
206
4
    }
207
75
208
75
    // Handle the regular case.
209
75
    Files.push_back(make<ArchiveFile>(std::move(File)));
210
75
    return;
211
75
  }
212
281
  case file_magic::elf_shared_object:
213
281
    if (Config->Relocatable) {
214
1
      error("attempted static link of dynamic object " + Path);
215
1
      return;
216
1
    }
217
280
218
280
    // DSOs usually have DT_SONAME tags in their ELF headers, and the
219
280
    // sonames are used to identify DSOs. But if they are missing,
220
280
    // they are identified by filenames. We don't know whether the new
221
280
    // file has a DT_SONAME or not because we haven't parsed it yet.
222
280
    // Here, we set the default soname for the file because we might
223
280
    // need it later.
224
280
    //
225
280
    // If a file was specified by -lfoo, the directory part is not
226
280
    // significant, as a user did not specify it. This behavior is
227
280
    // compatible with GNU.
228
280
    Files.push_back(
229
280
        createSharedFile(MBRef, WithLOption ? 
path::filename(Path)12
:
Path268
));
230
280
    return;
231
2.27k
  default:
232
2.27k
    if (InLib)
233
14
      Files.push_back(make<LazyObjFile>(MBRef, "", 0));
234
2.25k
    else
235
2.25k
      Files.push_back(createObjectFile(MBRef));
236
2.71k
  }
237
2.71k
}
238
239
// Add a given library by searching it from input search paths.
240
33
void LinkerDriver::addLibrary(StringRef Name) {
241
33
  if (Optional<std::string> Path = searchLibrary(Name))
242
25
    addFile(*Path, /*WithLOption=*/true);
243
8
  else
244
8
    error("unable to find library -l" + Name);
245
33
}
246
247
// This function is called on startup. We need this for LTO since
248
// LTO calls LLVM functions to compile bitcode files to native code.
249
// Technically this can be delayed until we read bitcode files, but
250
// we don't bother to do lazily because the initialization is fast.
251
1.98k
static void initLLVM(opt::InputArgList &Args) {
252
1.98k
  InitializeAllTargets();
253
1.98k
  InitializeAllTargetMCs();
254
1.98k
  InitializeAllAsmPrinters();
255
1.98k
  InitializeAllAsmParsers();
256
1.98k
257
1.98k
  // Parse and evaluate -mllvm options.
258
1.98k
  std::vector<const char *> V;
259
1.98k
  V.push_back("lld (LLVM option parsing)");
260
1.98k
  for (auto *Arg : Args.filtered(OPT_mllvm))
261
6
    V.push_back(Arg->getValue());
262
1.98k
  cl::ParseCommandLineOptions(V.size(), V.data());
263
1.98k
}
264
265
// Some command line options or some combinations of them are not allowed.
266
// This function checks for such errors.
267
1.98k
static void checkOptions(opt::InputArgList &Args) {
268
1.98k
  // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
269
1.98k
  // table which is a relatively new feature.
270
1.98k
  if (Config->EMachine == EM_MIPS && 
Config->GnuHash155
)
271
2
    error("the .gnu.hash section is not compatible with the MIPS target.");
272
1.98k
273
1.98k
  if (Config->FixCortexA53Errata843419 && 
Config->EMachine != EM_AARCH646
)
274
1
    error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
275
1.98k
276
1.98k
  if (Config->Pie && 
Config->Shared43
)
277
1
    error("-shared and -pie may not be used together");
278
1.98k
279
1.98k
  if (!Config->Shared && 
!Config->FilterList.empty()1.27k
)
280
1
    error("-F may not be used without -shared");
281
1.98k
282
1.98k
  if (!Config->Shared && 
!Config->AuxiliaryList.empty()1.27k
)
283
1
    error("-f may not be used without -shared");
284
1.98k
285
1.98k
  if (!Config->Relocatable && 
!Config->DefineCommon1.91k
)
286
1
    error("-no-define-common not supported in non relocatable output");
287
1.98k
288
1.98k
  if (Config->Relocatable) {
289
67
    if (Config->Shared)
290
1
      error("-r and -shared may not be used together");
291
67
    if (Config->GcSections)
292
1
      error("-r and --gc-sections may not be used together");
293
67
    if (Config->ICF)
294
1
      error("-r and --icf may not be used together");
295
67
    if (Config->Pie)
296
1
      error("-r and -pie may not be used together");
297
67
  }
298
1.98k
}
299
300
1.98k
static const char *getReproduceOption(opt::InputArgList &Args) {
301
1.98k
  if (auto *Arg = Args.getLastArg(OPT_reproduce))
302
9
    return Arg->getValue();
303
1.97k
  return getenv("LLD_REPRODUCE");
304
1.97k
}
305
306
23.7k
static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
307
23.7k
  for (auto *Arg : Args.filtered(OPT_z))
308
581
    if (Key == Arg->getValue())
309
29
      return true;
310
23.7k
  
return false23.7k
;
311
23.7k
}
312
313
1.98k
void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
314
1.98k
  ELFOptTable Parser;
315
1.98k
  opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
316
1.98k
317
1.98k
  // Interpret this flag early because error() depends on them.
318
1.98k
  errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
319
1.98k
320
1.98k
  // Handle -help
321
1.98k
  if (Args.hasArg(OPT_help)) {
322
2
    printHelp(ArgsArr[0]);
323
2
    return;
324
2
  }
325
1.98k
326
1.98k
  // Handle -v or -version.
327
1.98k
  //
328
1.98k
  // A note about "compatible with GNU linkers" message: this is a hack for
329
1.98k
  // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
330
1.98k
  // still the newest version in March 2017) or earlier to recognize LLD as
331
1.98k
  // a GNU compatible linker. As long as an output for the -v option
332
1.98k
  // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
333
1.98k
  //
334
1.98k
  // This is somewhat ugly hack, but in reality, we had no choice other
335
1.98k
  // than doing this. Considering the very long release cycle of Libtool,
336
1.98k
  // it is not easy to improve it to recognize LLD as a GNU compatible
337
1.98k
  // linker in a timely manner. Even if we can make it, there are still a
338
1.98k
  // lot of "configure" scripts out there that are generated by old version
339
1.98k
  // of Libtool. We cannot convince every software developer to migrate to
340
1.98k
  // the latest version and re-generate scripts. So we have this hack.
341
1.98k
  if (Args.hasArg(OPT_v) || 
Args.hasArg(OPT_version)1.98k
)
342
6
    message(getLLDVersion() + " (compatible with GNU linkers)");
343
1.98k
344
1.98k
  // The behavior of -v or --version is a bit strange, but this is
345
1.98k
  // needed for compatibility with GNU linkers.
346
1.98k
  if (Args.hasArg(OPT_v) && 
!Args.hasArg(OPT_INPUT)3
)
347
1
    return;
348
1.98k
  if (Args.hasArg(OPT_version))
349
3
    return;
350
1.98k
351
1.98k
  Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
352
1.98k
  errorHandler().ExitEarly = Config->ExitEarly;
353
1.98k
354
1.98k
  if (const char *Path = getReproduceOption(Args)) {
355
10
    // Note that --reproduce is a debug option so you can ignore it
356
10
    // if you are trying to understand the whole picture of the code.
357
10
    Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
358
10
        TarWriter::create(Path, path::stem(Path));
359
10
    if (ErrOrWriter) {
360
10
      Tar = ErrOrWriter->get();
361
10
      Tar->append("response.txt", createResponseFile(Args));
362
10
      Tar->append("version.txt", getLLDVersion() + "\n");
363
10
      make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
364
10
    } else {
365
0
      error(Twine("--reproduce: failed to open ") + Path + ": " +
366
0
            toString(ErrOrWriter.takeError()));
367
0
    }
368
10
  }
369
1.98k
370
1.98k
  readConfigs(Args);
371
1.98k
  initLLVM(Args);
372
1.98k
  createFiles(Args);
373
1.98k
  inferMachineType();
374
1.98k
  setConfigs();
375
1.98k
  checkOptions(Args);
376
1.98k
  if (errorCount())
377
124
    return;
378
1.85k
379
1.85k
  switch (Config->EKind) {
380
1.85k
  case ELF32LEKind:
381
238
    link<ELF32LE>(Args);
382
238
    return;
383
1.85k
  case ELF32BEKind:
384
105
    link<ELF32BE>(Args);
385
105
    return;
386
1.85k
  case ELF64LEKind:
387
1.45k
    link<ELF64LE>(Args);
388
1.45k
    return;
389
1.85k
  case ELF64BEKind:
390
55
    link<ELF64BE>(Args);
391
55
    return;
392
1.85k
  default:
393
0
    llvm_unreachable("unknown Config->EKind");
394
0
  }
395
0
}
396
397
1.98k
static std::string getRpath(opt::InputArgList &Args) {
398
1.98k
  std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
399
1.98k
  return llvm::join(V.begin(), V.end(), ":");
400
1.98k
}
401
402
// Determines what we should do if there are remaining unresolved
403
// symbols after the name resolution.
404
1.98k
static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
405
1.98k
  if (Args.hasArg(OPT_relocatable))
406
67
    return UnresolvedPolicy::IgnoreAll;
407
1.91k
408
1.91k
  UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
409
1.91k
                                              OPT_warn_unresolved_symbols, true)
410
1.91k
                                     ? 
UnresolvedPolicy::ReportError1.91k
411
1.91k
                                     : 
UnresolvedPolicy::Warn4
;
412
1.91k
413
1.91k
  // Process the last of -unresolved-symbols, -no-undefined or -z defs.
414
8.81k
  for (auto *Arg : llvm::reverse(Args)) {
415
8.81k
    switch (Arg->getOption().getID()) {
416
8.81k
    case OPT_unresolved_symbols: {
417
14
      StringRef S = Arg->getValue();
418
14
      if (S == "ignore-all" || 
S == "ignore-in-object-files"9
)
419
7
        return UnresolvedPolicy::Ignore;
420
7
      if (S == "ignore-in-shared-libs" || 
S == "report-all"4
)
421
5
        return ErrorOrWarn;
422
2
      error("unknown --unresolved-symbols value: " + S);
423
2
      continue;
424
2
    }
425
2
    case OPT_no_undefined:
426
2
      return ErrorOrWarn;
427
49
    case OPT_z:
428
49
      if (StringRef(Arg->getValue()) == "defs")
429
3
        return ErrorOrWarn;
430
46
      continue;
431
8.81k
    }
432
8.81k
  }
433
1.91k
434
1.91k
  // -shared implies -unresolved-symbols=ignore-all because missing
435
1.91k
  // symbols are likely to be resolved at runtime using other DSOs.
436
1.91k
  
if (1.89k
Config->Shared1.89k
)
437
701
    return UnresolvedPolicy::Ignore;
438
1.19k
  return ErrorOrWarn;
439
1.19k
}
440
441
1.98k
static Target2Policy getTarget2(opt::InputArgList &Args) {
442
1.98k
  StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
443
1.98k
  if (S == "rel")
444
1
    return Target2Policy::Rel;
445
1.98k
  if (S == "abs")
446
1
    return Target2Policy::Abs;
447
1.97k
  if (S == "got-rel")
448
1.97k
    return Target2Policy::GotRel;
449
0
  error("unknown --target2 option: " + S);
450
0
  return Target2Policy::GotRel;
451
0
}
452
453
1.98k
static bool isOutputFormatBinary(opt::InputArgList &Args) {
454
1.98k
  if (auto *Arg = Args.getLastArg(OPT_oformat)) {
455
6
    StringRef S = Arg->getValue();
456
6
    if (S == "binary")
457
5
      return true;
458
1
    error("unknown --oformat value: " + S);
459
1
  }
460
1.98k
  
return false1.97k
;
461
1.98k
}
462
463
1.98k
static DiscardPolicy getDiscard(opt::InputArgList &Args) {
464
1.98k
  if (Args.hasArg(OPT_relocatable))
465
67
    return DiscardPolicy::None;
466
1.91k
467
1.91k
  auto *Arg =
468
1.91k
      Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
469
1.91k
  if (!Arg)
470
1.90k
    return DiscardPolicy::Default;
471
6
  if (Arg->getOption().getID() == OPT_discard_all)
472
3
    return DiscardPolicy::All;
473
3
  if (Arg->getOption().getID() == OPT_discard_locals)
474
1
    return DiscardPolicy::Locals;
475
2
  return DiscardPolicy::None;
476
2
}
477
478
1.98k
static StringRef getDynamicLinker(opt::InputArgList &Args) {
479
1.98k
  auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
480
1.98k
  if (!Arg || 
Arg->getOption().getID() == OPT_no_dynamic_linker7
)
481
1.97k
    return "";
482
6
  return Arg->getValue();
483
6
}
484
485
1.98k
static StripPolicy getStrip(opt::InputArgList &Args) {
486
1.98k
  if (Args.hasArg(OPT_relocatable))
487
67
    return StripPolicy::None;
488
1.91k
489
1.91k
  auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
490
1.91k
  if (!Arg)
491
1.90k
    return StripPolicy::None;
492
6
  if (Arg->getOption().getID() == OPT_strip_all)
493
3
    return StripPolicy::All;
494
3
  return StripPolicy::Debug;
495
3
}
496
497
49
static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
498
49
  uint64_t VA = 0;
499
49
  if (S.startswith("0x"))
500
38
    S = S.drop_front(2);
501
49
  if (!to_integer(S, VA, 16))
502
5
    error("invalid argument: " + toString(Arg));
503
49
  return VA;
504
49
}
505
506
1.98k
static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
507
1.98k
  StringMap<uint64_t> Ret;
508
1.98k
  for (auto *Arg : Args.filtered(OPT_section_start)) {
509
14
    StringRef Name;
510
14
    StringRef Addr;
511
14
    std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
512
14
    Ret[Name] = parseSectionAddress(Addr, *Arg);
513
14
  }
514
1.98k
515
1.98k
  if (auto *Arg = Args.getLastArg(OPT_Ttext))
516
19
    Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
517
1.98k
  if (auto *Arg = Args.getLastArg(OPT_Tdata))
518
8
    Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
519
1.98k
  if (auto *Arg = Args.getLastArg(OPT_Tbss))
520
8
    Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
521
1.98k
  return Ret;
522
1.98k
}
523
524
1.98k
static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
525
1.98k
  StringRef S = Args.getLastArgValue(OPT_sort_section);
526
1.98k
  if (S == "alignment")
527
3
    return SortSectionPolicy::Alignment;
528
1.97k
  if (S == "name")
529
3
    return SortSectionPolicy::Name;
530
1.97k
  if (!S.empty())
531
0
    error("unknown --sort-section rule: " + S);
532
1.97k
  return SortSectionPolicy::Default;
533
1.97k
}
534
535
1.98k
static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
536
1.98k
  StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
537
1.98k
  if (S == "warn")
538
1
    return OrphanHandlingPolicy::Warn;
539
1.98k
  if (S == "error")
540
1
    return OrphanHandlingPolicy::Error;
541
1.97k
  if (S != "place")
542
1
    error("unknown --orphan-handling mode: " + S);
543
1.97k
  return OrphanHandlingPolicy::Place;
544
1.97k
}
545
546
// Parse --build-id or --build-id=<style>. We handle "tree" as a
547
// synonym for "sha1" because all our hash functions including
548
// -build-id=sha1 are actually tree hashes for performance reasons.
549
static std::pair<BuildIdKind, std::vector<uint8_t>>
550
1.98k
getBuildId(opt::InputArgList &Args) {
551
1.98k
  auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
552
1.98k
  if (!Arg)
553
1.96k
    return {BuildIdKind::None, {}};
554
15
555
15
  if (Arg->getOption().getID() == OPT_build_id)
556
5
    return {BuildIdKind::Fast, {}};
557
10
558
10
  StringRef S = Arg->getValue();
559
10
  if (S == "md5")
560
2
    return {BuildIdKind::Md5, {}};
561
8
  if (S == "sha1" || 
S == "tree"6
)
562
4
    return {BuildIdKind::Sha1, {}};
563
4
  if (S == "uuid")
564
1
    return {BuildIdKind::Uuid, {}};
565
3
  if (S.startswith("0x"))
566
1
    return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
567
2
568
2
  if (S != "none")
569
0
    error("unknown --build-id style: " + S);
570
2
  return {BuildIdKind::None, {}};
571
2
}
572
573
1.98k
static bool getCompressDebugSections(opt::InputArgList &Args) {
574
1.98k
  StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
575
1.98k
  if (S == "none")
576
1.97k
    return false;
577
7
  if (S != "zlib")
578
1
    error("unknown --compress-debug-sections value: " + S);
579
7
  if (!zlib::isAvailable())
580
0
    error("--compress-debug-sections: zlib is not available");
581
7
  return true;
582
7
}
583
584
7
static int parseInt(StringRef S, opt::Arg *Arg) {
585
7
  int V = 0;
586
7
  if (!to_integer(S, V, 10))
587
1
    error(Arg->getSpelling() + "=" + Arg->getValue() +
588
1
          ": number expected, but got '" + S + "'");
589
7
  return V;
590
7
}
591
592
// Initializes Config members by the command line options.
593
1.98k
void LinkerDriver::readConfigs(opt::InputArgList &Args) {
594
1.98k
  Config->AllowMultipleDefinition =
595
1.98k
      Args.hasArg(OPT_allow_multiple_definition) || 
hasZOption(Args, "muldefs")1.97k
;
596
1.98k
  Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
597
1.98k
  Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
598
1.98k
  Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
599
1.98k
  Config->Chroot = Args.getLastArgValue(OPT_chroot);
600
1.98k
  Config->CompressDebugSections = getCompressDebugSections(Args);
601
1.98k
  Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
602
1.98k
                                      !Args.hasArg(OPT_relocatable));
603
1.98k
  Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
604
1.98k
  Config->DisableVerify = Args.hasArg(OPT_disable_verify);
605
1.98k
  Config->Discard = getDiscard(Args);
606
1.98k
  Config->DynamicLinker = getDynamicLinker(Args);
607
1.98k
  Config->EhFrameHdr =
608
1.98k
      Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
609
1.98k
  Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
610
1.98k
  Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
611
1.98k
  Config->Entry = Args.getLastArgValue(OPT_entry);
612
1.98k
  Config->ExportDynamic =
613
1.98k
      Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
614
1.98k
  errorHandler().FatalWarnings =
615
1.98k
      Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
616
1.98k
  Config->FilterList = args::getStrings(Args, OPT_filter);
617
1.98k
  Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
618
1.98k
  Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
619
1.98k
  Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
620
1.98k
  Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
621
1.98k
  Config->ICF = Args.hasFlag(OPT_icf_all, OPT_icf_none, false);
622
1.98k
  Config->IgnoreDataAddressEquality =
623
1.98k
      Args.hasArg(OPT_ignore_data_address_equality);
624
1.98k
  Config->IgnoreFunctionAddressEquality =
625
1.98k
      Args.hasArg(OPT_ignore_function_address_equality);
626
1.98k
  Config->Init = Args.getLastArgValue(OPT_init, "_init");
627
1.98k
  Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
628
1.98k
  Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
629
1.98k
  Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
630
1.98k
  Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
631
1.98k
  Config->MapFile = Args.getLastArgValue(OPT_Map);
632
1.98k
  Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
633
1.98k
  Config->MergeArmExidx =
634
1.98k
      Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
635
1.98k
  Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
636
1.98k
  Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
637
1.98k
  Config->Nostdlib = Args.hasArg(OPT_nostdlib);
638
1.98k
  Config->OFormatBinary = isOutputFormatBinary(Args);
639
1.98k
  Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
640
1.98k
  Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
641
1.98k
  Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
642
1.98k
  Config->Optimize = args::getInteger(Args, OPT_O, 1);
643
1.98k
  Config->OrphanHandling = getOrphanHandling(Args);
644
1.98k
  Config->OutputFile = Args.getLastArgValue(OPT_o);
645
1.98k
  Config->Pie = Args.hasFlag(OPT_pie, OPT_nopie, false);
646
1.98k
  Config->PrintGcSections =
647
1.98k
      Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
648
1.98k
  Config->Rpath = getRpath(Args);
649
1.98k
  Config->Relocatable = Args.hasArg(OPT_relocatable);
650
1.98k
  Config->SaveTemps = Args.hasArg(OPT_save_temps);
651
1.98k
  Config->SearchPaths = args::getStrings(Args, OPT_library_path);
652
1.98k
  Config->SectionStartMap = getSectionStartMap(Args);
653
1.98k
  Config->Shared = Args.hasArg(OPT_shared);
654
1.98k
  Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
655
1.98k
  Config->SoName = Args.getLastArgValue(OPT_soname);
656
1.98k
  Config->SortSection = getSortSection(Args);
657
1.98k
  Config->Strip = getStrip(Args);
658
1.98k
  Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
659
1.98k
  Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
660
1.98k
  Config->Target2 = getTarget2(Args);
661
1.98k
  Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
662
1.98k
  Config->ThinLTOCachePolicy = CHECK(
663
1.98k
      parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
664
1.98k
      "--thinlto-cache-policy: invalid cache policy");
665
1.98k
  Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
666
1.98k
  ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
667
1.98k
  Config->Trace = Args.hasArg(OPT_trace);
668
1.98k
  Config->Undefined = args::getStrings(Args, OPT_undefined);
669
1.98k
  Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
670
1.98k
  Config->Verbose = Args.hasArg(OPT_verbose);
671
1.98k
  errorHandler().Verbose = Config->Verbose;
672
1.98k
  Config->WarnCommon = Args.hasArg(OPT_warn_common);
673
1.98k
  Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
674
1.98k
  Config->ZExecstack = hasZOption(Args, "execstack");
675
1.98k
  Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
676
1.98k
  Config->ZNodelete = hasZOption(Args, "nodelete");
677
1.98k
  Config->ZNodlopen = hasZOption(Args, "nodlopen");
678
1.98k
  Config->ZNow = hasZOption(Args, "now");
679
1.98k
  Config->ZOrigin = hasZOption(Args, "origin");
680
1.98k
  Config->ZRelro = !hasZOption(Args, "norelro");
681
1.98k
  Config->ZRodynamic = hasZOption(Args, "rodynamic");
682
1.98k
  Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
683
1.98k
  Config->ZText = !hasZOption(Args, "notext");
684
1.98k
  Config->ZWxneeded = hasZOption(Args, "wxneeded");
685
1.98k
686
1.98k
  // Parse LTO plugin-related options for compatibility with gold.
687
1.98k
  for (auto *Arg : Args.filtered(OPT_plugin_opt)) {
688
16
    StringRef S = Arg->getValue();
689
16
    if (S == "disable-verify")
690
1
      Config->DisableVerify = true;
691
15
    else if (S == "save-temps")
692
1
      Config->SaveTemps = true;
693
14
    else if (S.startswith("O"))
694
5
      Config->LTOO = parseInt(S.substr(1), Arg);
695
9
    else if (S.startswith("lto-partitions="))
696
1
      Config->LTOPartitions = parseInt(S.substr(15), Arg);
697
8
    else if (S.startswith("jobs="))
698
1
      Config->ThinLTOJobs = parseInt(S.substr(5), Arg);
699
7
    else if (!S.startswith("/") && 
!S.startswith("-fresolution=")6
&&
700
7
             
!S.startswith("-pass-through=")5
&&
!S.startswith("mcpu=")4
&&
701
7
             
!S.startswith("thinlto")4
&&
S != "-function-sections"4
&&
702
7
             
S != "-data-sections"3
)
703
2
      error(Arg->getSpelling() + ": unknown option: " + S);
704
16
  }
705
1.98k
706
1.98k
  if (Config->LTOO > 3)
707
4
    error("invalid optimization level for LTO: " + Twine(Config->LTOO));
708
1.98k
  if (Config->LTOPartitions == 0)
709
2
    error("--lto-partitions: number of threads must be > 0");
710
1.98k
  if (Config->ThinLTOJobs == 0)
711
2
    error("--thinlto-jobs: number of threads must be > 0");
712
1.98k
713
1.98k
  // Parse ELF{32,64}{LE,BE} and CPU type.
714
1.98k
  if (auto *Arg = Args.getLastArg(OPT_m)) {
715
109
    StringRef S = Arg->getValue();
716
109
    std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
717
109
        parseEmulation(S);
718
109
    Config->MipsN32Abi = (S == "elf32btsmipn32" || 
S == "elf32ltsmipn32"108
);
719
109
    Config->Emulation = S;
720
109
  }
721
1.98k
722
1.98k
  // Parse -hash-style={sysv,gnu,both}.
723
1.98k
  if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
724
142
    StringRef S = Arg->getValue();
725
142
    if (S == "sysv")
726
131
      Config->SysvHash = true;
727
11
    else if (S == "gnu")
728
10
      Config->GnuHash = true;
729
1
    else if (S == "both")
730
1
      Config->SysvHash = Config->GnuHash = true;
731
0
    else
732
0
      error("unknown -hash-style: " + S);
733
142
  }
734
1.98k
735
1.98k
  if (Args.hasArg(OPT_print_map))
736
4
    Config->MapFile = "-";
737
1.98k
738
1.98k
  // --omagic is an option to create old-fashioned executables in which
739
1.98k
  // .text segments are writable. Today, the option is still in use to
740
1.98k
  // create special-purpose programs such as boot loaders. It doesn't
741
1.98k
  // make sense to create PT_GNU_RELRO for such executables.
742
1.98k
  if (Config->Omagic)
743
4
    Config->ZRelro = false;
744
1.98k
745
1.98k
  std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
746
1.98k
747
1.98k
  if (auto *Arg = Args.getLastArg(OPT_pack_dyn_relocs_eq)) {
748
4
    StringRef S = Arg->getValue();
749
4
    if (S == "android")
750
2
      Config->AndroidPackDynRelocs = true;
751
2
    else if (S != "none")
752
0
      error("unknown -pack-dyn-relocs format: " + S);
753
4
  }
754
1.98k
755
1.98k
  if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
756
6
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
757
6
      Config->SymbolOrderingFile = args::getLines(*Buffer);
758
1.98k
759
1.98k
  // If --retain-symbol-file is used, we'll keep only the symbols listed in
760
1.98k
  // the file and discard all others.
761
1.98k
  if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
762
3
    Config->DefaultSymbolVersion = VER_NDX_LOCAL;
763
3
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
764
3
      for (StringRef S : args::getLines(*Buffer))
765
4
        Config->VersionScriptGlobals.push_back(
766
4
            {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
767
3
  }
768
1.98k
769
1.98k
  bool HasExportDynamic =
770
1.98k
      Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
771
1.98k
772
1.98k
  // Parses -dynamic-list and -export-dynamic-symbol. They make some
773
1.98k
  // symbols private. Note that -export-dynamic takes precedence over them
774
1.98k
  // as it says all symbols should be exported.
775
1.98k
  if (!HasExportDynamic) {
776
1.95k
    for (auto *Arg : Args.filtered(OPT_dynamic_list))
777
20
      if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
778
20
        readDynamicList(*Buffer);
779
1.95k
780
1.95k
    for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
781
4
      Config->DynamicList.push_back(
782
4
          {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
783
1.95k
  }
784
1.98k
785
1.98k
  for (auto *Arg : Args.filtered(OPT_version_script))
786
71
    if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
787
71
      readVersionScript(*Buffer);
788
1.98k
}
789
790
// Some Config members do not directly correspond to any particular
791
// command line options, but computed based on other Config values.
792
// This function initialize such members. See Config.h for the details
793
// of these values.
794
1.98k
static void setConfigs() {
795
1.98k
  ELFKind Kind = Config->EKind;
796
1.98k
  uint16_t Machine = Config->EMachine;
797
1.98k
798
1.98k
  // There is an ILP32 ABI for x86-64, although it's not very popular.
799
1.98k
  // It is called the x32 ABI.
800
1.98k
  bool IsX32 = (Kind == ELF32LEKind && 
Machine == EM_X86_64239
);
801
1.98k
802
1.98k
  Config->CopyRelocs = (Config->Relocatable || 
Config->EmitRelocs1.91k
);
803
1.98k
  Config->Is64 = (Kind == ELF64LEKind || 
Kind == ELF64BEKind437
);
804
1.98k
  Config->IsLE = (Kind == ELF32LEKind || 
Kind == ELF64LEKind1.74k
);
805
1.98k
  Config->Endianness =
806
1.98k
      Config->IsLE ? 
support::endianness::little1.78k
:
support::endianness::big198
;
807
1.98k
  Config->IsMips64EL = (Kind == ELF64LEKind && 
Machine == EM_MIPS1.54k
);
808
1.98k
  Config->IsRela = Config->Is64 || 
IsX32382
||
Config->MipsN32Abi379
;
809
1.98k
  Config->Pic = Config->Pie || 
Config->Shared1.93k
;
810
1.98k
  Config->Wordsize = Config->Is64 ? 
81.59k
:
4382
;
811
1.98k
}
812
813
// Returns a value of "-format" option.
814
7
static bool getBinaryOption(StringRef S) {
815
7
  if (S == "binary")
816
5
    return true;
817
2
  if (S == "elf" || S == "default")
818
1
    return false;
819
1
  error("unknown -format value: " + S +
820
1
        " (supported formats: elf, default, binary)");
821
1
  return false;
822
1
}
823
824
1.98k
void LinkerDriver::createFiles(opt::InputArgList &Args) {
825
9.18k
  for (auto *Arg : Args) {
826
9.18k
    switch (Arg->getOption().getUnaliasedOption().getID()) {
827
9.18k
    case OPT_library:
828
31
      addLibrary(Arg->getValue());
829
31
      break;
830
9.18k
    case OPT_INPUT:
831
2.74k
      addFile(Arg->getValue(), /*WithLOption=*/false);
832
2.74k
      break;
833
9.18k
    case OPT_defsym: {
834
11
      StringRef From;
835
11
      StringRef To;
836
11
      std::tie(From, To) = StringRef(Arg->getValue()).split('=');
837
11
      readDefsym(From, MemoryBufferRef(To, "-defsym"));
838
11
      break;
839
9.18k
    }
840
9.18k
    case OPT_script:
841
402
      if (Optional<std::string> Path = searchLinkerScript(Arg->getValue())) {
842
401
        if (Optional<MemoryBufferRef> MB = readFile(*Path))
843
401
          readLinkerScript(*MB);
844
401
        break;
845
401
      }
846
1
      error(Twine("cannot find linker script ") + Arg->getValue());
847
1
      break;
848
10
    case OPT_as_needed:
849
10
      Config->AsNeeded = true;
850
10
      break;
851
7
    case OPT_format:
852
7
      InBinary = getBinaryOption(Arg->getValue());
853
7
      break;
854
1
    case OPT_no_as_needed:
855
1
      Config->AsNeeded = false;
856
1
      break;
857
26
    case OPT_Bstatic:
858
26
      Config->Static = true;
859
26
      break;
860
6
    case OPT_Bdynamic:
861
6
      Config->Static = false;
862
6
      break;
863
15
    case OPT_whole_archive:
864
15
      InWholeArchive = true;
865
15
      break;
866
3
    case OPT_no_whole_archive:
867
3
      InWholeArchive = false;
868
3
      break;
869
8
    case OPT_start_lib:
870
8
      InLib = true;
871
8
      break;
872
3
    case OPT_end_lib:
873
3
      InLib = false;
874
3
      break;
875
9.18k
    }
876
9.18k
  }
877
1.98k
878
1.98k
  if (Files.empty() && 
errorCount() == 036
)
879
1
    error("no input files");
880
1.98k
}
881
882
// If -m <machine_type> was not given, infer it from object files.
883
1.98k
void LinkerDriver::inferMachineType() {
884
1.98k
  if (Config->EKind != ELFNoneKind)
885
107
    return;
886
1.87k
887
1.87k
  for (InputFile *F : Files) {
888
1.84k
    if (F->EKind == ELFNoneKind)
889
9
      continue;
890
1.83k
    Config->EKind = F->EKind;
891
1.83k
    Config->EMachine = F->EMachine;
892
1.83k
    Config->OSABI = F->OSABI;
893
1.83k
    Config->MipsN32Abi = Config->EMachine == EM_MIPS && 
isMipsN32Abi(F)149
;
894
1.83k
    return;
895
1.83k
  }
896
1.87k
  error("target emulation unknown: -m or at least one .o file required");
897
37
}
898
899
// Parse -z max-page-size=<value>. The default value is defined by
900
// each target.
901
1.85k
static uint64_t getMaxPageSize(opt::InputArgList &Args) {
902
1.85k
  uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
903
1.85k
                                       Target->DefaultMaxPageSize);
904
1.85k
  if (!isPowerOf2_64(Val))
905
1
    error("max-page-size: value isn't a power of 2");
906
1.85k
  return Val;
907
1.85k
}
908
909
// Parses -image-base option.
910
1.85k
static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
911
1.85k
  // Because we are using "Config->MaxPageSize" here, this function has to be
912
1.85k
  // called after the variable is initialized.
913
1.85k
  auto *Arg = Args.getLastArg(OPT_image_base);
914
1.85k
  if (!Arg)
915
1.85k
    return None;
916
6
917
6
  StringRef S = Arg->getValue();
918
6
  uint64_t V;
919
6
  if (!to_integer(S, V)) {
920
0
    error("-image-base: number expected, but got " + S);
921
0
    return 0;
922
0
  }
923
6
  if ((V % Config->MaxPageSize) != 0)
924
2
    warn("-image-base: address isn't multiple of page size: " + S);
925
6
  return V;
926
6
}
927
928
// Parses `--exclude-libs=lib,lib,...`.
929
// The library names may be delimited by commas or colons.
930
6
static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
931
6
  DenseSet<StringRef> Ret;
932
6
  for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
933
6
    StringRef S = Arg->getValue();
934
13
    for (;;) {
935
13
      size_t Pos = S.find_first_of(",:");
936
13
      if (Pos == StringRef::npos)
937
6
        break;
938
7
      Ret.insert(S.substr(0, Pos));
939
7
      S = S.substr(Pos + 1);
940
7
    }
941
6
    Ret.insert(S);
942
6
  }
943
6
  return Ret;
944
6
}
945
946
12
static Optional<StringRef> getArchiveName(InputFile *File) {
947
12
  if (isa<ArchiveFile>(File))
948
4
    return File->getName();
949
8
  if (!File->ArchiveName.empty())
950
2
    return File->ArchiveName;
951
6
  return None;
952
6
}
953
954
// Handles the -exclude-libs option. If a static library file is specified
955
// by the -exclude-libs option, all public symbols from the archive become
956
// private unless otherwise specified by version scripts or something.
957
// A special library name "ALL" means all archive files.
958
//
959
// This is not a popular option, but some programs such as bionic libc use it.
960
template <class ELFT>
961
6
static void excludeLibs(opt::InputArgList &Args, ArrayRef<InputFile *> Files) {
962
6
  DenseSet<StringRef> Libs = getExcludeLibs(Args);
963
6
  bool All = Libs.count("ALL");
964
6
965
6
  for (InputFile *File : Files)
966
12
    if (Optional<StringRef> Archive = getArchiveName(File))
967
6
      if (All || 
Libs.count(path::filename(*Archive))4
)
968
5
        for (Symbol *Sym : File->getSymbols())
969
7
          if (!Sym->isLocal())
970
5
            Sym->VersionId = VER_NDX_LOCAL;
971
6
}
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&, llvm::ArrayRef<lld::elf::InputFile*>)
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&, llvm::ArrayRef<lld::elf::InputFile*>)
Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&, llvm::ArrayRef<lld::elf::InputFile*>)
Line
Count
Source
961
6
static void excludeLibs(opt::InputArgList &Args, ArrayRef<InputFile *> Files) {
962
6
  DenseSet<StringRef> Libs = getExcludeLibs(Args);
963
6
  bool All = Libs.count("ALL");
964
6
965
6
  for (InputFile *File : Files)
966
12
    if (Optional<StringRef> Archive = getArchiveName(File))
967
6
      if (All || 
Libs.count(path::filename(*Archive))4
)
968
5
        for (Symbol *Sym : File->getSymbols())
969
7
          if (!Sym->isLocal())
970
5
            Sym->VersionId = VER_NDX_LOCAL;
971
6
}
Unexecuted instantiation: Driver.cpp:void excludeLibs<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&, llvm::ArrayRef<lld::elf::InputFile*>)
972
973
// Do actual linking. Note that when this function is called,
974
// all linker scripts have already been parsed.
975
1.85k
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
976
1.85k
  Target = getTarget();
977
1.85k
978
1.85k
  Config->MaxPageSize = getMaxPageSize(Args);
979
1.85k
  Config->ImageBase = getImageBase(Args);
980
1.85k
981
1.85k
  // If a -hash-style option was not given, set to a default value,
982
1.85k
  // which varies depending on the target.
983
1.85k
  if (!Args.hasArg(OPT_hash_style)) {
984
1.71k
    if (Config->EMachine == EM_MIPS)
985
153
      Config->SysvHash = true;
986
1.56k
    else
987
1.56k
      Config->SysvHash = Config->GnuHash = true;
988
1.71k
  }
989
1.85k
990
1.85k
  // Default output filename is "a.out" by the Unix tradition.
991
1.85k
  if (Config->OutputFile.empty())
992
15
    Config->OutputFile = "a.out";
993
1.85k
994
1.85k
  // Fail early if the output file or map file is not writable. If a user has a
995
1.85k
  // long link, e.g. due to a large LTO link, they do not wish to run it and
996
1.85k
  // find that it failed because there was a mistake in their command-line.
997
1.85k
  if (auto E = tryCreateFile(Config->OutputFile))
998
8
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
999
1.85k
  if (auto E = tryCreateFile(Config->MapFile))
1000
3
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1001
1.85k
  if (errorCount())
1002
14
    return;
1003
1.84k
1004
1.84k
  // Use default entry point name if no name was given via the command
1005
1.84k
  // line nor linker scripts. For some reason, MIPS entry point name is
1006
1.84k
  // different from others.
1007
1.84k
  Config->WarnMissingEntry =
1008
1.84k
      (!Config->Entry.empty() || 
(1.80k
!Config->Shared1.80k
&&
!Config->Relocatable1.12k
));
1009
1.84k
  if (Config->Entry.empty() && 
!Config->Relocatable1.80k
)
1010
1.74k
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"135
:
"_start"1.61k
;
1011
1.84k
1012
1.84k
  // Handle --trace-symbol.
1013
1.84k
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1014
33
    Symtab->trace(Arg->getValue());
1015
1.84k
1016
1.84k
  // Add all files to the symbol table. This will add almost all
1017
1.84k
  // symbols that we need to the symbol table.
1018
1.84k
  for (InputFile *F : Files)
1019
2.54k
    Symtab->addFile<ELFT>(F);
1020
1.84k
1021
1.84k
  // Now that we have every file, we can decide if we will need a
1022
1.84k
  // dynamic symbol table.
1023
1.84k
  // We need one if we were asked to export dynamic symbols or if we are
1024
1.84k
  // producing a shared library.
1025
1.84k
  // We also need one if any shared libraries are used and for pie executables
1026
1.84k
  // (probably because the dynamic linker needs it).
1027
1.84k
  Config->HasDynSymTab =
1028
1.84k
      !SharedFiles.empty() || 
Config->Pic1.59k
||
Config->ExportDynamic913
;
1029
1.84k
1030
1.84k
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1031
1.84k
  // are undefined symbols for them, so we add these to trigger that logic.
1032
1.84k
  for (StringRef Sym : Script->ReferencedSymbols)
1033
64
    Symtab->addUndefined<ELFT>(Sym);
1034
1.84k
1035
1.84k
  // Handle the `--undefined <sym>` options.
1036
1.84k
  for (StringRef S : Config->Undefined)
1037
19
    Symtab->fetchIfLazy<ELFT>(S);
1038
1.84k
1039
1.84k
  // If an entry symbol is in a static archive, pull out that file now
1040
1.84k
  // to complete the symbol table. After this, no new names except a
1041
1.84k
  // few linker-synthesized ones will be added to the symbol table.
1042
1.84k
  Symtab->fetchIfLazy<ELFT>(Config->Entry);
1043
1.84k
1044
1.84k
  // Return if there were name resolution errors.
1045
1.84k
  if (errorCount())
1046
36
    return;
1047
1.80k
1048
1.80k
  // Handle undefined symbols in DSOs.
1049
1.80k
  if (!Config->Shared)
1050
1.12k
    Symtab->scanShlibUndefined<ELFT>();
1051
1.80k
1052
1.80k
  // Handle the -exclude-libs option.
1053
1.80k
  if (Args.hasArg(OPT_exclude_libs))
1054
6
    excludeLibs<ELFT>(Args, Files);
1055
1.80k
1056
1.80k
  // Create ElfHeader early. We need a dummy section in
1057
1.80k
  // addReservedSymbols to mark the created symbols as not absolute.
1058
1.80k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1059
1.80k
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1060
1.80k
1061
1.80k
  // We need to create some reserved symbols such as _end. Create them.
1062
1.80k
  if (!Config->Relocatable)
1063
1.74k
    addReservedSymbols();
1064
1.80k
1065
1.80k
  // Apply version scripts.
1066
1.80k
  Symtab->scanVersionScript();
1067
1.80k
1068
1.80k
  // Create wrapped symbols for -wrap option.
1069
1.80k
  for (auto *Arg : Args.filtered(OPT_wrap))
1070
11
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1071
1.80k
1072
1.80k
  Symtab->addCombinedLTOObject<ELFT>();
1073
1.80k
  if (errorCount())
1074
6
    return;
1075
1.80k
1076
1.80k
  // Apply symbol renames for -wrap.
1077
1.80k
  Symtab->applySymbolWrap();
1078
1.80k
1079
1.80k
  // Now that we have a complete list of input files.
1080
1.80k
  // Beyond this point, no new files are added.
1081
1.80k
  // Aggregate all input sections into one place.
1082
1.80k
  for (InputFile *F : ObjectFiles)
1083
2.15k
    for (InputSectionBase *S : F->getSections())
1084
209k
      if (S && 
S != &InputSection::Discarded201k
)
1085
201k
        InputSections.push_back(S);
1086
1.80k
  for (BinaryFile *F : BinaryFiles)
1087
3
    for (InputSectionBase *S : F->getSections())
1088
3
      InputSections.push_back(cast<InputSection>(S));
1089
1.80k
1090
1.80k
  // We do not want to emit debug sections if --strip-all
1091
1.80k
  // or -strip-debug are given.
1092
1.80k
  if (Config->Strip != StripPolicy::None)
1093
11
    
llvm::erase_if(InputSections, [](InputSectionBase *S) 5
{
1094
11
      return S->Name.startswith(".debug") || 
S->Name.startswith(".zdebug")8
;
1095
11
    });
Unexecuted instantiation: void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Unexecuted instantiation: void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
1093
11
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1094
11
      return S->Name.startswith(".debug") || 
S->Name.startswith(".zdebug")8
;
1095
11
    });
Unexecuted instantiation: void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
1096
1.80k
1097
1.80k
  Config->EFlags = Target->calcEFlags();
1098
1.80k
1099
1.80k
  if (Config->EMachine == EM_ARM) {
1100
111
    // FIXME: These warnings can be removed when lld only uses these features
1101
111
    // when the input objects have been compiled with an architecture that
1102
111
    // supports them.
1103
111
    if (Config->ARMHasBlx == false)
1104
106
      warn("lld uses blx instruction, no object with architecture supporting "
1105
106
           "feature detected.");
1106
111
    if (Config->ARMJ1J2BranchEncoding == false)
1107
107
      warn("lld uses extended branch encoding, no object with architecture "
1108
107
           "supporting feature detected.");
1109
111
    if (Config->ARMHasMovtMovw == false)
1110
107
      warn("lld may use movt/movw, no object with architecture supporting "
1111
107
           "feature detected.");
1112
111
  }
1113
1.80k
1114
1.80k
  // This adds a .comment section containing a version string. We have to add it
1115
1.80k
  // before decompressAndMergeSections because the .comment section is a
1116
1.80k
  // mergeable section.
1117
1.80k
  if (!Config->Relocatable)
1118
1.73k
    InputSections.push_back(createCommentSection());
1119
1.80k
1120
1.80k
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1121
1.80k
  // and identical code folding.
1122
1.80k
  markLive<ELFT>();
1123
1.80k
  decompressSections();
1124
1.80k
  mergeSections();
1125
1.80k
  if (Config->ICF)
1126
22
    doIcf<ELFT>();
1127
1.80k
1128
1.80k
  // Write the result to the file.
1129
1.80k
  writeResult<ELFT>();
1130
1.80k
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::opt::InputArgList&)
Line
Count
Source
975
238
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
976
238
  Target = getTarget();
977
238
978
238
  Config->MaxPageSize = getMaxPageSize(Args);
979
238
  Config->ImageBase = getImageBase(Args);
980
238
981
238
  // If a -hash-style option was not given, set to a default value,
982
238
  // which varies depending on the target.
983
238
  if (!Args.hasArg(OPT_hash_style)) {
984
201
    if (Config->EMachine == EM_MIPS)
985
15
      Config->SysvHash = true;
986
186
    else
987
186
      Config->SysvHash = Config->GnuHash = true;
988
201
  }
989
238
990
238
  // Default output filename is "a.out" by the Unix tradition.
991
238
  if (Config->OutputFile.empty())
992
2
    Config->OutputFile = "a.out";
993
238
994
238
  // Fail early if the output file or map file is not writable. If a user has a
995
238
  // long link, e.g. due to a large LTO link, they do not wish to run it and
996
238
  // find that it failed because there was a mistake in their command-line.
997
238
  if (auto E = tryCreateFile(Config->OutputFile))
998
0
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
999
238
  if (auto E = tryCreateFile(Config->MapFile))
1000
0
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1001
238
  if (errorCount())
1002
0
    return;
1003
238
1004
238
  // Use default entry point name if no name was given via the command
1005
238
  // line nor linker scripts. For some reason, MIPS entry point name is
1006
238
  // different from others.
1007
238
  Config->WarnMissingEntry =
1008
238
      (!Config->Entry.empty() || 
(234
!Config->Shared234
&&
!Config->Relocatable144
));
1009
238
  if (Config->Entry.empty() && 
!Config->Relocatable234
)
1010
228
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"12
:
"_start"216
;
1011
238
1012
238
  // Handle --trace-symbol.
1013
238
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1014
0
    Symtab->trace(Arg->getValue());
1015
238
1016
238
  // Add all files to the symbol table. This will add almost all
1017
238
  // symbols that we need to the symbol table.
1018
238
  for (InputFile *F : Files)
1019
325
    Symtab->addFile<ELFT>(F);
1020
238
1021
238
  // Now that we have every file, we can decide if we will need a
1022
238
  // dynamic symbol table.
1023
238
  // We need one if we were asked to export dynamic symbols or if we are
1024
238
  // producing a shared library.
1025
238
  // We also need one if any shared libraries are used and for pie executables
1026
238
  // (probably because the dynamic linker needs it).
1027
238
  Config->HasDynSymTab =
1028
238
      !SharedFiles.empty() || 
Config->Pic202
||
Config->ExportDynamic110
;
1029
238
1030
238
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1031
238
  // are undefined symbols for them, so we add these to trigger that logic.
1032
238
  for (StringRef Sym : Script->ReferencedSymbols)
1033
0
    Symtab->addUndefined<ELFT>(Sym);
1034
238
1035
238
  // Handle the `--undefined <sym>` options.
1036
238
  for (StringRef S : Config->Undefined)
1037
0
    Symtab->fetchIfLazy<ELFT>(S);
1038
238
1039
238
  // If an entry symbol is in a static archive, pull out that file now
1040
238
  // to complete the symbol table. After this, no new names except a
1041
238
  // few linker-synthesized ones will be added to the symbol table.
1042
238
  Symtab->fetchIfLazy<ELFT>(Config->Entry);
1043
238
1044
238
  // Return if there were name resolution errors.
1045
238
  if (errorCount())
1046
8
    return;
1047
230
1048
230
  // Handle undefined symbols in DSOs.
1049
230
  if (!Config->Shared)
1050
140
    Symtab->scanShlibUndefined<ELFT>();
1051
230
1052
230
  // Handle the -exclude-libs option.
1053
230
  if (Args.hasArg(OPT_exclude_libs))
1054
0
    excludeLibs<ELFT>(Args, Files);
1055
230
1056
230
  // Create ElfHeader early. We need a dummy section in
1057
230
  // addReservedSymbols to mark the created symbols as not absolute.
1058
230
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1059
230
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1060
230
1061
230
  // We need to create some reserved symbols such as _end. Create them.
1062
230
  if (!Config->Relocatable)
1063
224
    addReservedSymbols();
1064
230
1065
230
  // Apply version scripts.
1066
230
  Symtab->scanVersionScript();
1067
230
1068
230
  // Create wrapped symbols for -wrap option.
1069
230
  for (auto *Arg : Args.filtered(OPT_wrap))
1070
0
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1071
230
1072
230
  Symtab->addCombinedLTOObject<ELFT>();
1073
230
  if (errorCount())
1074
0
    return;
1075
230
1076
230
  // Apply symbol renames for -wrap.
1077
230
  Symtab->applySymbolWrap();
1078
230
1079
230
  // Now that we have a complete list of input files.
1080
230
  // Beyond this point, no new files are added.
1081
230
  // Aggregate all input sections into one place.
1082
230
  for (InputFile *F : ObjectFiles)
1083
262
    for (InputSectionBase *S : F->getSections())
1084
2.03k
      if (S && 
S != &InputSection::Discarded958
)
1085
953
        InputSections.push_back(S);
1086
230
  for (BinaryFile *F : BinaryFiles)
1087
0
    for (InputSectionBase *S : F->getSections())
1088
0
      InputSections.push_back(cast<InputSection>(S));
1089
230
1090
230
  // We do not want to emit debug sections if --strip-all
1091
230
  // or -strip-debug are given.
1092
230
  if (Config->Strip != StripPolicy::None)
1093
0
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1094
0
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1095
0
    });
1096
230
1097
230
  Config->EFlags = Target->calcEFlags();
1098
230
1099
230
  if (Config->EMachine == EM_ARM) {
1100
111
    // FIXME: These warnings can be removed when lld only uses these features
1101
111
    // when the input objects have been compiled with an architecture that
1102
111
    // supports them.
1103
111
    if (Config->ARMHasBlx == false)
1104
106
      warn("lld uses blx instruction, no object with architecture supporting "
1105
106
           "feature detected.");
1106
111
    if (Config->ARMJ1J2BranchEncoding == false)
1107
107
      warn("lld uses extended branch encoding, no object with architecture "
1108
107
           "supporting feature detected.");
1109
111
    if (Config->ARMHasMovtMovw == false)
1110
107
      warn("lld may use movt/movw, no object with architecture supporting "
1111
107
           "feature detected.");
1112
111
  }
1113
230
1114
230
  // This adds a .comment section containing a version string. We have to add it
1115
230
  // before decompressAndMergeSections because the .comment section is a
1116
230
  // mergeable section.
1117
230
  if (!Config->Relocatable)
1118
224
    InputSections.push_back(createCommentSection());
1119
230
1120
230
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1121
230
  // and identical code folding.
1122
230
  markLive<ELFT>();
1123
230
  decompressSections();
1124
230
  mergeSections();
1125
230
  if (Config->ICF)
1126
2
    doIcf<ELFT>();
1127
230
1128
230
  // Write the result to the file.
1129
230
  writeResult<ELFT>();
1130
230
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::opt::InputArgList&)
Line
Count
Source
975
105
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
976
105
  Target = getTarget();
977
105
978
105
  Config->MaxPageSize = getMaxPageSize(Args);
979
105
  Config->ImageBase = getImageBase(Args);
980
105
981
105
  // If a -hash-style option was not given, set to a default value,
982
105
  // which varies depending on the target.
983
105
  if (!Args.hasArg(OPT_hash_style)) {
984
104
    if (Config->EMachine == EM_MIPS)
985
103
      Config->SysvHash = true;
986
1
    else
987
1
      Config->SysvHash = Config->GnuHash = true;
988
104
  }
989
105
990
105
  // Default output filename is "a.out" by the Unix tradition.
991
105
  if (Config->OutputFile.empty())
992
0
    Config->OutputFile = "a.out";
993
105
994
105
  // Fail early if the output file or map file is not writable. If a user has a
995
105
  // long link, e.g. due to a large LTO link, they do not wish to run it and
996
105
  // find that it failed because there was a mistake in their command-line.
997
105
  if (auto E = tryCreateFile(Config->OutputFile))
998
0
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
999
105
  if (auto E = tryCreateFile(Config->MapFile))
1000
0
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1001
105
  if (errorCount())
1002
0
    return;
1003
105
1004
105
  // Use default entry point name if no name was given via the command
1005
105
  // line nor linker scripts. For some reason, MIPS entry point name is
1006
105
  // different from others.
1007
105
  Config->WarnMissingEntry =
1008
105
      (!Config->Entry.empty() || 
(103
!Config->Shared103
&&
!Config->Relocatable59
));
1009
105
  if (Config->Entry.empty() && 
!Config->Relocatable103
)
1010
95
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"93
:
"_start"2
;
1011
105
1012
105
  // Handle --trace-symbol.
1013
105
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1014
0
    Symtab->trace(Arg->getValue());
1015
105
1016
105
  // Add all files to the symbol table. This will add almost all
1017
105
  // symbols that we need to the symbol table.
1018
105
  for (InputFile *F : Files)
1019
159
    Symtab->addFile<ELFT>(F);
1020
105
1021
105
  // Now that we have every file, we can decide if we will need a
1022
105
  // dynamic symbol table.
1023
105
  // We need one if we were asked to export dynamic symbols or if we are
1024
105
  // producing a shared library.
1025
105
  // We also need one if any shared libraries are used and for pie executables
1026
105
  // (probably because the dynamic linker needs it).
1027
105
  Config->HasDynSymTab =
1028
105
      !SharedFiles.empty() || 
Config->Pic86
||
Config->ExportDynamic46
;
1029
105
1030
105
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1031
105
  // are undefined symbols for them, so we add these to trigger that logic.
1032
105
  for (StringRef Sym : Script->ReferencedSymbols)
1033
0
    Symtab->addUndefined<ELFT>(Sym);
1034
105
1035
105
  // Handle the `--undefined <sym>` options.
1036
105
  for (StringRef S : Config->Undefined)
1037
0
    Symtab->fetchIfLazy<ELFT>(S);
1038
105
1039
105
  // If an entry symbol is in a static archive, pull out that file now
1040
105
  // to complete the symbol table. After this, no new names except a
1041
105
  // few linker-synthesized ones will be added to the symbol table.
1042
105
  Symtab->fetchIfLazy<ELFT>(Config->Entry);
1043
105
1044
105
  // Return if there were name resolution errors.
1045
105
  if (errorCount())
1046
2
    return;
1047
103
1048
103
  // Handle undefined symbols in DSOs.
1049
103
  if (!Config->Shared)
1050
59
    Symtab->scanShlibUndefined<ELFT>();
1051
103
1052
103
  // Handle the -exclude-libs option.
1053
103
  if (Args.hasArg(OPT_exclude_libs))
1054
0
    excludeLibs<ELFT>(Args, Files);
1055
103
1056
103
  // Create ElfHeader early. We need a dummy section in
1057
103
  // addReservedSymbols to mark the created symbols as not absolute.
1058
103
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1059
103
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1060
103
1061
103
  // We need to create some reserved symbols such as _end. Create them.
1062
103
  if (!Config->Relocatable)
1063
95
    addReservedSymbols();
1064
103
1065
103
  // Apply version scripts.
1066
103
  Symtab->scanVersionScript();
1067
103
1068
103
  // Create wrapped symbols for -wrap option.
1069
103
  for (auto *Arg : Args.filtered(OPT_wrap))
1070
0
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1071
103
1072
103
  Symtab->addCombinedLTOObject<ELFT>();
1073
103
  if (errorCount())
1074
0
    return;
1075
103
1076
103
  // Apply symbol renames for -wrap.
1077
103
  Symtab->applySymbolWrap();
1078
103
1079
103
  // Now that we have a complete list of input files.
1080
103
  // Beyond this point, no new files are added.
1081
103
  // Aggregate all input sections into one place.
1082
103
  for (InputFile *F : ObjectFiles)
1083
137
    for (InputSectionBase *S : F->getSections())
1084
1.24k
      if (S && 
S != &InputSection::Discarded740
)
1085
740
        InputSections.push_back(S);
1086
103
  for (BinaryFile *F : BinaryFiles)
1087
0
    for (InputSectionBase *S : F->getSections())
1088
0
      InputSections.push_back(cast<InputSection>(S));
1089
103
1090
103
  // We do not want to emit debug sections if --strip-all
1091
103
  // or -strip-debug are given.
1092
103
  if (Config->Strip != StripPolicy::None)
1093
0
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1094
0
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1095
0
    });
1096
103
1097
103
  Config->EFlags = Target->calcEFlags();
1098
103
1099
103
  if (Config->EMachine == EM_ARM) {
1100
0
    // FIXME: These warnings can be removed when lld only uses these features
1101
0
    // when the input objects have been compiled with an architecture that
1102
0
    // supports them.
1103
0
    if (Config->ARMHasBlx == false)
1104
0
      warn("lld uses blx instruction, no object with architecture supporting "
1105
0
           "feature detected.");
1106
0
    if (Config->ARMJ1J2BranchEncoding == false)
1107
0
      warn("lld uses extended branch encoding, no object with architecture "
1108
0
           "supporting feature detected.");
1109
0
    if (Config->ARMHasMovtMovw == false)
1110
0
      warn("lld may use movt/movw, no object with architecture supporting "
1111
0
           "feature detected.");
1112
0
  }
1113
103
1114
103
  // This adds a .comment section containing a version string. We have to add it
1115
103
  // before decompressAndMergeSections because the .comment section is a
1116
103
  // mergeable section.
1117
103
  if (!Config->Relocatable)
1118
95
    InputSections.push_back(createCommentSection());
1119
103
1120
103
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1121
103
  // and identical code folding.
1122
103
  markLive<ELFT>();
1123
103
  decompressSections();
1124
103
  mergeSections();
1125
103
  if (Config->ICF)
1126
0
    doIcf<ELFT>();
1127
103
1128
103
  // Write the result to the file.
1129
103
  writeResult<ELFT>();
1130
103
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::opt::InputArgList&)
Line
Count
Source
975
1.45k
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
976
1.45k
  Target = getTarget();
977
1.45k
978
1.45k
  Config->MaxPageSize = getMaxPageSize(Args);
979
1.45k
  Config->ImageBase = getImageBase(Args);
980
1.45k
981
1.45k
  // If a -hash-style option was not given, set to a default value,
982
1.45k
  // which varies depending on the target.
983
1.45k
  if (!Args.hasArg(OPT_hash_style)) {
984
1.35k
    if (Config->EMachine == EM_MIPS)
985
2
      Config->SysvHash = true;
986
1.35k
    else
987
1.35k
      Config->SysvHash = Config->GnuHash = true;
988
1.35k
  }
989
1.45k
990
1.45k
  // Default output filename is "a.out" by the Unix tradition.
991
1.45k
  if (Config->OutputFile.empty())
992
13
    Config->OutputFile = "a.out";
993
1.45k
994
1.45k
  // Fail early if the output file or map file is not writable. If a user has a
995
1.45k
  // long link, e.g. due to a large LTO link, they do not wish to run it and
996
1.45k
  // find that it failed because there was a mistake in their command-line.
997
1.45k
  if (auto E = tryCreateFile(Config->OutputFile))
998
8
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
999
1.45k
  if (auto E = tryCreateFile(Config->MapFile))
1000
3
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1001
1.45k
  if (errorCount())
1002
14
    return;
1003
1.44k
1004
1.44k
  // Use default entry point name if no name was given via the command
1005
1.44k
  // line nor linker scripts. For some reason, MIPS entry point name is
1006
1.44k
  // different from others.
1007
1.44k
  Config->WarnMissingEntry =
1008
1.44k
      (!Config->Entry.empty() || 
(1.41k
!Config->Shared1.41k
&&
!Config->Relocatable892
));
1009
1.44k
  if (Config->Entry.empty() && 
!Config->Relocatable1.41k
)
1010
1.37k
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"0
: "_start";
1011
1.44k
1012
1.44k
  // Handle --trace-symbol.
1013
1.44k
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1014
33
    Symtab->trace(Arg->getValue());
1015
1.44k
1016
1.44k
  // Add all files to the symbol table. This will add almost all
1017
1.44k
  // symbols that we need to the symbol table.
1018
1.44k
  for (InputFile *F : Files)
1019
1.98k
    Symtab->addFile<ELFT>(F);
1020
1.44k
1021
1.44k
  // Now that we have every file, we can decide if we will need a
1022
1.44k
  // dynamic symbol table.
1023
1.44k
  // We need one if we were asked to export dynamic symbols or if we are
1024
1.44k
  // producing a shared library.
1025
1.44k
  // We also need one if any shared libraries are used and for pie executables
1026
1.44k
  // (probably because the dynamic linker needs it).
1027
1.44k
  Config->HasDynSymTab =
1028
1.44k
      !SharedFiles.empty() || 
Config->Pic1.25k
||
Config->ExportDynamic734
;
1029
1.44k
1030
1.44k
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1031
1.44k
  // are undefined symbols for them, so we add these to trigger that logic.
1032
1.44k
  for (StringRef Sym : Script->ReferencedSymbols)
1033
60
    Symtab->addUndefined<ELFT>(Sym);
1034
1.44k
1035
1.44k
  // Handle the `--undefined <sym>` options.
1036
1.44k
  for (StringRef S : Config->Undefined)
1037
19
    Symtab->fetchIfLazy<ELFT>(S);
1038
1.44k
1039
1.44k
  // If an entry symbol is in a static archive, pull out that file now
1040
1.44k
  // to complete the symbol table. After this, no new names except a
1041
1.44k
  // few linker-synthesized ones will be added to the symbol table.
1042
1.44k
  Symtab->fetchIfLazy<ELFT>(Config->Entry);
1043
1.44k
1044
1.44k
  // Return if there were name resolution errors.
1045
1.44k
  if (errorCount())
1046
22
    return;
1047
1.42k
1048
1.42k
  // Handle undefined symbols in DSOs.
1049
1.42k
  if (!Config->Shared)
1050
896
    Symtab->scanShlibUndefined<ELFT>();
1051
1.42k
1052
1.42k
  // Handle the -exclude-libs option.
1053
1.42k
  if (Args.hasArg(OPT_exclude_libs))
1054
6
    excludeLibs<ELFT>(Args, Files);
1055
1.42k
1056
1.42k
  // Create ElfHeader early. We need a dummy section in
1057
1.42k
  // addReservedSymbols to mark the created symbols as not absolute.
1058
1.42k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1059
1.42k
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1060
1.42k
1061
1.42k
  // We need to create some reserved symbols such as _end. Create them.
1062
1.42k
  if (!Config->Relocatable)
1063
1.37k
    addReservedSymbols();
1064
1.42k
1065
1.42k
  // Apply version scripts.
1066
1.42k
  Symtab->scanVersionScript();
1067
1.42k
1068
1.42k
  // Create wrapped symbols for -wrap option.
1069
1.42k
  for (auto *Arg : Args.filtered(OPT_wrap))
1070
11
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1071
1.42k
1072
1.42k
  Symtab->addCombinedLTOObject<ELFT>();
1073
1.42k
  if (errorCount())
1074
6
    return;
1075
1.41k
1076
1.41k
  // Apply symbol renames for -wrap.
1077
1.41k
  Symtab->applySymbolWrap();
1078
1.41k
1079
1.41k
  // Now that we have a complete list of input files.
1080
1.41k
  // Beyond this point, no new files are added.
1081
1.41k
  // Aggregate all input sections into one place.
1082
1.41k
  for (InputFile *F : ObjectFiles)
1083
1.69k
    for (InputSectionBase *S : F->getSections())
1084
205k
      if (S && 
S != &InputSection::Discarded199k
)
1085
199k
        InputSections.push_back(S);
1086
1.41k
  for (BinaryFile *F : BinaryFiles)
1087
3
    for (InputSectionBase *S : F->getSections())
1088
3
      InputSections.push_back(cast<InputSection>(S));
1089
1.41k
1090
1.41k
  // We do not want to emit debug sections if --strip-all
1091
1.41k
  // or -strip-debug are given.
1092
1.41k
  if (Config->Strip != StripPolicy::None)
1093
5
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1094
5
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1095
5
    });
1096
1.41k
1097
1.41k
  Config->EFlags = Target->calcEFlags();
1098
1.41k
1099
1.41k
  if (Config->EMachine == EM_ARM) {
1100
0
    // FIXME: These warnings can be removed when lld only uses these features
1101
0
    // when the input objects have been compiled with an architecture that
1102
0
    // supports them.
1103
0
    if (Config->ARMHasBlx == false)
1104
0
      warn("lld uses blx instruction, no object with architecture supporting "
1105
0
           "feature detected.");
1106
0
    if (Config->ARMJ1J2BranchEncoding == false)
1107
0
      warn("lld uses extended branch encoding, no object with architecture "
1108
0
           "supporting feature detected.");
1109
0
    if (Config->ARMHasMovtMovw == false)
1110
0
      warn("lld may use movt/movw, no object with architecture supporting "
1111
0
           "feature detected.");
1112
0
  }
1113
1.41k
1114
1.41k
  // This adds a .comment section containing a version string. We have to add it
1115
1.41k
  // before decompressAndMergeSections because the .comment section is a
1116
1.41k
  // mergeable section.
1117
1.41k
  if (!Config->Relocatable)
1118
1.36k
    InputSections.push_back(createCommentSection());
1119
1.41k
1120
1.41k
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1121
1.41k
  // and identical code folding.
1122
1.41k
  markLive<ELFT>();
1123
1.41k
  decompressSections();
1124
1.41k
  mergeSections();
1125
1.41k
  if (Config->ICF)
1126
20
    doIcf<ELFT>();
1127
1.41k
1128
1.41k
  // Write the result to the file.
1129
1.41k
  writeResult<ELFT>();
1130
1.41k
}
void lld::elf::LinkerDriver::link<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::opt::InputArgList&)
Line
Count
Source
975
55
template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
976
55
  Target = getTarget();
977
55
978
55
  Config->MaxPageSize = getMaxPageSize(Args);
979
55
  Config->ImageBase = getImageBase(Args);
980
55
981
55
  // If a -hash-style option was not given, set to a default value,
982
55
  // which varies depending on the target.
983
55
  if (!Args.hasArg(OPT_hash_style)) {
984
54
    if (Config->EMachine == EM_MIPS)
985
33
      Config->SysvHash = true;
986
21
    else
987
21
      Config->SysvHash = Config->GnuHash = true;
988
54
  }
989
55
990
55
  // Default output filename is "a.out" by the Unix tradition.
991
55
  if (Config->OutputFile.empty())
992
0
    Config->OutputFile = "a.out";
993
55
994
55
  // Fail early if the output file or map file is not writable. If a user has a
995
55
  // long link, e.g. due to a large LTO link, they do not wish to run it and
996
55
  // find that it failed because there was a mistake in their command-line.
997
55
  if (auto E = tryCreateFile(Config->OutputFile))
998
0
    error("cannot open output file " + Config->OutputFile + ": " + E.message());
999
55
  if (auto E = tryCreateFile(Config->MapFile))
1000
0
    error("cannot open map file " + Config->MapFile + ": " + E.message());
1001
55
  if (errorCount())
1002
0
    return;
1003
55
1004
55
  // Use default entry point name if no name was given via the command
1005
55
  // line nor linker scripts. For some reason, MIPS entry point name is
1006
55
  // different from others.
1007
55
  Config->WarnMissingEntry =
1008
55
      (!Config->Entry.empty() || 
(53
!Config->Shared53
&&
!Config->Relocatable31
));
1009
55
  if (Config->Entry.empty() && 
!Config->Relocatable53
)
1010
52
    Config->Entry = (Config->EMachine == EM_MIPS) ? 
"__start"30
:
"_start"22
;
1011
55
1012
55
  // Handle --trace-symbol.
1013
55
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
1014
0
    Symtab->trace(Arg->getValue());
1015
55
1016
55
  // Add all files to the symbol table. This will add almost all
1017
55
  // symbols that we need to the symbol table.
1018
55
  for (InputFile *F : Files)
1019
74
    Symtab->addFile<ELFT>(F);
1020
55
1021
55
  // Now that we have every file, we can decide if we will need a
1022
55
  // dynamic symbol table.
1023
55
  // We need one if we were asked to export dynamic symbols or if we are
1024
55
  // producing a shared library.
1025
55
  // We also need one if any shared libraries are used and for pie executables
1026
55
  // (probably because the dynamic linker needs it).
1027
55
  Config->HasDynSymTab =
1028
55
      !SharedFiles.empty() || 
Config->Pic44
||
Config->ExportDynamic23
;
1029
55
1030
55
  // Some symbols (such as __ehdr_start) are defined lazily only when there
1031
55
  // are undefined symbols for them, so we add these to trigger that logic.
1032
55
  for (StringRef Sym : Script->ReferencedSymbols)
1033
4
    Symtab->addUndefined<ELFT>(Sym);
1034
55
1035
55
  // Handle the `--undefined <sym>` options.
1036
55
  for (StringRef S : Config->Undefined)
1037
0
    Symtab->fetchIfLazy<ELFT>(S);
1038
55
1039
55
  // If an entry symbol is in a static archive, pull out that file now
1040
55
  // to complete the symbol table. After this, no new names except a
1041
55
  // few linker-synthesized ones will be added to the symbol table.
1042
55
  Symtab->fetchIfLazy<ELFT>(Config->Entry);
1043
55
1044
55
  // Return if there were name resolution errors.
1045
55
  if (errorCount())
1046
4
    return;
1047
51
1048
51
  // Handle undefined symbols in DSOs.
1049
51
  if (!Config->Shared)
1050
29
    Symtab->scanShlibUndefined<ELFT>();
1051
51
1052
51
  // Handle the -exclude-libs option.
1053
51
  if (Args.hasArg(OPT_exclude_libs))
1054
0
    excludeLibs<ELFT>(Args, Files);
1055
51
1056
51
  // Create ElfHeader early. We need a dummy section in
1057
51
  // addReservedSymbols to mark the created symbols as not absolute.
1058
51
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1059
51
  Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1060
51
1061
51
  // We need to create some reserved symbols such as _end. Create them.
1062
51
  if (!Config->Relocatable)
1063
50
    addReservedSymbols();
1064
51
1065
51
  // Apply version scripts.
1066
51
  Symtab->scanVersionScript();
1067
51
1068
51
  // Create wrapped symbols for -wrap option.
1069
51
  for (auto *Arg : Args.filtered(OPT_wrap))
1070
0
    Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1071
51
1072
51
  Symtab->addCombinedLTOObject<ELFT>();
1073
51
  if (errorCount())
1074
0
    return;
1075
51
1076
51
  // Apply symbol renames for -wrap.
1077
51
  Symtab->applySymbolWrap();
1078
51
1079
51
  // Now that we have a complete list of input files.
1080
51
  // Beyond this point, no new files are added.
1081
51
  // Aggregate all input sections into one place.
1082
51
  for (InputFile *F : ObjectFiles)
1083
58
    for (InputSectionBase *S : F->getSections())
1084
489
      if (S && 
S != &InputSection::Discarded261
)
1085
261
        InputSections.push_back(S);
1086
51
  for (BinaryFile *F : BinaryFiles)
1087
0
    for (InputSectionBase *S : F->getSections())
1088
0
      InputSections.push_back(cast<InputSection>(S));
1089
51
1090
51
  // We do not want to emit debug sections if --strip-all
1091
51
  // or -strip-debug are given.
1092
51
  if (Config->Strip != StripPolicy::None)
1093
0
    llvm::erase_if(InputSections, [](InputSectionBase *S) {
1094
0
      return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1095
0
    });
1096
51
1097
51
  Config->EFlags = Target->calcEFlags();
1098
51
1099
51
  if (Config->EMachine == EM_ARM) {
1100
0
    // FIXME: These warnings can be removed when lld only uses these features
1101
0
    // when the input objects have been compiled with an architecture that
1102
0
    // supports them.
1103
0
    if (Config->ARMHasBlx == false)
1104
0
      warn("lld uses blx instruction, no object with architecture supporting "
1105
0
           "feature detected.");
1106
0
    if (Config->ARMJ1J2BranchEncoding == false)
1107
0
      warn("lld uses extended branch encoding, no object with architecture "
1108
0
           "supporting feature detected.");
1109
0
    if (Config->ARMHasMovtMovw == false)
1110
0
      warn("lld may use movt/movw, no object with architecture supporting "
1111
0
           "feature detected.");
1112
0
  }
1113
51
1114
51
  // This adds a .comment section containing a version string. We have to add it
1115
51
  // before decompressAndMergeSections because the .comment section is a
1116
51
  // mergeable section.
1117
51
  if (!Config->Relocatable)
1118
50
    InputSections.push_back(createCommentSection());
1119
51
1120
51
  // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1121
51
  // and identical code folding.
1122
51
  markLive<ELFT>();
1123
51
  decompressSections();
1124
51
  mergeSections();
1125
51
  if (Config->ICF)
1126
0
    doIcf<ELFT>();
1127
51
1128
51
  // Write the result to the file.
1129
51
  writeResult<ELFT>();
1130
51
}