Coverage Report

Created: 2017-10-03 07:32

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