1292934Sdim//===- Driver.cpp ---------------------------------------------------------===//
2292934Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6292934Sdim//
7292934Sdim//===----------------------------------------------------------------------===//
8321369Sdim//
9321369Sdim// The driver drives the entire linking process. It is responsible for
10321369Sdim// parsing command line options and doing whatever it is instructed to do.
11321369Sdim//
12321369Sdim// One notable thing in the LLD's driver when compared to other linkers is
13321369Sdim// that the LLD's driver is agnostic on the host operating system.
14321369Sdim// Other linkers usually have implicit default values (such as a dynamic
15321369Sdim// linker path or library paths) for each host OS.
16321369Sdim//
17321369Sdim// I don't think implicit default values are useful because they are
18321369Sdim// usually explicitly specified by the compiler driver. They can even
19321369Sdim// be harmful when you are doing cross-linking. Therefore, in LLD, we
20321369Sdim// simply trust the compiler driver to pass all required options and
21321369Sdim// don't try to make effort on our side.
22321369Sdim//
23321369Sdim//===----------------------------------------------------------------------===//
24292934Sdim
25292934Sdim#include "Driver.h"
26292934Sdim#include "Config.h"
27303239Sdim#include "ICF.h"
28292934Sdim#include "InputFiles.h"
29303239Sdim#include "InputSection.h"
30303239Sdim#include "LinkerScript.h"
31341825Sdim#include "MarkLive.h"
32321369Sdim#include "OutputSections.h"
33321369Sdim#include "ScriptParser.h"
34292934Sdim#include "SymbolTable.h"
35327952Sdim#include "Symbols.h"
36321369Sdim#include "SyntheticSections.h"
37292934Sdim#include "Target.h"
38292934Sdim#include "Writer.h"
39327952Sdim#include "lld/Common/Args.h"
40327952Sdim#include "lld/Common/Driver.h"
41327952Sdim#include "lld/Common/ErrorHandler.h"
42353358Sdim#include "lld/Common/Filesystem.h"
43327952Sdim#include "lld/Common/Memory.h"
44341825Sdim#include "lld/Common/Strings.h"
45341825Sdim#include "lld/Common/TargetOptionsCommandFlags.h"
46327952Sdim#include "lld/Common/Threads.h"
47327952Sdim#include "lld/Common/Version.h"
48341825Sdim#include "llvm/ADT/SetVector.h"
49292934Sdim#include "llvm/ADT/StringExtras.h"
50303239Sdim#include "llvm/ADT/StringSwitch.h"
51360784Sdim#include "llvm/LTO/LTO.h"
52314564Sdim#include "llvm/Support/CommandLine.h"
53321369Sdim#include "llvm/Support/Compression.h"
54353358Sdim#include "llvm/Support/GlobPattern.h"
55341825Sdim#include "llvm/Support/LEB128.h"
56314564Sdim#include "llvm/Support/Path.h"
57314564Sdim#include "llvm/Support/TarWriter.h"
58303239Sdim#include "llvm/Support/TargetSelect.h"
59292934Sdim#include "llvm/Support/raw_ostream.h"
60303239Sdim#include <cstdlib>
61292934Sdim#include <utility>
62292934Sdim
63292934Sdimusing namespace llvm;
64292934Sdimusing namespace llvm::ELF;
65292934Sdimusing namespace llvm::object;
66303239Sdimusing namespace llvm::sys;
67344779Sdimusing namespace llvm::support;
68292934Sdim
69360784Sdimnamespace lld {
70360784Sdimnamespace elf {
71292934Sdim
72360784SdimConfiguration *config;
73360784SdimLinkerDriver *driver;
74292934Sdim
75353358Sdimstatic void setConfigs(opt::InputArgList &args);
76353358Sdimstatic void readConfigs(opt::InputArgList &args);
77321369Sdim
78360784Sdimbool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
79360784Sdim          raw_ostream &stderrOS) {
80360784Sdim  lld::stdoutOS = &stdoutOS;
81360784Sdim  lld::stderrOS = &stderrOS;
82360784Sdim
83353358Sdim  errorHandler().logName = args::getFilenameWithoutExe(args[0]);
84353358Sdim  errorHandler().errorLimitExceededMsg =
85327952Sdim      "too many errors emitted, stopping now (use "
86327952Sdim      "-error-limit=0 to see all errors)";
87353358Sdim  errorHandler().exitEarly = canExitEarly;
88360784Sdim  stderrOS.enable_colors(stderrOS.has_colors());
89341825Sdim
90353358Sdim  inputSections.clear();
91353358Sdim  outputSections.clear();
92353358Sdim  binaryFiles.clear();
93353358Sdim  bitcodeFiles.clear();
94353358Sdim  objectFiles.clear();
95353358Sdim  sharedFiles.clear();
96303239Sdim
97353358Sdim  config = make<Configuration>();
98353358Sdim  driver = make<LinkerDriver>();
99353358Sdim  script = make<LinkerScript>();
100353358Sdim  symtab = make<SymbolTable>();
101344779Sdim
102353358Sdim  tar = nullptr;
103353358Sdim  memset(&in, 0, sizeof(in));
104344779Sdim
105353358Sdim  partitions = {Partition()};
106303239Sdim
107353358Sdim  SharedFile::vernauxNum = 0;
108327952Sdim
109353358Sdim  config->progName = args[0];
110353358Sdim
111353358Sdim  driver->main(args);
112353358Sdim
113327952Sdim  // Exit immediately if we don't need to return to the caller.
114327952Sdim  // This saves time because the overhead of calling destructors
115327952Sdim  // for all globally-allocated objects is not negligible.
116353358Sdim  if (canExitEarly)
117327952Sdim    exitLld(errorCount() ? 1 : 0);
118327952Sdim
119314564Sdim  freeArena();
120327952Sdim  return !errorCount();
121292934Sdim}
122292934Sdim
123303239Sdim// Parses a linker -m option.
124353358Sdimstatic std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
125353358Sdim  uint8_t osabi = 0;
126353358Sdim  StringRef s = emul;
127353358Sdim  if (s.endswith("_fbsd")) {
128353358Sdim    s = s.drop_back(5);
129353358Sdim    osabi = ELFOSABI_FREEBSD;
130314564Sdim  }
131303239Sdim
132353358Sdim  std::pair<ELFKind, uint16_t> ret =
133353358Sdim      StringSwitch<std::pair<ELFKind, uint16_t>>(s)
134341825Sdim          .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
135341825Sdim                 {ELF64LEKind, EM_AARCH64})
136319957Semaste          .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
137303239Sdim          .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
138321369Sdim          .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
139321369Sdim          .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
140344779Sdim          .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
141344779Sdim          .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
142303239Sdim          .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
143303239Sdim          .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
144344779Sdim          .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
145303239Sdim          .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
146341825Sdim          .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
147314564Sdim          .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
148303239Sdim          .Case("elf_i386", {ELF32LEKind, EM_386})
149314564Sdim          .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
150303239Sdim          .Default({ELFNoneKind, EM_NONE});
151303239Sdim
152353358Sdim  if (ret.first == ELFNoneKind)
153353358Sdim    error("unknown emulation: " + emul);
154353358Sdim  return std::make_tuple(ret.first, ret.second, osabi);
155292934Sdim}
156292934Sdim
157293258Sdim// Returns slices of MB by parsing MB as an archive file.
158293258Sdim// Each slice consists of a member file in the archive.
159321369Sdimstd::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
160353358Sdim    MemoryBufferRef mb) {
161353358Sdim  std::unique_ptr<Archive> file =
162353358Sdim      CHECK(Archive::create(mb),
163353358Sdim            mb.getBufferIdentifier() + ": failed to parse archive");
164293258Sdim
165353358Sdim  std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
166353358Sdim  Error err = Error::success();
167353358Sdim  bool addToTar = file->isThin() && tar;
168360784Sdim  for (const Archive::Child &c : file->children(err)) {
169353358Sdim    MemoryBufferRef mbref =
170353358Sdim        CHECK(c.getMemoryBufferRef(),
171353358Sdim              mb.getBufferIdentifier() +
172314564Sdim                  ": could not get the buffer for a child of the archive");
173353358Sdim    if (addToTar)
174353358Sdim      tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
175353358Sdim    v.push_back(std::make_pair(mbref, c.getChildOffset()));
176293258Sdim  }
177353358Sdim  if (err)
178353358Sdim    fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
179353358Sdim          toString(std::move(err)));
180303239Sdim
181303239Sdim  // Take ownership of memory buffers created for members of thin archives.
182353358Sdim  for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
183353358Sdim    make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
184303239Sdim
185353358Sdim  return v;
186293258Sdim}
187293258Sdim
188321369Sdim// Opens a file and create a file object. Path has to be resolved already.
189353358Sdimvoid LinkerDriver::addFile(StringRef path, bool withLOption) {
190303239Sdim  using namespace sys::fs;
191292934Sdim
192353358Sdim  Optional<MemoryBufferRef> buffer = readFile(path);
193353358Sdim  if (!buffer.hasValue())
194303239Sdim    return;
195353358Sdim  MemoryBufferRef mbref = *buffer;
196303239Sdim
197353358Sdim  if (config->formatBinary) {
198353358Sdim    files.push_back(make<BinaryFile>(mbref));
199314564Sdim    return;
200314564Sdim  }
201314564Sdim
202353358Sdim  switch (identify_magic(mbref.getBuffer())) {
203292934Sdim  case file_magic::unknown:
204353358Sdim    readLinkerScript(mbref);
205292934Sdim    return;
206321369Sdim  case file_magic::archive: {
207321369Sdim    // Handle -whole-archive.
208353358Sdim    if (inWholeArchive) {
209353358Sdim      for (const auto &p : getArchiveMembers(mbref))
210353358Sdim        files.push_back(createObjectFile(p.first, path, p.second));
211292934Sdim      return;
212292934Sdim    }
213321369Sdim
214353358Sdim    std::unique_ptr<Archive> file =
215353358Sdim        CHECK(Archive::create(mbref), path + ": failed to parse archive");
216321369Sdim
217321369Sdim    // If an archive file has no symbol table, it is likely that a user
218321369Sdim    // is attempting LTO and using a default ar command that doesn't
219321369Sdim    // understand the LLVM bitcode file. It is a pretty common error, so
220321369Sdim    // we'll handle it as if it had a symbol table.
221353358Sdim    if (!file->isEmpty() && !file->hasSymbolTable()) {
222353358Sdim      // Check if all members are bitcode files. If not, ignore, which is the
223353358Sdim      // default action without the LTO hack described above.
224353358Sdim      for (const std::pair<MemoryBufferRef, uint64_t> &p :
225353358Sdim           getArchiveMembers(mbref))
226353358Sdim        if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
227353358Sdim          error(path + ": archive has no index; run ranlib to add one");
228353358Sdim          return;
229353358Sdim        }
230353358Sdim
231353358Sdim      for (const std::pair<MemoryBufferRef, uint64_t> &p :
232353358Sdim           getArchiveMembers(mbref))
233353358Sdim        files.push_back(make<LazyObjFile>(p.first, path, p.second));
234321369Sdim      return;
235321369Sdim    }
236321369Sdim
237321369Sdim    // Handle the regular case.
238353358Sdim    files.push_back(make<ArchiveFile>(std::move(file)));
239292934Sdim    return;
240321369Sdim  }
241292934Sdim  case file_magic::elf_shared_object:
242353358Sdim    if (config->isStatic || config->relocatable) {
243353358Sdim      error("attempted static link of dynamic object " + path);
244303239Sdim      return;
245303239Sdim    }
246321369Sdim
247321369Sdim    // DSOs usually have DT_SONAME tags in their ELF headers, and the
248321369Sdim    // sonames are used to identify DSOs. But if they are missing,
249321369Sdim    // they are identified by filenames. We don't know whether the new
250321369Sdim    // file has a DT_SONAME or not because we haven't parsed it yet.
251321369Sdim    // Here, we set the default soname for the file because we might
252321369Sdim    // need it later.
253321369Sdim    //
254321369Sdim    // If a file was specified by -lfoo, the directory part is not
255321369Sdim    // significant, as a user did not specify it. This behavior is
256321369Sdim    // compatible with GNU.
257353358Sdim    files.push_back(
258353358Sdim        make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
259292934Sdim    return;
260341825Sdim  case file_magic::bitcode:
261341825Sdim  case file_magic::elf_relocatable:
262353358Sdim    if (inLib)
263353358Sdim      files.push_back(make<LazyObjFile>(mbref, "", 0));
264303239Sdim    else
265353358Sdim      files.push_back(createObjectFile(mbref));
266341825Sdim    break;
267341825Sdim  default:
268353358Sdim    error(path + ": unknown file type");
269292934Sdim  }
270292934Sdim}
271292934Sdim
272303239Sdim// Add a given library by searching it from input search paths.
273353358Sdimvoid LinkerDriver::addLibrary(StringRef name) {
274353358Sdim  if (Optional<std::string> path = searchLibrary(name))
275353358Sdim    addFile(*path, /*withLOption=*/true);
276314564Sdim  else
277353358Sdim    error("unable to find library -l" + name);
278303239Sdim}
279303239Sdim
280303239Sdim// This function is called on startup. We need this for LTO since
281303239Sdim// LTO calls LLVM functions to compile bitcode files to native code.
282303239Sdim// Technically this can be delayed until we read bitcode files, but
283303239Sdim// we don't bother to do lazily because the initialization is fast.
284341825Sdimstatic void initLLVM() {
285303239Sdim  InitializeAllTargets();
286303239Sdim  InitializeAllTargetMCs();
287303239Sdim  InitializeAllAsmPrinters();
288303239Sdim  InitializeAllAsmParsers();
289303239Sdim}
290303239Sdim
291293846Sdim// Some command line options or some combinations of them are not allowed.
292293846Sdim// This function checks for such errors.
293344779Sdimstatic void checkOptions() {
294293846Sdim  // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
295293846Sdim  // table which is a relatively new feature.
296353358Sdim  if (config->emachine == EM_MIPS && config->gnuHash)
297344779Sdim    error("the .gnu.hash section is not compatible with the MIPS target");
298293846Sdim
299353358Sdim  if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
300344779Sdim    error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
301327952Sdim
302360784Sdim  if (config->fixCortexA8 && config->emachine != EM_ARM)
303360784Sdim    error("--fix-cortex-a8 is only supported on ARM targets");
304360784Sdim
305353358Sdim  if (config->tocOptimize && config->emachine != EM_PPC64)
306344779Sdim    error("--toc-optimize is only supported on the PowerPC64 target");
307344779Sdim
308353358Sdim  if (config->pie && config->shared)
309303239Sdim    error("-shared and -pie may not be used together");
310303239Sdim
311353358Sdim  if (!config->shared && !config->filterList.empty())
312321369Sdim    error("-F may not be used without -shared");
313321369Sdim
314353358Sdim  if (!config->shared && !config->auxiliaryList.empty())
315321369Sdim    error("-f may not be used without -shared");
316321369Sdim
317353358Sdim  if (!config->relocatable && !config->defineCommon)
318327952Sdim    error("-no-define-common not supported in non relocatable output");
319327952Sdim
320360784Sdim  if (config->strip == StripPolicy::All && config->emitRelocs)
321360784Sdim    error("--strip-all and --emit-relocs may not be used together");
322360784Sdim
323353358Sdim  if (config->zText && config->zIfuncNoplt)
324350467Sluporl    error("-z text and -z ifunc-noplt may not be used together");
325350467Sluporl
326353358Sdim  if (config->relocatable) {
327353358Sdim    if (config->shared)
328303239Sdim      error("-r and -shared may not be used together");
329353358Sdim    if (config->gcSections)
330303239Sdim      error("-r and --gc-sections may not be used together");
331353358Sdim    if (config->gdbIndex)
332341825Sdim      error("-r and --gdb-index may not be used together");
333353358Sdim    if (config->icf != ICFLevel::None)
334303239Sdim      error("-r and --icf may not be used together");
335353358Sdim    if (config->pie)
336303239Sdim      error("-r and -pie may not be used together");
337360784Sdim    if (config->exportDynamic)
338360784Sdim      error("-r and --export-dynamic may not be used together");
339303239Sdim  }
340341825Sdim
341353358Sdim  if (config->executeOnly) {
342353358Sdim    if (config->emachine != EM_AARCH64)
343341825Sdim      error("-execute-only is only supported on AArch64 targets");
344341825Sdim
345353358Sdim    if (config->singleRoRx && !script->hasSectionsCommand)
346341825Sdim      error("-execute-only and -no-rosegment cannot be used together");
347341825Sdim  }
348353358Sdim
349360784Sdim  if (config->zRetpolineplt && config->zForceIbt)
350360784Sdim    error("-z force-ibt may not be used with -z retpolineplt");
351353358Sdim
352353358Sdim  if (config->emachine != EM_AARCH64) {
353353358Sdim    if (config->pacPlt)
354360784Sdim      error("-z pac-plt only supported on AArch64");
355353358Sdim    if (config->forceBTI)
356360784Sdim      error("-z force-bti only supported on AArch64");
357353358Sdim  }
358293846Sdim}
359293846Sdim
360353358Sdimstatic const char *getReproduceOption(opt::InputArgList &args) {
361353358Sdim  if (auto *arg = args.getLastArg(OPT_reproduce))
362353358Sdim    return arg->getValue();
363303239Sdim  return getenv("LLD_REPRODUCE");
364303239Sdim}
365303239Sdim
366353358Sdimstatic bool hasZOption(opt::InputArgList &args, StringRef key) {
367353358Sdim  for (auto *arg : args.filtered(OPT_z))
368353358Sdim    if (key == arg->getValue())
369292934Sdim      return true;
370292934Sdim  return false;
371292934Sdim}
372292934Sdim
373353358Sdimstatic bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
374341825Sdim                     bool Default) {
375353358Sdim  for (auto *arg : args.filtered_reverse(OPT_z)) {
376353358Sdim    if (k1 == arg->getValue())
377341825Sdim      return true;
378353358Sdim    if (k2 == arg->getValue())
379341825Sdim      return false;
380341825Sdim  }
381341825Sdim  return Default;
382341825Sdim}
383341825Sdim
384360784Sdimstatic SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
385360784Sdim  for (auto *arg : args.filtered_reverse(OPT_z)) {
386360784Sdim    StringRef v = arg->getValue();
387360784Sdim    if (v == "noseparate-code")
388360784Sdim      return SeparateSegmentKind::None;
389360784Sdim    if (v == "separate-code")
390360784Sdim      return SeparateSegmentKind::Code;
391360784Sdim    if (v == "separate-loadable-segments")
392360784Sdim      return SeparateSegmentKind::Loadable;
393360784Sdim  }
394360784Sdim  return SeparateSegmentKind::None;
395360784Sdim}
396360784Sdim
397360784Sdimstatic GnuStackKind getZGnuStack(opt::InputArgList &args) {
398360784Sdim  for (auto *arg : args.filtered_reverse(OPT_z)) {
399360784Sdim    if (StringRef("execstack") == arg->getValue())
400360784Sdim      return GnuStackKind::Exec;
401360784Sdim    if (StringRef("noexecstack") == arg->getValue())
402360784Sdim      return GnuStackKind::NoExec;
403360784Sdim    if (StringRef("nognustack") == arg->getValue())
404360784Sdim      return GnuStackKind::None;
405360784Sdim  }
406360784Sdim
407360784Sdim  return GnuStackKind::NoExec;
408360784Sdim}
409360784Sdim
410353358Sdimstatic bool isKnownZFlag(StringRef s) {
411353358Sdim  return s == "combreloc" || s == "copyreloc" || s == "defs" ||
412360784Sdim         s == "execstack" || s == "force-bti" || s == "force-ibt" ||
413360784Sdim         s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
414360784Sdim         s == "initfirst" || s == "interpose" ||
415353358Sdim         s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
416360784Sdim         s == "separate-code" || s == "separate-loadable-segments" ||
417353358Sdim         s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" ||
418353358Sdim         s == "nodelete" || s == "nodlopen" || s == "noexecstack" ||
419360784Sdim         s == "nognustack" || s == "nokeep-text-section-prefix" ||
420360784Sdim         s == "norelro" || s == "noseparate-code" || s == "notext" ||
421360784Sdim         s == "now" || s == "origin" || s == "pac-plt" || s == "relro" ||
422360784Sdim         s == "retpolineplt" || s == "rodynamic" || s == "shstk" ||
423360784Sdim         s == "text" || s == "undefs" || s == "wxneeded" ||
424360784Sdim         s.startswith("common-page-size=") || s.startswith("max-page-size=") ||
425353358Sdim         s.startswith("stack-size=");
426341825Sdim}
427341825Sdim
428341825Sdim// Report an error for an unknown -z option.
429353358Sdimstatic void checkZOptions(opt::InputArgList &args) {
430353358Sdim  for (auto *arg : args.filtered(OPT_z))
431353358Sdim    if (!isKnownZFlag(arg->getValue()))
432353358Sdim      error("unknown -z value: " + StringRef(arg->getValue()));
433341825Sdim}
434341825Sdim
435353358Sdimvoid LinkerDriver::main(ArrayRef<const char *> argsArr) {
436353358Sdim  ELFOptTable parser;
437353358Sdim  opt::InputArgList args = parser.parse(argsArr.slice(1));
438314564Sdim
439314564Sdim  // Interpret this flag early because error() depends on them.
440353358Sdim  errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
441353358Sdim  checkZOptions(args);
442314564Sdim
443314564Sdim  // Handle -help
444353358Sdim  if (args.hasArg(OPT_help)) {
445341825Sdim    printHelp();
446303239Sdim    return;
447303239Sdim  }
448314564Sdim
449316029Semaste  // Handle -v or -version.
450316029Semaste  //
451316029Semaste  // A note about "compatible with GNU linkers" message: this is a hack for
452316029Semaste  // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
453316029Semaste  // still the newest version in March 2017) or earlier to recognize LLD as
454316029Semaste  // a GNU compatible linker. As long as an output for the -v option
455316029Semaste  // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
456316029Semaste  //
457316029Semaste  // This is somewhat ugly hack, but in reality, we had no choice other
458316029Semaste  // than doing this. Considering the very long release cycle of Libtool,
459316029Semaste  // it is not easy to improve it to recognize LLD as a GNU compatible
460316029Semaste  // linker in a timely manner. Even if we can make it, there are still a
461316029Semaste  // lot of "configure" scripts out there that are generated by old version
462316029Semaste  // of Libtool. We cannot convince every software developer to migrate to
463316029Semaste  // the latest version and re-generate scripts. So we have this hack.
464353358Sdim  if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
465321369Sdim    message(getLLDVersion() + " (compatible with GNU linkers)");
466316029Semaste
467353358Sdim  if (const char *path = getReproduceOption(args)) {
468303239Sdim    // Note that --reproduce is a debug option so you can ignore it
469303239Sdim    // if you are trying to understand the whole picture of the code.
470353358Sdim    Expected<std::unique_ptr<TarWriter>> errOrWriter =
471353358Sdim        TarWriter::create(path, path::stem(path));
472353358Sdim    if (errOrWriter) {
473353358Sdim      tar = std::move(*errOrWriter);
474353358Sdim      tar->append("response.txt", createResponseFile(args));
475353358Sdim      tar->append("version.txt", getLLDVersion() + "\n");
476314564Sdim    } else {
477353358Sdim      error("--reproduce: " + toString(errOrWriter.takeError()));
478303239Sdim    }
479303239Sdim  }
480303239Sdim
481353358Sdim  readConfigs(args);
482344779Sdim
483344779Sdim  // The behavior of -v or --version is a bit strange, but this is
484344779Sdim  // needed for compatibility with GNU linkers.
485353358Sdim  if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
486344779Sdim    return;
487353358Sdim  if (args.hasArg(OPT_version))
488344779Sdim    return;
489344779Sdim
490341825Sdim  initLLVM();
491353358Sdim  createFiles(args);
492341825Sdim  if (errorCount())
493341825Sdim    return;
494341825Sdim
495314564Sdim  inferMachineType();
496353358Sdim  setConfigs(args);
497344779Sdim  checkOptions();
498327952Sdim  if (errorCount())
499303239Sdim    return;
500292934Sdim
501353358Sdim  // The Target instance handles target-specific stuff, such as applying
502353358Sdim  // relocations or writing a PLT section. It also contains target-dependent
503353358Sdim  // values such as a default image base address.
504353358Sdim  target = getTarget();
505353358Sdim
506353358Sdim  switch (config->ekind) {
507292934Sdim  case ELF32LEKind:
508353358Sdim    link<ELF32LE>(args);
509292934Sdim    return;
510292934Sdim  case ELF32BEKind:
511353358Sdim    link<ELF32BE>(args);
512292934Sdim    return;
513292934Sdim  case ELF64LEKind:
514353358Sdim    link<ELF64LE>(args);
515292934Sdim    return;
516292934Sdim  case ELF64BEKind:
517353358Sdim    link<ELF64BE>(args);
518292934Sdim    return;
519292934Sdim  default:
520314564Sdim    llvm_unreachable("unknown Config->EKind");
521292934Sdim  }
522292934Sdim}
523292934Sdim
524353358Sdimstatic std::string getRpath(opt::InputArgList &args) {
525353358Sdim  std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
526353358Sdim  return llvm::join(v.begin(), v.end(), ":");
527321369Sdim}
528321369Sdim
529321369Sdim// Determines what we should do if there are remaining unresolved
530321369Sdim// symbols after the name resolution.
531353358Sdimstatic UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
532353358Sdim  UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
533327952Sdim                                              OPT_warn_unresolved_symbols, true)
534321369Sdim                                     ? UnresolvedPolicy::ReportError
535321369Sdim                                     : UnresolvedPolicy::Warn;
536321369Sdim
537321369Sdim  // Process the last of -unresolved-symbols, -no-undefined or -z defs.
538353358Sdim  for (auto *arg : llvm::reverse(args)) {
539353358Sdim    switch (arg->getOption().getID()) {
540321369Sdim    case OPT_unresolved_symbols: {
541353358Sdim      StringRef s = arg->getValue();
542353358Sdim      if (s == "ignore-all" || s == "ignore-in-object-files")
543321369Sdim        return UnresolvedPolicy::Ignore;
544353358Sdim      if (s == "ignore-in-shared-libs" || s == "report-all")
545353358Sdim        return errorOrWarn;
546353358Sdim      error("unknown --unresolved-symbols value: " + s);
547321369Sdim      continue;
548321369Sdim    }
549321369Sdim    case OPT_no_undefined:
550353358Sdim      return errorOrWarn;
551321369Sdim    case OPT_z:
552353358Sdim      if (StringRef(arg->getValue()) == "defs")
553353358Sdim        return errorOrWarn;
554360784Sdim      if (StringRef(arg->getValue()) == "undefs")
555360784Sdim        return UnresolvedPolicy::Ignore;
556321369Sdim      continue;
557321369Sdim    }
558303239Sdim  }
559321369Sdim
560321369Sdim  // -shared implies -unresolved-symbols=ignore-all because missing
561321369Sdim  // symbols are likely to be resolved at runtime using other DSOs.
562353358Sdim  if (config->shared)
563321369Sdim    return UnresolvedPolicy::Ignore;
564353358Sdim  return errorOrWarn;
565303239Sdim}
566303239Sdim
567353358Sdimstatic Target2Policy getTarget2(opt::InputArgList &args) {
568353358Sdim  StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
569353358Sdim  if (s == "rel")
570321369Sdim    return Target2Policy::Rel;
571353358Sdim  if (s == "abs")
572321369Sdim    return Target2Policy::Abs;
573353358Sdim  if (s == "got-rel")
574321369Sdim    return Target2Policy::GotRel;
575353358Sdim  error("unknown --target2 option: " + s);
576314564Sdim  return Target2Policy::GotRel;
577314564Sdim}
578314564Sdim
579353358Sdimstatic bool isOutputFormatBinary(opt::InputArgList &args) {
580353358Sdim  StringRef s = args.getLastArgValue(OPT_oformat, "elf");
581353358Sdim  if (s == "binary")
582344779Sdim    return true;
583353358Sdim  if (!s.startswith("elf"))
584353358Sdim    error("unknown --oformat value: " + s);
585314564Sdim  return false;
586314564Sdim}
587314564Sdim
588353358Sdimstatic DiscardPolicy getDiscard(opt::InputArgList &args) {
589353358Sdim  if (args.hasArg(OPT_relocatable))
590321369Sdim    return DiscardPolicy::None;
591314564Sdim
592353358Sdim  auto *arg =
593353358Sdim      args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
594353358Sdim  if (!arg)
595314564Sdim    return DiscardPolicy::Default;
596353358Sdim  if (arg->getOption().getID() == OPT_discard_all)
597314564Sdim    return DiscardPolicy::All;
598353358Sdim  if (arg->getOption().getID() == OPT_discard_locals)
599314564Sdim    return DiscardPolicy::Locals;
600314564Sdim  return DiscardPolicy::None;
601314564Sdim}
602314564Sdim
603353358Sdimstatic StringRef getDynamicLinker(opt::InputArgList &args) {
604353358Sdim  auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
605360784Sdim  if (!arg)
606321369Sdim    return "";
607360784Sdim  if (arg->getOption().getID() == OPT_no_dynamic_linker) {
608360784Sdim    // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
609360784Sdim    config->noDynamicLinker = true;
610360784Sdim    return "";
611360784Sdim  }
612353358Sdim  return arg->getValue();
613314564Sdim}
614314564Sdim
615353358Sdimstatic ICFLevel getICF(opt::InputArgList &args) {
616353358Sdim  auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
617353358Sdim  if (!arg || arg->getOption().getID() == OPT_icf_none)
618341825Sdim    return ICFLevel::None;
619353358Sdim  if (arg->getOption().getID() == OPT_icf_safe)
620341825Sdim    return ICFLevel::Safe;
621341825Sdim  return ICFLevel::All;
622341825Sdim}
623341825Sdim
624353358Sdimstatic StripPolicy getStrip(opt::InputArgList &args) {
625353358Sdim  if (args.hasArg(OPT_relocatable))
626321369Sdim    return StripPolicy::None;
627321369Sdim
628353358Sdim  auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
629353358Sdim  if (!arg)
630321369Sdim    return StripPolicy::None;
631353358Sdim  if (arg->getOption().getID() == OPT_strip_all)
632321369Sdim    return StripPolicy::All;
633321369Sdim  return StripPolicy::Debug;
634321369Sdim}
635321369Sdim
636353358Sdimstatic uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
637353358Sdim                                    const opt::Arg &arg) {
638353358Sdim  uint64_t va = 0;
639353358Sdim  if (s.startswith("0x"))
640353358Sdim    s = s.drop_front(2);
641353358Sdim  if (!to_integer(s, va, 16))
642353358Sdim    error("invalid argument: " + arg.getAsString(args));
643353358Sdim  return va;
644314564Sdim}
645314564Sdim
646353358Sdimstatic StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
647353358Sdim  StringMap<uint64_t> ret;
648353358Sdim  for (auto *arg : args.filtered(OPT_section_start)) {
649353358Sdim    StringRef name;
650353358Sdim    StringRef addr;
651353358Sdim    std::tie(name, addr) = StringRef(arg->getValue()).split('=');
652353358Sdim    ret[name] = parseSectionAddress(addr, args, *arg);
653314564Sdim  }
654314564Sdim
655353358Sdim  if (auto *arg = args.getLastArg(OPT_Ttext))
656353358Sdim    ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
657353358Sdim  if (auto *arg = args.getLastArg(OPT_Tdata))
658353358Sdim    ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
659353358Sdim  if (auto *arg = args.getLastArg(OPT_Tbss))
660353358Sdim    ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
661353358Sdim  return ret;
662314564Sdim}
663314564Sdim
664353358Sdimstatic SortSectionPolicy getSortSection(opt::InputArgList &args) {
665353358Sdim  StringRef s = args.getLastArgValue(OPT_sort_section);
666353358Sdim  if (s == "alignment")
667314564Sdim    return SortSectionPolicy::Alignment;
668353358Sdim  if (s == "name")
669314564Sdim    return SortSectionPolicy::Name;
670353358Sdim  if (!s.empty())
671353358Sdim    error("unknown --sort-section rule: " + s);
672314564Sdim  return SortSectionPolicy::Default;
673314564Sdim}
674314564Sdim
675353358Sdimstatic OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
676353358Sdim  StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
677353358Sdim  if (s == "warn")
678327952Sdim    return OrphanHandlingPolicy::Warn;
679353358Sdim  if (s == "error")
680327952Sdim    return OrphanHandlingPolicy::Error;
681353358Sdim  if (s != "place")
682353358Sdim    error("unknown --orphan-handling mode: " + s);
683327952Sdim  return OrphanHandlingPolicy::Place;
684321369Sdim}
685321369Sdim
686321369Sdim// Parse --build-id or --build-id=<style>. We handle "tree" as a
687321369Sdim// synonym for "sha1" because all our hash functions including
688321369Sdim// -build-id=sha1 are actually tree hashes for performance reasons.
689321369Sdimstatic std::pair<BuildIdKind, std::vector<uint8_t>>
690353358SdimgetBuildId(opt::InputArgList &args) {
691353358Sdim  auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
692353358Sdim  if (!arg)
693321369Sdim    return {BuildIdKind::None, {}};
694321369Sdim
695353358Sdim  if (arg->getOption().getID() == OPT_build_id)
696321369Sdim    return {BuildIdKind::Fast, {}};
697321369Sdim
698353358Sdim  StringRef s = arg->getValue();
699353358Sdim  if (s == "fast")
700341825Sdim    return {BuildIdKind::Fast, {}};
701353358Sdim  if (s == "md5")
702321369Sdim    return {BuildIdKind::Md5, {}};
703353358Sdim  if (s == "sha1" || s == "tree")
704321369Sdim    return {BuildIdKind::Sha1, {}};
705353358Sdim  if (s == "uuid")
706321369Sdim    return {BuildIdKind::Uuid, {}};
707353358Sdim  if (s.startswith("0x"))
708353358Sdim    return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
709321369Sdim
710353358Sdim  if (s != "none")
711353358Sdim    error("unknown --build-id style: " + s);
712321369Sdim  return {BuildIdKind::None, {}};
713321369Sdim}
714321369Sdim
715353358Sdimstatic std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
716353358Sdim  StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
717353358Sdim  if (s == "android")
718341825Sdim    return {true, false};
719353358Sdim  if (s == "relr")
720341825Sdim    return {false, true};
721353358Sdim  if (s == "android+relr")
722341825Sdim    return {true, true};
723341825Sdim
724353358Sdim  if (s != "none")
725353358Sdim    error("unknown -pack-dyn-relocs format: " + s);
726341825Sdim  return {false, false};
727341825Sdim}
728341825Sdim
729353358Sdimstatic void readCallGraph(MemoryBufferRef mb) {
730341825Sdim  // Build a map from symbol name to section
731353358Sdim  DenseMap<StringRef, Symbol *> map;
732353358Sdim  for (InputFile *file : objectFiles)
733353358Sdim    for (Symbol *sym : file->getSymbols())
734353358Sdim      map[sym->getName()] = sym;
735341825Sdim
736353358Sdim  auto findSection = [&](StringRef name) -> InputSectionBase * {
737353358Sdim    Symbol *sym = map.lookup(name);
738353358Sdim    if (!sym) {
739353358Sdim      if (config->warnSymbolOrdering)
740353358Sdim        warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
741344779Sdim      return nullptr;
742344779Sdim    }
743353358Sdim    maybeWarnUnorderableSymbol(sym);
744344779Sdim
745353358Sdim    if (Defined *dr = dyn_cast_or_null<Defined>(sym))
746353358Sdim      return dyn_cast_or_null<InputSectionBase>(dr->section);
747344779Sdim    return nullptr;
748344779Sdim  };
749344779Sdim
750353358Sdim  for (StringRef line : args::getLines(mb)) {
751353358Sdim    SmallVector<StringRef, 3> fields;
752353358Sdim    line.split(fields, ' ');
753353358Sdim    uint64_t count;
754344779Sdim
755353358Sdim    if (fields.size() != 3 || !to_integer(fields[2], count)) {
756353358Sdim      error(mb.getBufferIdentifier() + ": parse error");
757344779Sdim      return;
758341825Sdim    }
759344779Sdim
760353358Sdim    if (InputSectionBase *from = findSection(fields[0]))
761353358Sdim      if (InputSectionBase *to = findSection(fields[1]))
762353358Sdim        config->callGraphProfile[std::make_pair(from, to)] += count;
763341825Sdim  }
764341825Sdim}
765341825Sdim
766344779Sdimtemplate <class ELFT> static void readCallGraphsFromObjectFiles() {
767353358Sdim  for (auto file : objectFiles) {
768353358Sdim    auto *obj = cast<ObjFile<ELFT>>(file);
769344779Sdim
770353358Sdim    for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
771353358Sdim      auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
772353358Sdim      auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
773353358Sdim      if (!fromSym || !toSym)
774344779Sdim        continue;
775344779Sdim
776353358Sdim      auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
777353358Sdim      auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
778353358Sdim      if (from && to)
779353358Sdim        config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
780344779Sdim    }
781344779Sdim  }
782344779Sdim}
783344779Sdim
784353358Sdimstatic bool getCompressDebugSections(opt::InputArgList &args) {
785353358Sdim  StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
786353358Sdim  if (s == "none")
787321369Sdim    return false;
788353358Sdim  if (s != "zlib")
789353358Sdim    error("unknown --compress-debug-sections value: " + s);
790321369Sdim  if (!zlib::isAvailable())
791321369Sdim    error("--compress-debug-sections: zlib is not available");
792321369Sdim  return true;
793321369Sdim}
794321369Sdim
795360784Sdimstatic StringRef getAliasSpelling(opt::Arg *arg) {
796360784Sdim  if (const opt::Arg *alias = arg->getAlias())
797360784Sdim    return alias->getSpelling();
798360784Sdim  return arg->getSpelling();
799360784Sdim}
800360784Sdim
801353358Sdimstatic std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
802353358Sdim                                                        unsigned id) {
803353358Sdim  auto *arg = args.getLastArg(id);
804353358Sdim  if (!arg)
805341825Sdim    return {"", ""};
806341825Sdim
807353358Sdim  StringRef s = arg->getValue();
808353358Sdim  std::pair<StringRef, StringRef> ret = s.split(';');
809353358Sdim  if (ret.second.empty())
810360784Sdim    error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
811353358Sdim  return ret;
812327952Sdim}
813327952Sdim
814341825Sdim// Parse the symbol ordering file and warn for any duplicate entries.
815353358Sdimstatic std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
816353358Sdim  SetVector<StringRef> names;
817353358Sdim  for (StringRef s : args::getLines(mb))
818353358Sdim    if (!names.insert(s) && config->warnSymbolOrdering)
819353358Sdim      warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
820341825Sdim
821353358Sdim  return names.takeVector();
822341825Sdim}
823341825Sdim
824353358Sdimstatic void parseClangOption(StringRef opt, const Twine &msg) {
825353358Sdim  std::string err;
826353358Sdim  raw_string_ostream os(err);
827341825Sdim
828353358Sdim  const char *argv[] = {config->progName.data(), opt.data()};
829353358Sdim  if (cl::ParseCommandLineOptions(2, argv, "", &os))
830341825Sdim    return;
831353358Sdim  os.flush();
832353358Sdim  error(msg + ": " + StringRef(err).trim());
833341825Sdim}
834341825Sdim
835293846Sdim// Initializes Config members by the command line options.
836353358Sdimstatic void readConfigs(opt::InputArgList &args) {
837353358Sdim  errorHandler().verbose = args.hasArg(OPT_verbose);
838353358Sdim  errorHandler().fatalWarnings =
839353358Sdim      args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
840353358Sdim  errorHandler().vsDiagnostics =
841353358Sdim      args.hasArg(OPT_visual_studio_diagnostics_format, false);
842353358Sdim  threadsEnabled = args.hasFlag(OPT_threads, OPT_no_threads, true);
843341825Sdim
844353358Sdim  config->allowMultipleDefinition =
845353358Sdim      args.hasFlag(OPT_allow_multiple_definition,
846341825Sdim                   OPT_no_allow_multiple_definition, false) ||
847353358Sdim      hasZOption(args, "muldefs");
848353358Sdim  config->allowShlibUndefined =
849353358Sdim      args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
850353358Sdim                   args.hasArg(OPT_shared));
851353358Sdim  config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
852353358Sdim  config->bsymbolic = args.hasArg(OPT_Bsymbolic);
853353358Sdim  config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions);
854353358Sdim  config->checkSections =
855353358Sdim      args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
856353358Sdim  config->chroot = args.getLastArgValue(OPT_chroot);
857353358Sdim  config->compressDebugSections = getCompressDebugSections(args);
858353358Sdim  config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false);
859353358Sdim  config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
860353358Sdim                                      !args.hasArg(OPT_relocatable));
861353358Sdim  config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
862353358Sdim  config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
863353358Sdim  config->disableVerify = args.hasArg(OPT_disable_verify);
864353358Sdim  config->discard = getDiscard(args);
865353358Sdim  config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
866353358Sdim  config->dynamicLinker = getDynamicLinker(args);
867353358Sdim  config->ehFrameHdr =
868353358Sdim      args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
869353358Sdim  config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
870353358Sdim  config->emitRelocs = args.hasArg(OPT_emit_relocs);
871353358Sdim  config->callGraphProfileSort = args.hasFlag(
872344779Sdim      OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
873353358Sdim  config->enableNewDtags =
874353358Sdim      args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
875353358Sdim  config->entry = args.getLastArgValue(OPT_entry);
876353358Sdim  config->executeOnly =
877353358Sdim      args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
878353358Sdim  config->exportDynamic =
879353358Sdim      args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
880353358Sdim  config->filterList = args::getStrings(args, OPT_filter);
881353358Sdim  config->fini = args.getLastArgValue(OPT_fini, "_fini");
882353358Sdim  config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419);
883360784Sdim  config->fixCortexA8 = args.hasArg(OPT_fix_cortex_a8);
884360784Sdim  config->forceBTI = hasZOption(args, "force-bti");
885353358Sdim  config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
886353358Sdim  config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
887353358Sdim  config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
888353358Sdim  config->icf = getICF(args);
889353358Sdim  config->ignoreDataAddressEquality =
890353358Sdim      args.hasArg(OPT_ignore_data_address_equality);
891353358Sdim  config->ignoreFunctionAddressEquality =
892353358Sdim      args.hasArg(OPT_ignore_function_address_equality);
893353358Sdim  config->init = args.getLastArgValue(OPT_init, "_init");
894353358Sdim  config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
895353358Sdim  config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
896353358Sdim  config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
897353358Sdim  config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
898353358Sdim  config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager);
899353358Sdim  config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
900353358Sdim  config->ltoo = args::getInteger(args, OPT_lto_O, 2);
901360784Sdim  config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
902353358Sdim  config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
903353358Sdim  config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
904353358Sdim  config->mapFile = args.getLastArgValue(OPT_Map);
905353358Sdim  config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
906353358Sdim  config->mergeArmExidx =
907353358Sdim      args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
908360784Sdim  config->mmapOutputFile =
909360784Sdim      args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
910353358Sdim  config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
911353358Sdim  config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
912353358Sdim  config->nostdlib = args.hasArg(OPT_nostdlib);
913353358Sdim  config->oFormatBinary = isOutputFormatBinary(args);
914353358Sdim  config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
915353358Sdim  config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
916353358Sdim  config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
917353358Sdim  config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
918353358Sdim  config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
919353358Sdim  config->optimize = args::getInteger(args, OPT_O, 1);
920353358Sdim  config->orphanHandling = getOrphanHandling(args);
921353358Sdim  config->outputFile = args.getLastArgValue(OPT_o);
922360784Sdim  config->pacPlt = hasZOption(args, "pac-plt");
923353358Sdim  config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
924353358Sdim  config->printIcfSections =
925353358Sdim      args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
926353358Sdim  config->printGcSections =
927353358Sdim      args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
928353358Sdim  config->printSymbolOrder =
929353358Sdim      args.getLastArgValue(OPT_print_symbol_order);
930353358Sdim  config->rpath = getRpath(args);
931353358Sdim  config->relocatable = args.hasArg(OPT_relocatable);
932353358Sdim  config->saveTemps = args.hasArg(OPT_save_temps);
933353358Sdim  config->searchPaths = args::getStrings(args, OPT_library_path);
934353358Sdim  config->sectionStartMap = getSectionStartMap(args);
935353358Sdim  config->shared = args.hasArg(OPT_shared);
936353358Sdim  config->singleRoRx = args.hasArg(OPT_no_rosegment);
937353358Sdim  config->soName = args.getLastArgValue(OPT_soname);
938353358Sdim  config->sortSection = getSortSection(args);
939353358Sdim  config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
940353358Sdim  config->strip = getStrip(args);
941353358Sdim  config->sysroot = args.getLastArgValue(OPT_sysroot);
942353358Sdim  config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
943353358Sdim  config->target2 = getTarget2(args);
944353358Sdim  config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
945353358Sdim  config->thinLTOCachePolicy = CHECK(
946353358Sdim      parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
947321369Sdim      "--thinlto-cache-policy: invalid cache policy");
948360784Sdim  config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
949360784Sdim  config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
950360784Sdim                             args.hasArg(OPT_thinlto_index_only_eq);
951360784Sdim  config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
952353358Sdim  config->thinLTOJobs = args::getInteger(args, OPT_thinlto_jobs, -1u);
953353358Sdim  config->thinLTOObjectSuffixReplace =
954360784Sdim      getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
955353358Sdim  config->thinLTOPrefixReplace =
956360784Sdim      getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
957353358Sdim  config->trace = args.hasArg(OPT_trace);
958353358Sdim  config->undefined = args::getStrings(args, OPT_undefined);
959353358Sdim  config->undefinedVersion =
960353358Sdim      args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
961353358Sdim  config->useAndroidRelrTags = args.hasFlag(
962341825Sdim      OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
963353358Sdim  config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
964353358Sdim  config->warnBackrefs =
965353358Sdim      args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
966353358Sdim  config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
967353358Sdim  config->warnIfuncTextrel =
968353358Sdim      args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
969353358Sdim  config->warnSymbolOrdering =
970353358Sdim      args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
971353358Sdim  config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
972353358Sdim  config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
973360784Sdim  config->zForceIbt = hasZOption(args, "force-ibt");
974353358Sdim  config->zGlobal = hasZOption(args, "global");
975360784Sdim  config->zGnustack = getZGnuStack(args);
976353358Sdim  config->zHazardplt = hasZOption(args, "hazardplt");
977353358Sdim  config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
978353358Sdim  config->zInitfirst = hasZOption(args, "initfirst");
979353358Sdim  config->zInterpose = hasZOption(args, "interpose");
980353358Sdim  config->zKeepTextSectionPrefix = getZFlag(
981353358Sdim      args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
982353358Sdim  config->zNodefaultlib = hasZOption(args, "nodefaultlib");
983353358Sdim  config->zNodelete = hasZOption(args, "nodelete");
984353358Sdim  config->zNodlopen = hasZOption(args, "nodlopen");
985353358Sdim  config->zNow = getZFlag(args, "now", "lazy", false);
986353358Sdim  config->zOrigin = hasZOption(args, "origin");
987353358Sdim  config->zRelro = getZFlag(args, "relro", "norelro", true);
988353358Sdim  config->zRetpolineplt = hasZOption(args, "retpolineplt");
989353358Sdim  config->zRodynamic = hasZOption(args, "rodynamic");
990360784Sdim  config->zSeparate = getZSeparate(args);
991360784Sdim  config->zShstk = hasZOption(args, "shstk");
992353358Sdim  config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
993353358Sdim  config->zText = getZFlag(args, "text", "notext", true);
994353358Sdim  config->zWxneeded = hasZOption(args, "wxneeded");
995292934Sdim
996341825Sdim  // Parse LTO options.
997353358Sdim  if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
998353358Sdim    parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
999353358Sdim                     arg->getSpelling());
1000327952Sdim
1001353358Sdim  for (auto *arg : args.filtered(OPT_plugin_opt))
1002353358Sdim    parseClangOption(arg->getValue(), arg->getSpelling());
1003341825Sdim
1004341825Sdim  // Parse -mllvm options.
1005353358Sdim  for (auto *arg : args.filtered(OPT_mllvm))
1006353358Sdim    parseClangOption(arg->getValue(), arg->getSpelling());
1007341825Sdim
1008353358Sdim  if (config->ltoo > 3)
1009353358Sdim    error("invalid optimization level for LTO: " + Twine(config->ltoo));
1010353358Sdim  if (config->ltoPartitions == 0)
1011321369Sdim    error("--lto-partitions: number of threads must be > 0");
1012353358Sdim  if (config->thinLTOJobs == 0)
1013321369Sdim    error("--thinlto-jobs: number of threads must be > 0");
1014292934Sdim
1015353358Sdim  if (config->splitStackAdjustSize < 0)
1016344779Sdim    error("--split-stack-adjust-size: size must be >= 0");
1017344779Sdim
1018360784Sdim  // The text segment is traditionally the first segment, whose address equals
1019360784Sdim  // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1020360784Sdim  // is an old-fashioned option that does not play well with lld's layout.
1021360784Sdim  // Suggest --image-base as a likely alternative.
1022360784Sdim  if (args.hasArg(OPT_Ttext_segment))
1023360784Sdim    error("-Ttext-segment is not supported. Use --image-base if you "
1024360784Sdim          "intend to set the base address");
1025360784Sdim
1026327952Sdim  // Parse ELF{32,64}{LE,BE} and CPU type.
1027353358Sdim  if (auto *arg = args.getLastArg(OPT_m)) {
1028353358Sdim    StringRef s = arg->getValue();
1029353358Sdim    std::tie(config->ekind, config->emachine, config->osabi) =
1030353358Sdim        parseEmulation(s);
1031353738Sdim    config->mipsN32Abi =
1032353738Sdim        (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1033353358Sdim    config->emulation = s;
1034321369Sdim  }
1035321369Sdim
1036327952Sdim  // Parse -hash-style={sysv,gnu,both}.
1037353358Sdim  if (auto *arg = args.getLastArg(OPT_hash_style)) {
1038353358Sdim    StringRef s = arg->getValue();
1039353358Sdim    if (s == "sysv")
1040353358Sdim      config->sysvHash = true;
1041353358Sdim    else if (s == "gnu")
1042353358Sdim      config->gnuHash = true;
1043353358Sdim    else if (s == "both")
1044353358Sdim      config->sysvHash = config->gnuHash = true;
1045327952Sdim    else
1046353358Sdim      error("unknown -hash-style: " + s);
1047327952Sdim  }
1048327952Sdim
1049353358Sdim  if (args.hasArg(OPT_print_map))
1050353358Sdim    config->mapFile = "-";
1051321369Sdim
1052353358Sdim  // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1053353358Sdim  // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1054353358Sdim  // it.
1055353358Sdim  if (config->nmagic || config->omagic)
1056353358Sdim    config->zRelro = false;
1057303239Sdim
1058353358Sdim  std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1059314564Sdim
1060353358Sdim  std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1061353358Sdim      getPackDynRelocs(args);
1062327952Sdim
1063353358Sdim  if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1064353358Sdim    if (args.hasArg(OPT_call_graph_ordering_file))
1065353358Sdim      error("--symbol-ordering-file and --call-graph-order-file "
1066353358Sdim            "may not be used together");
1067353358Sdim    if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1068353358Sdim      config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1069353358Sdim      // Also need to disable CallGraphProfileSort to prevent
1070353358Sdim      // LLD order symbols with CGProfile
1071353358Sdim      config->callGraphProfileSort = false;
1072353358Sdim    }
1073353358Sdim  }
1074314564Sdim
1075360784Sdim  assert(config->versionDefinitions.empty());
1076360784Sdim  config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}});
1077360784Sdim  config->versionDefinitions.push_back(
1078360784Sdim      {"global", (uint16_t)VER_NDX_GLOBAL, {}});
1079360784Sdim
1080321369Sdim  // If --retain-symbol-file is used, we'll keep only the symbols listed in
1081314564Sdim  // the file and discard all others.
1082353358Sdim  if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1083360784Sdim    config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(
1084360784Sdim        {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1085353358Sdim    if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1086353358Sdim      for (StringRef s : args::getLines(*buffer))
1087360784Sdim        config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(
1088360784Sdim            {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1089314564Sdim  }
1090314564Sdim
1091321369Sdim  // Parses -dynamic-list and -export-dynamic-symbol. They make some
1092321369Sdim  // symbols private. Note that -export-dynamic takes precedence over them
1093321369Sdim  // as it says all symbols should be exported.
1094360784Sdim  if (!config->exportDynamic) {
1095353358Sdim    for (auto *arg : args.filtered(OPT_dynamic_list))
1096353358Sdim      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1097353358Sdim        readDynamicList(*buffer);
1098321369Sdim
1099353358Sdim    for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1100353358Sdim      config->dynamicList.push_back(
1101360784Sdim          {arg->getValue(), /*isExternCpp=*/false, /*hasWildcard=*/false});
1102314564Sdim  }
1103314564Sdim
1104341825Sdim  // If --export-dynamic-symbol=foo is given and symbol foo is defined in
1105341825Sdim  // an object file in an archive file, that object file should be pulled
1106341825Sdim  // out and linked. (It doesn't have to behave like that from technical
1107341825Sdim  // point of view, but this is needed for compatibility with GNU.)
1108353358Sdim  for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1109353358Sdim    config->undefined.push_back(arg->getValue());
1110341825Sdim
1111353358Sdim  for (auto *arg : args.filtered(OPT_version_script))
1112353358Sdim    if (Optional<std::string> path = searchScript(arg->getValue())) {
1113353358Sdim      if (Optional<MemoryBufferRef> buffer = readFile(*path))
1114353358Sdim        readVersionScript(*buffer);
1115341825Sdim    } else {
1116353358Sdim      error(Twine("cannot find version script ") + arg->getValue());
1117341825Sdim    }
1118293846Sdim}
1119292934Sdim
1120321369Sdim// Some Config members do not directly correspond to any particular
1121321369Sdim// command line options, but computed based on other Config values.
1122321369Sdim// This function initialize such members. See Config.h for the details
1123321369Sdim// of these values.
1124353358Sdimstatic void setConfigs(opt::InputArgList &args) {
1125353358Sdim  ELFKind k = config->ekind;
1126353358Sdim  uint16_t m = config->emachine;
1127321369Sdim
1128353358Sdim  config->copyRelocs = (config->relocatable || config->emitRelocs);
1129353358Sdim  config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1130353358Sdim  config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1131353358Sdim  config->endianness = config->isLE ? endianness::little : endianness::big;
1132353358Sdim  config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1133353358Sdim  config->isPic = config->pie || config->shared;
1134353358Sdim  config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1135353358Sdim  config->wordsize = config->is64 ? 8 : 4;
1136341825Sdim
1137341825Sdim  // ELF defines two different ways to store relocation addends as shown below:
1138341825Sdim  //
1139341825Sdim  //  Rel:  Addends are stored to the location where relocations are applied.
1140341825Sdim  //  Rela: Addends are stored as part of relocation entry.
1141341825Sdim  //
1142341825Sdim  // In other words, Rela makes it easy to read addends at the price of extra
1143341825Sdim  // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1144341825Sdim  // different mechanisms in the first place, but this is how the spec is
1145341825Sdim  // defined.
1146341825Sdim  //
1147341825Sdim  // You cannot choose which one, Rel or Rela, you want to use. Instead each
1148341825Sdim  // ABI defines which one you need to use. The following expression expresses
1149341825Sdim  // that.
1150353358Sdim  config->isRela = m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON ||
1151353358Sdim                   m == EM_PPC || m == EM_PPC64 || m == EM_RISCV ||
1152353358Sdim                   m == EM_X86_64;
1153341825Sdim
1154341825Sdim  // If the output uses REL relocations we must store the dynamic relocation
1155341825Sdim  // addends to the output sections. We also store addends for RELA relocations
1156341825Sdim  // if --apply-dynamic-relocs is used.
1157341825Sdim  // We default to not writing the addends when using RELA relocations since
1158341825Sdim  // any standard conforming tool can find it in r_addend.
1159353358Sdim  config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1160341825Sdim                                      OPT_no_apply_dynamic_relocs, false) ||
1161353358Sdim                         !config->isRela;
1162344779Sdim
1163353358Sdim  config->tocOptimize =
1164353358Sdim      args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1165321369Sdim}
1166321369Sdim
1167314564Sdim// Returns a value of "-format" option.
1168353358Sdimstatic bool isFormatBinary(StringRef s) {
1169353358Sdim  if (s == "binary")
1170314564Sdim    return true;
1171353358Sdim  if (s == "elf" || s == "default")
1172314564Sdim    return false;
1173353358Sdim  error("unknown -format value: " + s +
1174314564Sdim        " (supported formats: elf, default, binary)");
1175314564Sdim  return false;
1176314564Sdim}
1177314564Sdim
1178353358Sdimvoid LinkerDriver::createFiles(opt::InputArgList &args) {
1179341825Sdim  // For --{push,pop}-state.
1180353358Sdim  std::vector<std::tuple<bool, bool, bool>> stack;
1181341825Sdim
1182341825Sdim  // Iterate over argv to process input files and positional arguments.
1183353358Sdim  for (auto *arg : args) {
1184353358Sdim    switch (arg->getOption().getID()) {
1185327952Sdim    case OPT_library:
1186353358Sdim      addLibrary(arg->getValue());
1187292934Sdim      break;
1188292934Sdim    case OPT_INPUT:
1189353358Sdim      addFile(arg->getValue(), /*withLOption=*/false);
1190292934Sdim      break;
1191341825Sdim    case OPT_defsym: {
1192353358Sdim      StringRef from;
1193353358Sdim      StringRef to;
1194353358Sdim      std::tie(from, to) = StringRef(arg->getValue()).split('=');
1195353358Sdim      if (from.empty() || to.empty())
1196353358Sdim        error("-defsym: syntax error: " + StringRef(arg->getValue()));
1197344779Sdim      else
1198353358Sdim        readDefsym(from, MemoryBufferRef(to, "-defsym"));
1199341825Sdim      break;
1200341825Sdim    }
1201314564Sdim    case OPT_script:
1202353358Sdim      if (Optional<std::string> path = searchScript(arg->getValue())) {
1203353358Sdim        if (Optional<MemoryBufferRef> mb = readFile(*path))
1204353358Sdim          readLinkerScript(*mb);
1205327952Sdim        break;
1206327952Sdim      }
1207353358Sdim      error(Twine("cannot find linker script ") + arg->getValue());
1208314564Sdim      break;
1209292934Sdim    case OPT_as_needed:
1210353358Sdim      config->asNeeded = true;
1211292934Sdim      break;
1212314564Sdim    case OPT_format:
1213353358Sdim      config->formatBinary = isFormatBinary(arg->getValue());
1214314564Sdim      break;
1215292934Sdim    case OPT_no_as_needed:
1216353358Sdim      config->asNeeded = false;
1217292934Sdim      break;
1218292934Sdim    case OPT_Bstatic:
1219353358Sdim    case OPT_omagic:
1220353358Sdim    case OPT_nmagic:
1221353358Sdim      config->isStatic = true;
1222292934Sdim      break;
1223292934Sdim    case OPT_Bdynamic:
1224353358Sdim      config->isStatic = false;
1225292934Sdim      break;
1226292934Sdim    case OPT_whole_archive:
1227353358Sdim      inWholeArchive = true;
1228292934Sdim      break;
1229292934Sdim    case OPT_no_whole_archive:
1230353358Sdim      inWholeArchive = false;
1231292934Sdim      break;
1232341825Sdim    case OPT_just_symbols:
1233353358Sdim      if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1234353358Sdim        files.push_back(createObjectFile(*mb));
1235353358Sdim        files.back()->justSymbols = true;
1236341825Sdim      }
1237341825Sdim      break;
1238341825Sdim    case OPT_start_group:
1239353358Sdim      if (InputFile::isInGroup)
1240341825Sdim        error("nested --start-group");
1241353358Sdim      InputFile::isInGroup = true;
1242341825Sdim      break;
1243341825Sdim    case OPT_end_group:
1244353358Sdim      if (!InputFile::isInGroup)
1245341825Sdim        error("stray --end-group");
1246353358Sdim      InputFile::isInGroup = false;
1247353358Sdim      ++InputFile::nextGroupId;
1248341825Sdim      break;
1249303239Sdim    case OPT_start_lib:
1250353358Sdim      if (inLib)
1251341825Sdim        error("nested --start-lib");
1252353358Sdim      if (InputFile::isInGroup)
1253341825Sdim        error("may not nest --start-lib in --start-group");
1254353358Sdim      inLib = true;
1255353358Sdim      InputFile::isInGroup = true;
1256303239Sdim      break;
1257303239Sdim    case OPT_end_lib:
1258353358Sdim      if (!inLib)
1259341825Sdim        error("stray --end-lib");
1260353358Sdim      inLib = false;
1261353358Sdim      InputFile::isInGroup = false;
1262353358Sdim      ++InputFile::nextGroupId;
1263303239Sdim      break;
1264341825Sdim    case OPT_push_state:
1265353358Sdim      stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1266341825Sdim      break;
1267341825Sdim    case OPT_pop_state:
1268353358Sdim      if (stack.empty()) {
1269341825Sdim        error("unbalanced --push-state/--pop-state");
1270341825Sdim        break;
1271341825Sdim      }
1272353358Sdim      std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1273353358Sdim      stack.pop_back();
1274341825Sdim      break;
1275292934Sdim    }
1276292934Sdim  }
1277292934Sdim
1278353358Sdim  if (files.empty() && errorCount() == 0)
1279314564Sdim    error("no input files");
1280314564Sdim}
1281303239Sdim
1282314564Sdim// If -m <machine_type> was not given, infer it from object files.
1283314564Sdimvoid LinkerDriver::inferMachineType() {
1284353358Sdim  if (config->ekind != ELFNoneKind)
1285314564Sdim    return;
1286314564Sdim
1287353358Sdim  for (InputFile *f : files) {
1288353358Sdim    if (f->ekind == ELFNoneKind)
1289314564Sdim      continue;
1290353358Sdim    config->ekind = f->ekind;
1291353358Sdim    config->emachine = f->emachine;
1292353358Sdim    config->osabi = f->osabi;
1293353358Sdim    config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1294314564Sdim    return;
1295303239Sdim  }
1296314564Sdim  error("target emulation unknown: -m or at least one .o file required");
1297292934Sdim}
1298292934Sdim
1299314564Sdim// Parse -z max-page-size=<value>. The default value is defined by
1300314564Sdim// each target.
1301353358Sdimstatic uint64_t getMaxPageSize(opt::InputArgList &args) {
1302353358Sdim  uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1303353358Sdim                                       target->defaultMaxPageSize);
1304353358Sdim  if (!isPowerOf2_64(val))
1305314564Sdim    error("max-page-size: value isn't a power of 2");
1306353358Sdim  if (config->nmagic || config->omagic) {
1307353358Sdim    if (val != target->defaultMaxPageSize)
1308353358Sdim      warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1309353358Sdim    return 1;
1310353358Sdim  }
1311353358Sdim  return val;
1312314564Sdim}
1313314564Sdim
1314353358Sdim// Parse -z common-page-size=<value>. The default value is defined by
1315353358Sdim// each target.
1316353358Sdimstatic uint64_t getCommonPageSize(opt::InputArgList &args) {
1317353358Sdim  uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1318353358Sdim                                       target->defaultCommonPageSize);
1319353358Sdim  if (!isPowerOf2_64(val))
1320353358Sdim    error("common-page-size: value isn't a power of 2");
1321353358Sdim  if (config->nmagic || config->omagic) {
1322353358Sdim    if (val != target->defaultCommonPageSize)
1323353358Sdim      warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1324353358Sdim    return 1;
1325353358Sdim  }
1326353358Sdim  // commonPageSize can't be larger than maxPageSize.
1327353358Sdim  if (val > config->maxPageSize)
1328353358Sdim    val = config->maxPageSize;
1329353358Sdim  return val;
1330353358Sdim}
1331353358Sdim
1332314564Sdim// Parses -image-base option.
1333353358Sdimstatic Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1334353358Sdim  // Because we are using "Config->maxPageSize" here, this function has to be
1335327952Sdim  // called after the variable is initialized.
1336353358Sdim  auto *arg = args.getLastArg(OPT_image_base);
1337353358Sdim  if (!arg)
1338327952Sdim    return None;
1339314564Sdim
1340353358Sdim  StringRef s = arg->getValue();
1341353358Sdim  uint64_t v;
1342353358Sdim  if (!to_integer(s, v)) {
1343353358Sdim    error("-image-base: number expected, but got " + s);
1344314564Sdim    return 0;
1345314564Sdim  }
1346353358Sdim  if ((v % config->maxPageSize) != 0)
1347353358Sdim    warn("-image-base: address isn't multiple of page size: " + s);
1348353358Sdim  return v;
1349314564Sdim}
1350314564Sdim
1351321369Sdim// Parses `--exclude-libs=lib,lib,...`.
1352321369Sdim// The library names may be delimited by commas or colons.
1353353358Sdimstatic DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1354353358Sdim  DenseSet<StringRef> ret;
1355353358Sdim  for (auto *arg : args.filtered(OPT_exclude_libs)) {
1356353358Sdim    StringRef s = arg->getValue();
1357321369Sdim    for (;;) {
1358353358Sdim      size_t pos = s.find_first_of(",:");
1359353358Sdim      if (pos == StringRef::npos)
1360321369Sdim        break;
1361353358Sdim      ret.insert(s.substr(0, pos));
1362353358Sdim      s = s.substr(pos + 1);
1363321369Sdim    }
1364353358Sdim    ret.insert(s);
1365321369Sdim  }
1366353358Sdim  return ret;
1367321369Sdim}
1368321369Sdim
1369321369Sdim// Handles the -exclude-libs option. If a static library file is specified
1370321369Sdim// by the -exclude-libs option, all public symbols from the archive become
1371321369Sdim// private unless otherwise specified by version scripts or something.
1372321369Sdim// A special library name "ALL" means all archive files.
1373321369Sdim//
1374321369Sdim// This is not a popular option, but some programs such as bionic libc use it.
1375353358Sdimstatic void excludeLibs(opt::InputArgList &args) {
1376353358Sdim  DenseSet<StringRef> libs = getExcludeLibs(args);
1377353358Sdim  bool all = libs.count("ALL");
1378321369Sdim
1379353358Sdim  auto visit = [&](InputFile *file) {
1380353358Sdim    if (!file->archiveName.empty())
1381353358Sdim      if (all || libs.count(path::filename(file->archiveName)))
1382353358Sdim        for (Symbol *sym : file->getSymbols())
1383360784Sdim          if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
1384353358Sdim            sym->versionId = VER_NDX_LOCAL;
1385341825Sdim  };
1386341825Sdim
1387353358Sdim  for (InputFile *file : objectFiles)
1388353358Sdim    visit(file);
1389341825Sdim
1390353358Sdim  for (BitcodeFile *file : bitcodeFiles)
1391353358Sdim    visit(file);
1392321369Sdim}
1393321369Sdim
1394341825Sdim// Force Sym to be entered in the output. Used for -u or equivalent.
1395353358Sdimstatic void handleUndefined(Symbol *sym) {
1396353358Sdim  // Since a symbol may not be used inside the program, LTO may
1397353358Sdim  // eliminate it. Mark the symbol as "used" to prevent it.
1398353358Sdim  sym->isUsedInRegularObj = true;
1399353358Sdim
1400353358Sdim  if (sym->isLazy())
1401353358Sdim    sym->fetch();
1402353358Sdim}
1403353358Sdim
1404360784Sdim// As an extension to GNU linkers, lld supports a variant of `-u`
1405353358Sdim// which accepts wildcard patterns. All symbols that match a given
1406353358Sdim// pattern are handled as if they were given by `-u`.
1407353358Sdimstatic void handleUndefinedGlob(StringRef arg) {
1408353358Sdim  Expected<GlobPattern> pat = GlobPattern::create(arg);
1409353358Sdim  if (!pat) {
1410353358Sdim    error("--undefined-glob: " + toString(pat.takeError()));
1411341825Sdim    return;
1412353358Sdim  }
1413341825Sdim
1414353358Sdim  std::vector<Symbol *> syms;
1415360784Sdim  for (Symbol *sym : symtab->symbols()) {
1416353358Sdim    // Calling Sym->fetch() from here is not safe because it may
1417353358Sdim    // add new symbols to the symbol table, invalidating the
1418353358Sdim    // current iterator. So we just keep a note.
1419353358Sdim    if (pat->match(sym->getName()))
1420353358Sdim      syms.push_back(sym);
1421360784Sdim  }
1422341825Sdim
1423353358Sdim  for (Symbol *sym : syms)
1424353358Sdim    handleUndefined(sym);
1425341825Sdim}
1426341825Sdim
1427353358Sdimstatic void handleLibcall(StringRef name) {
1428353358Sdim  Symbol *sym = symtab->find(name);
1429353358Sdim  if (!sym || !sym->isLazy())
1430344779Sdim    return;
1431341825Sdim
1432353358Sdim  MemoryBufferRef mb;
1433353358Sdim  if (auto *lo = dyn_cast<LazyObject>(sym))
1434353358Sdim    mb = lo->file->mb;
1435344779Sdim  else
1436353358Sdim    mb = cast<LazyArchive>(sym)->getMemberBuffer();
1437344779Sdim
1438353358Sdim  if (isBitcode(mb))
1439353358Sdim    sym->fetch();
1440341825Sdim}
1441341825Sdim
1442353358Sdim// Replaces common symbols with defined symbols reside in .bss sections.
1443353358Sdim// This function is called after all symbol names are resolved. As a
1444353358Sdim// result, the passes after the symbol resolution won't see any
1445353358Sdim// symbols of type CommonSymbol.
1446353358Sdimstatic void replaceCommonSymbols() {
1447360784Sdim  for (Symbol *sym : symtab->symbols()) {
1448353358Sdim    auto *s = dyn_cast<CommonSymbol>(sym);
1449353358Sdim    if (!s)
1450360784Sdim      continue;
1451353358Sdim
1452353358Sdim    auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1453353358Sdim    bss->file = s->file;
1454353358Sdim    bss->markDead();
1455353358Sdim    inputSections.push_back(bss);
1456353358Sdim    s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1457353358Sdim                       /*value=*/0, s->size, bss});
1458360784Sdim  }
1459353358Sdim}
1460353358Sdim
1461344779Sdim// If all references to a DSO happen to be weak, the DSO is not added
1462344779Sdim// to DT_NEEDED. If that happens, we need to eliminate shared symbols
1463344779Sdim// created from the DSO. Otherwise, they become dangling references
1464344779Sdim// that point to a non-existent DSO.
1465353358Sdimstatic void demoteSharedSymbols() {
1466360784Sdim  for (Symbol *sym : symtab->symbols()) {
1467353358Sdim    auto *s = dyn_cast<SharedSymbol>(sym);
1468353358Sdim    if (!s || s->getFile().isNeeded)
1469360784Sdim      continue;
1470353358Sdim
1471353358Sdim    bool used = s->used;
1472353358Sdim    s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1473353358Sdim    s->used = used;
1474360784Sdim  }
1475341825Sdim}
1476341825Sdim
1477353358Sdim// The section referred to by `s` is considered address-significant. Set the
1478353358Sdim// keepUnique flag on the section if appropriate.
1479353358Sdimstatic void markAddrsig(Symbol *s) {
1480353358Sdim  if (auto *d = dyn_cast_or_null<Defined>(s))
1481353358Sdim    if (d->section)
1482341825Sdim      // We don't need to keep text sections unique under --icf=all even if they
1483341825Sdim      // are address-significant.
1484353358Sdim      if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1485353358Sdim        d->section->keepUnique = true;
1486341825Sdim}
1487341825Sdim
1488341825Sdim// Record sections that define symbols mentioned in --keep-unique <symbol>
1489341825Sdim// and symbols referred to by address-significance tables. These sections are
1490341825Sdim// ineligible for ICF.
1491341825Sdimtemplate <class ELFT>
1492353358Sdimstatic void findKeepUniqueSections(opt::InputArgList &args) {
1493353358Sdim  for (auto *arg : args.filtered(OPT_keep_unique)) {
1494353358Sdim    StringRef name = arg->getValue();
1495353358Sdim    auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1496353358Sdim    if (!d || !d->section) {
1497353358Sdim      warn("could not find symbol " + name + " to keep unique");
1498341825Sdim      continue;
1499341825Sdim    }
1500353358Sdim    d->section->keepUnique = true;
1501341825Sdim  }
1502341825Sdim
1503341825Sdim  // --icf=all --ignore-data-address-equality means that we can ignore
1504341825Sdim  // the dynsym and address-significance tables entirely.
1505353358Sdim  if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1506341825Sdim    return;
1507341825Sdim
1508341825Sdim  // Symbols in the dynsym could be address-significant in other executables
1509341825Sdim  // or DSOs, so we conservatively mark them as address-significant.
1510360784Sdim  for (Symbol *sym : symtab->symbols())
1511353358Sdim    if (sym->includeInDynsym())
1512353358Sdim      markAddrsig(sym);
1513341825Sdim
1514341825Sdim  // Visit the address-significance table in each object file and mark each
1515341825Sdim  // referenced symbol as address-significant.
1516353358Sdim  for (InputFile *f : objectFiles) {
1517353358Sdim    auto *obj = cast<ObjFile<ELFT>>(f);
1518353358Sdim    ArrayRef<Symbol *> syms = obj->getSymbols();
1519353358Sdim    if (obj->addrsigSec) {
1520353358Sdim      ArrayRef<uint8_t> contents =
1521353358Sdim          check(obj->getObj().getSectionContents(obj->addrsigSec));
1522353358Sdim      const uint8_t *cur = contents.begin();
1523353358Sdim      while (cur != contents.end()) {
1524353358Sdim        unsigned size;
1525353358Sdim        const char *err;
1526353358Sdim        uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1527353358Sdim        if (err)
1528353358Sdim          fatal(toString(f) + ": could not decode addrsig section: " + err);
1529353358Sdim        markAddrsig(syms[symIndex]);
1530353358Sdim        cur += size;
1531341825Sdim      }
1532341825Sdim    } else {
1533341825Sdim      // If an object file does not have an address-significance table,
1534341825Sdim      // conservatively mark all of its symbols as address-significant.
1535353358Sdim      for (Symbol *s : syms)
1536353358Sdim        markAddrsig(s);
1537341825Sdim    }
1538341825Sdim  }
1539341825Sdim}
1540341825Sdim
1541353358Sdim// This function reads a symbol partition specification section. These sections
1542353358Sdim// are used to control which partition a symbol is allocated to. See
1543353358Sdim// https://lld.llvm.org/Partitions.html for more details on partitions.
1544353358Sdimtemplate <typename ELFT>
1545353358Sdimstatic void readSymbolPartitionSection(InputSectionBase *s) {
1546353358Sdim  // Read the relocation that refers to the partition's entry point symbol.
1547353358Sdim  Symbol *sym;
1548353358Sdim  if (s->areRelocsRela)
1549353358Sdim    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1550353358Sdim  else
1551353358Sdim    sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1552353358Sdim  if (!isa<Defined>(sym) || !sym->includeInDynsym())
1553353358Sdim    return;
1554353358Sdim
1555353358Sdim  StringRef partName = reinterpret_cast<const char *>(s->data().data());
1556353358Sdim  for (Partition &part : partitions) {
1557353358Sdim    if (part.name == partName) {
1558353358Sdim      sym->partition = part.getNumber();
1559353358Sdim      return;
1560353358Sdim    }
1561353358Sdim  }
1562353358Sdim
1563353358Sdim  // Forbid partitions from being used on incompatible targets, and forbid them
1564353358Sdim  // from being used together with various linker features that assume a single
1565353358Sdim  // set of output sections.
1566353358Sdim  if (script->hasSectionsCommand)
1567353358Sdim    error(toString(s->file) +
1568353358Sdim          ": partitions cannot be used with the SECTIONS command");
1569353358Sdim  if (script->hasPhdrsCommands())
1570353358Sdim    error(toString(s->file) +
1571353358Sdim          ": partitions cannot be used with the PHDRS command");
1572353358Sdim  if (!config->sectionStartMap.empty())
1573353358Sdim    error(toString(s->file) + ": partitions cannot be used with "
1574353358Sdim                              "--section-start, -Ttext, -Tdata or -Tbss");
1575353358Sdim  if (config->emachine == EM_MIPS)
1576353358Sdim    error(toString(s->file) + ": partitions cannot be used on this target");
1577353358Sdim
1578353358Sdim  // Impose a limit of no more than 254 partitions. This limit comes from the
1579353358Sdim  // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1580353358Sdim  // the amount of space devoted to the partition number in RankFlags.
1581353358Sdim  if (partitions.size() == 254)
1582353358Sdim    fatal("may not have more than 254 partitions");
1583353358Sdim
1584353358Sdim  partitions.emplace_back();
1585353358Sdim  Partition &newPart = partitions.back();
1586353358Sdim  newPart.name = partName;
1587353358Sdim  sym->partition = newPart.getNumber();
1588344779Sdim}
1589344779Sdim
1590353358Sdimstatic Symbol *addUndefined(StringRef name) {
1591353358Sdim  return symtab->addSymbol(
1592353358Sdim      Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1593353358Sdim}
1594353358Sdim
1595353358Sdim// This function is where all the optimizations of link-time
1596353358Sdim// optimization takes place. When LTO is in use, some input files are
1597353358Sdim// not in native object file format but in the LLVM bitcode format.
1598353358Sdim// This function compiles bitcode files into a few big native files
1599353358Sdim// using LLVM functions and replaces bitcode symbols with the results.
1600353358Sdim// Because all bitcode files that the program consists of are passed to
1601353358Sdim// the compiler at once, it can do a whole-program optimization.
1602353358Sdimtemplate <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1603353358Sdim  // Compile bitcode files and replace bitcode symbols.
1604353358Sdim  lto.reset(new BitcodeCompiler);
1605353358Sdim  for (BitcodeFile *file : bitcodeFiles)
1606353358Sdim    lto->add(*file);
1607353358Sdim
1608353358Sdim  for (InputFile *file : lto->compile()) {
1609353358Sdim    auto *obj = cast<ObjFile<ELFT>>(file);
1610353358Sdim    obj->parse(/*ignoreComdats=*/true);
1611353358Sdim    for (Symbol *sym : obj->getGlobalSymbols())
1612353358Sdim      sym->parseSymbolVersion();
1613353358Sdim    objectFiles.push_back(file);
1614353358Sdim  }
1615353358Sdim}
1616353358Sdim
1617344779Sdim// The --wrap option is a feature to rename symbols so that you can write
1618344779Sdim// wrappers for existing functions. If you pass `-wrap=foo`, all
1619344779Sdim// occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1620344779Sdim// expected to write `wrap_foo` function as a wrapper). The original
1621344779Sdim// symbol becomes accessible as `real_foo`, so you can call that from your
1622344779Sdim// wrapper.
1623344779Sdim//
1624344779Sdim// This data structure is instantiated for each -wrap option.
1625344779Sdimstruct WrappedSymbol {
1626353358Sdim  Symbol *sym;
1627353358Sdim  Symbol *real;
1628353358Sdim  Symbol *wrap;
1629344779Sdim};
1630344779Sdim
1631344779Sdim// Handles -wrap option.
1632344779Sdim//
1633344779Sdim// This function instantiates wrapper symbols. At this point, they seem
1634344779Sdim// like they are not being used at all, so we explicitly set some flags so
1635344779Sdim// that LTO won't eliminate them.
1636353358Sdimstatic std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1637353358Sdim  std::vector<WrappedSymbol> v;
1638353358Sdim  DenseSet<StringRef> seen;
1639344779Sdim
1640353358Sdim  for (auto *arg : args.filtered(OPT_wrap)) {
1641353358Sdim    StringRef name = arg->getValue();
1642353358Sdim    if (!seen.insert(name).second)
1643344779Sdim      continue;
1644344779Sdim
1645353358Sdim    Symbol *sym = symtab->find(name);
1646353358Sdim    if (!sym)
1647344779Sdim      continue;
1648344779Sdim
1649353358Sdim    Symbol *real = addUndefined(saver.save("__real_" + name));
1650353358Sdim    Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
1651353358Sdim    v.push_back({sym, real, wrap});
1652344779Sdim
1653344779Sdim    // We want to tell LTO not to inline symbols to be overwritten
1654344779Sdim    // because LTO doesn't know the final symbol contents after renaming.
1655353358Sdim    real->canInline = false;
1656353358Sdim    sym->canInline = false;
1657344779Sdim
1658344779Sdim    // Tell LTO not to eliminate these symbols.
1659353358Sdim    sym->isUsedInRegularObj = true;
1660353358Sdim    wrap->isUsedInRegularObj = true;
1661344779Sdim  }
1662353358Sdim  return v;
1663344779Sdim}
1664344779Sdim
1665344779Sdim// Do renaming for -wrap by updating pointers to symbols.
1666344779Sdim//
1667344779Sdim// When this function is executed, only InputFiles and symbol table
1668344779Sdim// contain pointers to symbol objects. We visit them to replace pointers,
1669344779Sdim// so that wrapped symbols are swapped as instructed by the command line.
1670353358Sdimstatic void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1671353358Sdim  DenseMap<Symbol *, Symbol *> map;
1672353358Sdim  for (const WrappedSymbol &w : wrapped) {
1673353358Sdim    map[w.sym] = w.wrap;
1674353358Sdim    map[w.real] = w.sym;
1675344779Sdim  }
1676344779Sdim
1677344779Sdim  // Update pointers in input files.
1678353358Sdim  parallelForEach(objectFiles, [&](InputFile *file) {
1679353358Sdim    MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1680353358Sdim    for (size_t i = 0, e = syms.size(); i != e; ++i)
1681353358Sdim      if (Symbol *s = map.lookup(syms[i]))
1682353358Sdim        syms[i] = s;
1683344779Sdim  });
1684344779Sdim
1685344779Sdim  // Update pointers in the symbol table.
1686353358Sdim  for (const WrappedSymbol &w : wrapped)
1687353358Sdim    symtab->wrap(w.sym, w.real, w.wrap);
1688344779Sdim}
1689344779Sdim
1690353358Sdim// To enable CET (x86's hardware-assited control flow enforcement), each
1691353358Sdim// source file must be compiled with -fcf-protection. Object files compiled
1692353358Sdim// with the flag contain feature flags indicating that they are compatible
1693353358Sdim// with CET. We enable the feature only when all object files are compatible
1694353358Sdim// with CET.
1695353358Sdim//
1696353358Sdim// This is also the case with AARCH64's BTI and PAC which use the similar
1697353358Sdim// GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
1698353358Sdimtemplate <class ELFT> static uint32_t getAndFeatures() {
1699353358Sdim  if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1700353358Sdim      config->emachine != EM_AARCH64)
1701353358Sdim    return 0;
1702353358Sdim
1703353358Sdim  uint32_t ret = -1;
1704353358Sdim  for (InputFile *f : objectFiles) {
1705353358Sdim    uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1706353358Sdim    if (config->forceBTI && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1707360784Sdim      warn(toString(f) + ": -z force-bti: file does not have BTI property");
1708353358Sdim      features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1709360784Sdim    } else if (config->zForceIbt &&
1710360784Sdim               !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
1711360784Sdim      warn(toString(f) + ": -z force-ibt: file does not have "
1712360784Sdim                         "GNU_PROPERTY_X86_FEATURE_1_IBT property");
1713360784Sdim      features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
1714360784Sdim    }
1715353358Sdim    ret &= features;
1716353358Sdim  }
1717353358Sdim
1718353358Sdim  // Force enable pointer authentication Plt, we don't warn in this case as
1719353358Sdim  // this does not require support in the object for correctness.
1720353358Sdim  if (config->pacPlt)
1721353358Sdim    ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1722360784Sdim  // Force enable Shadow Stack.
1723360784Sdim  if (config->zShstk)
1724360784Sdim    ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
1725353358Sdim
1726353358Sdim  return ret;
1727353358Sdim}
1728353358Sdim
1729303239Sdim// Do actual linking. Note that when this function is called,
1730303239Sdim// all linker scripts have already been parsed.
1731353358Sdimtemplate <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1732327952Sdim  // If a -hash-style option was not given, set to a default value,
1733327952Sdim  // which varies depending on the target.
1734353358Sdim  if (!args.hasArg(OPT_hash_style)) {
1735353358Sdim    if (config->emachine == EM_MIPS)
1736353358Sdim      config->sysvHash = true;
1737327952Sdim    else
1738353358Sdim      config->sysvHash = config->gnuHash = true;
1739327952Sdim  }
1740327952Sdim
1741303239Sdim  // Default output filename is "a.out" by the Unix tradition.
1742353358Sdim  if (config->outputFile.empty())
1743353358Sdim    config->outputFile = "a.out";
1744303239Sdim
1745321369Sdim  // Fail early if the output file or map file is not writable. If a user has a
1746321369Sdim  // long link, e.g. due to a large LTO link, they do not wish to run it and
1747321369Sdim  // find that it failed because there was a mistake in their command-line.
1748353358Sdim  if (auto e = tryCreateFile(config->outputFile))
1749353358Sdim    error("cannot open output file " + config->outputFile + ": " + e.message());
1750353358Sdim  if (auto e = tryCreateFile(config->mapFile))
1751353358Sdim    error("cannot open map file " + config->mapFile + ": " + e.message());
1752327952Sdim  if (errorCount())
1753321369Sdim    return;
1754321369Sdim
1755314564Sdim  // Use default entry point name if no name was given via the command
1756314564Sdim  // line nor linker scripts. For some reason, MIPS entry point name is
1757314564Sdim  // different from others.
1758353358Sdim  config->warnMissingEntry =
1759353358Sdim      (!config->entry.empty() || (!config->shared && !config->relocatable));
1760353358Sdim  if (config->entry.empty() && !config->relocatable)
1761353358Sdim    config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
1762314564Sdim
1763303239Sdim  // Handle --trace-symbol.
1764353358Sdim  for (auto *arg : args.filtered(OPT_trace_symbol))
1765353358Sdim    symtab->insert(arg->getValue())->traced = true;
1766303239Sdim
1767314564Sdim  // Add all files to the symbol table. This will add almost all
1768353358Sdim  // symbols that we need to the symbol table. This process might
1769353358Sdim  // add files to the link, via autolinking, these files are always
1770353358Sdim  // appended to the Files vector.
1771353358Sdim  for (size_t i = 0; i < files.size(); ++i)
1772353358Sdim    parseFile(files[i]);
1773292934Sdim
1774327952Sdim  // Now that we have every file, we can decide if we will need a
1775327952Sdim  // dynamic symbol table.
1776327952Sdim  // We need one if we were asked to export dynamic symbols or if we are
1777327952Sdim  // producing a shared library.
1778327952Sdim  // We also need one if any shared libraries are used and for pie executables
1779327952Sdim  // (probably because the dynamic linker needs it).
1780353358Sdim  config->hasDynSymTab =
1781353358Sdim      !sharedFiles.empty() || config->isPic || config->exportDynamic;
1782327952Sdim
1783327952Sdim  // Some symbols (such as __ehdr_start) are defined lazily only when there
1784327952Sdim  // are undefined symbols for them, so we add these to trigger that logic.
1785353358Sdim  for (StringRef name : script->referencedSymbols)
1786353358Sdim    addUndefined(name);
1787327952Sdim
1788327952Sdim  // Handle the `--undefined <sym>` options.
1789353358Sdim  for (StringRef arg : config->undefined)
1790353358Sdim    if (Symbol *sym = symtab->find(arg))
1791353358Sdim      handleUndefined(sym);
1792327952Sdim
1793341825Sdim  // If an entry symbol is in a static archive, pull out that file now.
1794353358Sdim  if (Symbol *sym = symtab->find(config->entry))
1795353358Sdim    handleUndefined(sym);
1796292934Sdim
1797353358Sdim  // Handle the `--undefined-glob <pattern>` options.
1798353358Sdim  for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1799353358Sdim    handleUndefinedGlob(pat);
1800353358Sdim
1801360784Sdim  // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
1802360784Sdim  if (Symbol *sym = symtab->find(config->init))
1803360784Sdim    sym->isUsedInRegularObj = true;
1804360784Sdim  if (Symbol *sym = symtab->find(config->fini))
1805360784Sdim    sym->isUsedInRegularObj = true;
1806360784Sdim
1807341825Sdim  // If any of our inputs are bitcode files, the LTO code generator may create
1808341825Sdim  // references to certain library functions that might not be explicit in the
1809341825Sdim  // bitcode file's symbol table. If any of those library functions are defined
1810341825Sdim  // in a bitcode file in an archive member, we need to arrange to use LTO to
1811341825Sdim  // compile those archive members by adding them to the link beforehand.
1812341825Sdim  //
1813344779Sdim  // However, adding all libcall symbols to the link can have undesired
1814344779Sdim  // consequences. For example, the libgcc implementation of
1815344779Sdim  // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1816344779Sdim  // that aborts the program if the Linux kernel does not support 64-bit
1817344779Sdim  // atomics, which would prevent the program from running even if it does not
1818344779Sdim  // use 64-bit atomics.
1819344779Sdim  //
1820344779Sdim  // Therefore, we only add libcall symbols to the link before LTO if we have
1821344779Sdim  // to, i.e. if the symbol's definition is in bitcode. Any other required
1822344779Sdim  // libcall symbols will be added to the link after LTO when we add the LTO
1823344779Sdim  // object file to the link.
1824353358Sdim  if (!bitcodeFiles.empty())
1825360784Sdim    for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1826353358Sdim      handleLibcall(s);
1827341825Sdim
1828314564Sdim  // Return if there were name resolution errors.
1829327952Sdim  if (errorCount())
1830314564Sdim    return;
1831292934Sdim
1832341825Sdim  // Now when we read all script files, we want to finalize order of linker
1833341825Sdim  // script commands, which can be not yet final because of INSERT commands.
1834353358Sdim  script->processInsertCommands();
1835321369Sdim
1836341825Sdim  // We want to declare linker script's symbols early,
1837341825Sdim  // so that we can version them.
1838341825Sdim  // They also might be exported if referenced by DSOs.
1839353358Sdim  script->declareSymbols();
1840341825Sdim
1841321369Sdim  // Handle the -exclude-libs option.
1842353358Sdim  if (args.hasArg(OPT_exclude_libs))
1843353358Sdim    excludeLibs(args);
1844321369Sdim
1845353358Sdim  // Create elfHeader early. We need a dummy section in
1846326831Sdim  // addReservedSymbols to mark the created symbols as not absolute.
1847353358Sdim  Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1848353358Sdim  Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1849326831Sdim
1850344779Sdim  // Create wrapped symbols for -wrap option.
1851353358Sdim  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1852344779Sdim
1853326831Sdim  // We need to create some reserved symbols such as _end. Create them.
1854353358Sdim  if (!config->relocatable)
1855327952Sdim    addReservedSymbols();
1856326831Sdim
1857321369Sdim  // Apply version scripts.
1858329983Sdim  //
1859329983Sdim  // For a relocatable output, version scripts don't make sense, and
1860329983Sdim  // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1861329983Sdim  // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1862353358Sdim  if (!config->relocatable)
1863353358Sdim    symtab->scanVersionScript();
1864292934Sdim
1865341825Sdim  // Do link-time optimization if given files are LLVM bitcode files.
1866341825Sdim  // This compiles bitcode files into real object files.
1867344779Sdim  //
1868344779Sdim  // With this the symbol table should be complete. After this, no new names
1869344779Sdim  // except a few linker-synthesized ones will be added to the symbol table.
1870353358Sdim  compileBitcodeFiles<ELFT>();
1871327952Sdim  if (errorCount())
1872303239Sdim    return;
1873303239Sdim
1874341825Sdim  // If -thinlto-index-only is given, we should create only "index
1875341825Sdim  // files" and not object files. Index file creation is already done
1876341825Sdim  // in addCombinedLTOObject, so we are done if that's the case.
1877353358Sdim  if (config->thinLTOIndexOnly)
1878341825Sdim    return;
1879341825Sdim
1880344779Sdim  // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1881344779Sdim  // an output file in bitcode and exit, so that you can just get a
1882344779Sdim  // combined bitcode file.
1883353358Sdim  if (config->emitLLVM)
1884344779Sdim    return;
1885344779Sdim
1886327952Sdim  // Apply symbol renames for -wrap.
1887353358Sdim  if (!wrapped.empty())
1888353358Sdim    wrapSymbols(wrapped);
1889293846Sdim
1890314564Sdim  // Now that we have a complete list of input files.
1891314564Sdim  // Beyond this point, no new files are added.
1892314564Sdim  // Aggregate all input sections into one place.
1893353358Sdim  for (InputFile *f : objectFiles)
1894353358Sdim    for (InputSectionBase *s : f->getSections())
1895353358Sdim      if (s && s != &InputSection::discarded)
1896353358Sdim        inputSections.push_back(s);
1897353358Sdim  for (BinaryFile *f : binaryFiles)
1898353358Sdim    for (InputSectionBase *s : f->getSections())
1899353358Sdim      inputSections.push_back(cast<InputSection>(s));
1900314564Sdim
1901353358Sdim  llvm::erase_if(inputSections, [](InputSectionBase *s) {
1902353358Sdim    if (s->type == SHT_LLVM_SYMPART) {
1903353358Sdim      readSymbolPartitionSection<ELFT>(s);
1904353358Sdim      return true;
1905353358Sdim    }
1906327952Sdim
1907353358Sdim    // We do not want to emit debug sections if --strip-all
1908353358Sdim    // or -strip-debug are given.
1909363496Sdim    if (config->strip == StripPolicy::None)
1910363496Sdim      return false;
1911363496Sdim
1912363496Sdim    if (isDebugSection(*s))
1913363496Sdim      return true;
1914363496Sdim    if (auto *isec = dyn_cast<InputSection>(s))
1915363496Sdim      if (InputSectionBase *rel = isec->getRelocatedSection())
1916363496Sdim        if (isDebugSection(*rel))
1917363496Sdim          return true;
1918363496Sdim
1919363496Sdim    return false;
1920353358Sdim  });
1921327952Sdim
1922353358Sdim  // Now that the number of partitions is fixed, save a pointer to the main
1923353358Sdim  // partition.
1924353358Sdim  mainPart = &partitions[0];
1925353358Sdim
1926353358Sdim  // Read .note.gnu.property sections from input object files which
1927353358Sdim  // contain a hint to tweak linker's and loader's behaviors.
1928353358Sdim  config->andFeatures = getAndFeatures<ELFT>();
1929353358Sdim
1930353358Sdim  // The Target instance handles target-specific stuff, such as applying
1931353358Sdim  // relocations or writing a PLT section. It also contains target-dependent
1932353358Sdim  // values such as a default image base address.
1933353358Sdim  target = getTarget();
1934353358Sdim
1935353358Sdim  config->eflags = target->calcEFlags();
1936353358Sdim  // maxPageSize (sometimes called abi page size) is the maximum page size that
1937353358Sdim  // the output can be run on. For example if the OS can use 4k or 64k page
1938353358Sdim  // sizes then maxPageSize must be 64k for the output to be useable on both.
1939353358Sdim  // All important alignment decisions must use this value.
1940353358Sdim  config->maxPageSize = getMaxPageSize(args);
1941353358Sdim  // commonPageSize is the most common page size that the output will be run on.
1942353358Sdim  // For example if an OS can use 4k or 64k page sizes and 4k is more common
1943353358Sdim  // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1944353358Sdim  // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1945353358Sdim  // is limited to writing trap instructions on the last executable segment.
1946353358Sdim  config->commonPageSize = getCommonPageSize(args);
1947353358Sdim
1948353358Sdim  config->imageBase = getImageBase(args);
1949353358Sdim
1950353358Sdim  if (config->emachine == EM_ARM) {
1951327952Sdim    // FIXME: These warnings can be removed when lld only uses these features
1952327952Sdim    // when the input objects have been compiled with an architecture that
1953327952Sdim    // supports them.
1954353358Sdim    if (config->armHasBlx == false)
1955327952Sdim      warn("lld uses blx instruction, no object with architecture supporting "
1956344779Sdim           "feature detected");
1957327952Sdim  }
1958327952Sdim
1959360784Sdim  // This adds a .comment section containing a version string.
1960353358Sdim  if (!config->relocatable)
1961353358Sdim    inputSections.push_back(createCommentSection());
1962321369Sdim
1963353358Sdim  // Replace common symbols with regular symbols.
1964353358Sdim  replaceCommonSymbols();
1965353358Sdim
1966360784Sdim  // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
1967341825Sdim  splitSections<ELFT>();
1968360784Sdim
1969360784Sdim  // Garbage collection and removal of shared symbols from unused shared objects.
1970327952Sdim  markLive<ELFT>();
1971353358Sdim  demoteSharedSymbols();
1972360784Sdim
1973360784Sdim  // Make copies of any input sections that need to be copied into each
1974360784Sdim  // partition.
1975360784Sdim  copySectionsIntoPartitions();
1976360784Sdim
1977360784Sdim  // Create synthesized sections such as .got and .plt. This is called before
1978360784Sdim  // processSectionCommands() so that they can be placed by SECTIONS commands.
1979360784Sdim  createSyntheticSections<ELFT>();
1980360784Sdim
1981360784Sdim  // Some input sections that are used for exception handling need to be moved
1982360784Sdim  // into synthetic sections. Do that now so that they aren't assigned to
1983360784Sdim  // output sections in the usual way.
1984360784Sdim  if (!config->relocatable)
1985360784Sdim    combineEhSections();
1986360784Sdim
1987360784Sdim  // Create output sections described by SECTIONS commands.
1988360784Sdim  script->processSectionCommands();
1989360784Sdim
1990360784Sdim  // Linker scripts control how input sections are assigned to output sections.
1991360784Sdim  // Input sections that were not handled by scripts are called "orphans", and
1992360784Sdim  // they are assigned to output sections by the default rule. Process that.
1993360784Sdim  script->addOrphanSections();
1994360784Sdim
1995360784Sdim  // Migrate InputSectionDescription::sectionBases to sections. This includes
1996360784Sdim  // merging MergeInputSections into a single MergeSyntheticSection. From this
1997360784Sdim  // point onwards InputSectionDescription::sections should be used instead of
1998360784Sdim  // sectionBases.
1999360784Sdim  for (BaseCommand *base : script->sectionCommands)
2000360784Sdim    if (auto *sec = dyn_cast<OutputSection>(base))
2001360784Sdim      sec->finalizeInputSections();
2002360784Sdim  llvm::erase_if(inputSections,
2003360784Sdim                 [](InputSectionBase *s) { return isa<MergeInputSection>(s); });
2004360784Sdim
2005360784Sdim  // Two input sections with different output sections should not be folded.
2006360784Sdim  // ICF runs after processSectionCommands() so that we know the output sections.
2007353358Sdim  if (config->icf != ICFLevel::None) {
2008353358Sdim    findKeepUniqueSections<ELFT>(args);
2009303239Sdim    doIcf<ELFT>();
2010341825Sdim  }
2011303239Sdim
2012341825Sdim  // Read the callgraph now that we know what was gced or icfed
2013353358Sdim  if (config->callGraphProfileSort) {
2014353358Sdim    if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2015353358Sdim      if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2016353358Sdim        readCallGraph(*buffer);
2017344779Sdim    readCallGraphsFromObjectFiles<ELFT>();
2018344779Sdim  }
2019341825Sdim
2020314564Sdim  // Write the result to the file.
2021314564Sdim  writeResult<ELFT>();
2022292934Sdim}
2023360784Sdim
2024360784Sdim} // namespace elf
2025360784Sdim} // namespace lld
2026