Coverage Report

Created: 2017-09-21 03:39

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