1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The driver drives the entire linking process. It is responsible for
10 // parsing command line options and doing whatever it is instructed to do.
11 //
12 // One notable thing in the LLD's driver when compared to other linkers is
13 // that the LLD's driver is agnostic on the host operating system.
14 // Other linkers usually have implicit default values (such as a dynamic
15 // linker path or library paths) for each host OS.
16 //
17 // I don't think implicit default values are useful because they are
18 // usually explicitly specified by the compiler driver. They can even
19 // be harmful when you are doing cross-linking. Therefore, in LLD, we
20 // simply trust the compiler driver to pass all required options and
21 // don't try to make effort on our side.
22 //
23 //===----------------------------------------------------------------------===//
24
25 #include "Driver.h"
26 #include "Config.h"
27 #include "ICF.h"
28 #include "InputFiles.h"
29 #include "InputSection.h"
30 #include "LinkerScript.h"
31 #include "MarkLive.h"
32 #include "OutputSections.h"
33 #include "ScriptParser.h"
34 #include "SymbolTable.h"
35 #include "Symbols.h"
36 #include "SyntheticSections.h"
37 #include "Target.h"
38 #include "Writer.h"
39 #include "lld/Common/Args.h"
40 #include "lld/Common/Driver.h"
41 #include "lld/Common/ErrorHandler.h"
42 #include "lld/Common/Filesystem.h"
43 #include "lld/Common/Memory.h"
44 #include "lld/Common/Strings.h"
45 #include "lld/Common/TargetOptionsCommandFlags.h"
46 #include "lld/Common/Version.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/ADT/StringSwitch.h"
50 #include "llvm/LTO/LTO.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compression.h"
53 #include "llvm/Support/GlobPattern.h"
54 #include "llvm/Support/LEB128.h"
55 #include "llvm/Support/Parallel.h"
56 #include "llvm/Support/Path.h"
57 #include "llvm/Support/TarWriter.h"
58 #include "llvm/Support/TargetSelect.h"
59 #include "llvm/Support/TimeProfiler.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <cstdlib>
62 #include <utility>
63
64 using namespace llvm;
65 using namespace llvm::ELF;
66 using namespace llvm::object;
67 using namespace llvm::sys;
68 using namespace llvm::support;
69 using namespace lld;
70 using namespace lld::elf;
71
72 Configuration *elf::config;
73 LinkerDriver *elf::driver;
74
75 static void setConfigs(opt::InputArgList &args);
76 static void readConfigs(opt::InputArgList &args);
77
link(ArrayRef<const char * > args,bool canExitEarly,raw_ostream & stdoutOS,raw_ostream & stderrOS)78 bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
79 raw_ostream &stdoutOS, raw_ostream &stderrOS) {
80 lld::stdoutOS = &stdoutOS;
81 lld::stderrOS = &stderrOS;
82
83 errorHandler().cleanupCallback = []() {
84 freeArena();
85
86 inputSections.clear();
87 outputSections.clear();
88 archiveFiles.clear();
89 binaryFiles.clear();
90 bitcodeFiles.clear();
91 lazyObjFiles.clear();
92 objectFiles.clear();
93 sharedFiles.clear();
94 backwardReferences.clear();
95
96 tar = nullptr;
97 memset(&in, 0, sizeof(in));
98
99 partitions = {Partition()};
100
101 SharedFile::vernauxNum = 0;
102 };
103
104 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
105 errorHandler().errorLimitExceededMsg =
106 "too many errors emitted, stopping now (use "
107 "-error-limit=0 to see all errors)";
108 errorHandler().exitEarly = canExitEarly;
109 stderrOS.enable_colors(stderrOS.has_colors());
110
111 config = make<Configuration>();
112 driver = make<LinkerDriver>();
113 script = make<LinkerScript>();
114 symtab = make<SymbolTable>();
115
116 partitions = {Partition()};
117
118 config->progName = args[0];
119
120 driver->main(args);
121
122 // Exit immediately if we don't need to return to the caller.
123 // This saves time because the overhead of calling destructors
124 // for all globally-allocated objects is not negligible.
125 if (canExitEarly)
126 exitLld(errorCount() ? 1 : 0);
127
128 bool ret = errorCount() == 0;
129 if (!canExitEarly)
130 errorHandler().reset();
131 return ret;
132 }
133
134 // Parses a linker -m option.
parseEmulation(StringRef emul)135 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
136 uint8_t osabi = 0;
137 StringRef s = emul;
138 if (s.endswith("_fbsd")) {
139 s = s.drop_back(5);
140 osabi = ELFOSABI_FREEBSD;
141 }
142
143 std::pair<ELFKind, uint16_t> ret =
144 StringSwitch<std::pair<ELFKind, uint16_t>>(s)
145 .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
146 {ELF64LEKind, EM_AARCH64})
147 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
148 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
149 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
150 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
151 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
152 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
153 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
154 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
155 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
156 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
157 .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
158 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
159 .Case("elf_i386", {ELF32LEKind, EM_386})
160 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
161 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
162 .Default({ELFNoneKind, EM_NONE});
163
164 if (ret.first == ELFNoneKind)
165 error("unknown emulation: " + emul);
166 return std::make_tuple(ret.first, ret.second, osabi);
167 }
168
169 // Returns slices of MB by parsing MB as an archive file.
170 // Each slice consists of a member file in the archive.
getArchiveMembers(MemoryBufferRef mb)171 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
172 MemoryBufferRef mb) {
173 std::unique_ptr<Archive> file =
174 CHECK(Archive::create(mb),
175 mb.getBufferIdentifier() + ": failed to parse archive");
176
177 std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
178 Error err = Error::success();
179 bool addToTar = file->isThin() && tar;
180 for (const Archive::Child &c : file->children(err)) {
181 MemoryBufferRef mbref =
182 CHECK(c.getMemoryBufferRef(),
183 mb.getBufferIdentifier() +
184 ": could not get the buffer for a child of the archive");
185 if (addToTar)
186 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
187 v.push_back(std::make_pair(mbref, c.getChildOffset()));
188 }
189 if (err)
190 fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
191 toString(std::move(err)));
192
193 // Take ownership of memory buffers created for members of thin archives.
194 for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
195 make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
196
197 return v;
198 }
199
200 // Opens a file and create a file object. Path has to be resolved already.
addFile(StringRef path,bool withLOption)201 void LinkerDriver::addFile(StringRef path, bool withLOption) {
202 using namespace sys::fs;
203
204 Optional<MemoryBufferRef> buffer = readFile(path);
205 if (!buffer.hasValue())
206 return;
207 MemoryBufferRef mbref = *buffer;
208
209 if (config->formatBinary) {
210 files.push_back(make<BinaryFile>(mbref));
211 return;
212 }
213
214 switch (identify_magic(mbref.getBuffer())) {
215 case file_magic::unknown:
216 readLinkerScript(mbref);
217 return;
218 case file_magic::archive: {
219 // Handle -whole-archive.
220 if (inWholeArchive) {
221 for (const auto &p : getArchiveMembers(mbref))
222 files.push_back(createObjectFile(p.first, path, p.second));
223 return;
224 }
225
226 std::unique_ptr<Archive> file =
227 CHECK(Archive::create(mbref), path + ": failed to parse archive");
228
229 // If an archive file has no symbol table, it is likely that a user
230 // is attempting LTO and using a default ar command that doesn't
231 // understand the LLVM bitcode file. It is a pretty common error, so
232 // we'll handle it as if it had a symbol table.
233 if (!file->isEmpty() && !file->hasSymbolTable()) {
234 // Check if all members are bitcode files. If not, ignore, which is the
235 // default action without the LTO hack described above.
236 for (const std::pair<MemoryBufferRef, uint64_t> &p :
237 getArchiveMembers(mbref))
238 if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
239 error(path + ": archive has no index; run ranlib to add one");
240 return;
241 }
242
243 for (const std::pair<MemoryBufferRef, uint64_t> &p :
244 getArchiveMembers(mbref))
245 files.push_back(make<LazyObjFile>(p.first, path, p.second));
246 return;
247 }
248
249 // Handle the regular case.
250 files.push_back(make<ArchiveFile>(std::move(file)));
251 return;
252 }
253 case file_magic::elf_shared_object:
254 if (config->isStatic || config->relocatable) {
255 error("attempted static link of dynamic object " + path);
256 return;
257 }
258
259 // DSOs usually have DT_SONAME tags in their ELF headers, and the
260 // sonames are used to identify DSOs. But if they are missing,
261 // they are identified by filenames. We don't know whether the new
262 // file has a DT_SONAME or not because we haven't parsed it yet.
263 // Here, we set the default soname for the file because we might
264 // need it later.
265 //
266 // If a file was specified by -lfoo, the directory part is not
267 // significant, as a user did not specify it. This behavior is
268 // compatible with GNU.
269 files.push_back(
270 make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
271 return;
272 case file_magic::bitcode:
273 case file_magic::elf_relocatable:
274 if (inLib)
275 files.push_back(make<LazyObjFile>(mbref, "", 0));
276 else
277 files.push_back(createObjectFile(mbref));
278 break;
279 default:
280 error(path + ": unknown file type");
281 }
282 }
283
284 // Add a given library by searching it from input search paths.
addLibrary(StringRef name)285 void LinkerDriver::addLibrary(StringRef name) {
286 if (Optional<std::string> path = searchLibrary(name))
287 addFile(*path, /*withLOption=*/true);
288 else
289 error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
290 }
291
292 // This function is called on startup. We need this for LTO since
293 // LTO calls LLVM functions to compile bitcode files to native code.
294 // Technically this can be delayed until we read bitcode files, but
295 // we don't bother to do lazily because the initialization is fast.
initLLVM()296 static void initLLVM() {
297 InitializeAllTargets();
298 InitializeAllTargetMCs();
299 InitializeAllAsmPrinters();
300 InitializeAllAsmParsers();
301 }
302
303 // Some command line options or some combinations of them are not allowed.
304 // This function checks for such errors.
checkOptions()305 static void checkOptions() {
306 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
307 // table which is a relatively new feature.
308 if (config->emachine == EM_MIPS && config->gnuHash)
309 error("the .gnu.hash section is not compatible with the MIPS target");
310
311 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
312 error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
313
314 if (config->fixCortexA8 && config->emachine != EM_ARM)
315 error("--fix-cortex-a8 is only supported on ARM targets");
316
317 if (config->tocOptimize && config->emachine != EM_PPC64)
318 error("--toc-optimize is only supported on the PowerPC64 target");
319
320 if (config->pcRelOptimize && config->emachine != EM_PPC64)
321 error("--pcrel--optimize is only supported on the PowerPC64 target");
322
323 if (config->pie && config->shared)
324 error("-shared and -pie may not be used together");
325
326 if (!config->shared && !config->filterList.empty())
327 error("-F may not be used without -shared");
328
329 if (!config->shared && !config->auxiliaryList.empty())
330 error("-f may not be used without -shared");
331
332 if (!config->relocatable && !config->defineCommon)
333 error("-no-define-common not supported in non relocatable output");
334
335 if (config->strip == StripPolicy::All && config->emitRelocs)
336 error("--strip-all and --emit-relocs may not be used together");
337
338 if (config->zText && config->zIfuncNoplt)
339 error("-z text and -z ifunc-noplt may not be used together");
340
341 if (config->relocatable) {
342 if (config->shared)
343 error("-r and -shared may not be used together");
344 if (config->gdbIndex)
345 error("-r and --gdb-index may not be used together");
346 if (config->icf != ICFLevel::None)
347 error("-r and --icf may not be used together");
348 if (config->pie)
349 error("-r and -pie may not be used together");
350 if (config->exportDynamic)
351 error("-r and --export-dynamic may not be used together");
352 }
353
354 if (config->executeOnly) {
355 if (config->emachine != EM_AARCH64)
356 error("-execute-only is only supported on AArch64 targets");
357
358 if (config->singleRoRx && !script->hasSectionsCommand)
359 error("-execute-only and -no-rosegment cannot be used together");
360 }
361
362 if (config->zRetpolineplt && config->zForceIbt)
363 error("-z force-ibt may not be used with -z retpolineplt");
364
365 if (config->emachine != EM_AARCH64) {
366 if (config->zPacPlt)
367 error("-z pac-plt only supported on AArch64");
368 if (config->zForceBti)
369 error("-z force-bti only supported on AArch64");
370 }
371 }
372
getReproduceOption(opt::InputArgList & args)373 static const char *getReproduceOption(opt::InputArgList &args) {
374 if (auto *arg = args.getLastArg(OPT_reproduce))
375 return arg->getValue();
376 return getenv("LLD_REPRODUCE");
377 }
378
hasZOption(opt::InputArgList & args,StringRef key)379 static bool hasZOption(opt::InputArgList &args, StringRef key) {
380 for (auto *arg : args.filtered(OPT_z))
381 if (key == arg->getValue())
382 return true;
383 return false;
384 }
385
getZFlag(opt::InputArgList & args,StringRef k1,StringRef k2,bool Default)386 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
387 bool Default) {
388 for (auto *arg : args.filtered_reverse(OPT_z)) {
389 if (k1 == arg->getValue())
390 return true;
391 if (k2 == arg->getValue())
392 return false;
393 }
394 return Default;
395 }
396
getZSeparate(opt::InputArgList & args)397 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
398 for (auto *arg : args.filtered_reverse(OPT_z)) {
399 StringRef v = arg->getValue();
400 if (v == "noseparate-code")
401 return SeparateSegmentKind::None;
402 if (v == "separate-code")
403 return SeparateSegmentKind::Code;
404 if (v == "separate-loadable-segments")
405 return SeparateSegmentKind::Loadable;
406 }
407 return SeparateSegmentKind::None;
408 }
409
getZGnuStack(opt::InputArgList & args)410 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
411 for (auto *arg : args.filtered_reverse(OPT_z)) {
412 if (StringRef("execstack") == arg->getValue())
413 return GnuStackKind::Exec;
414 if (StringRef("noexecstack") == arg->getValue())
415 return GnuStackKind::NoExec;
416 if (StringRef("nognustack") == arg->getValue())
417 return GnuStackKind::None;
418 }
419
420 return GnuStackKind::NoExec;
421 }
422
getZStartStopVisibility(opt::InputArgList & args)423 static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
424 for (auto *arg : args.filtered_reverse(OPT_z)) {
425 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
426 if (kv.first == "start-stop-visibility") {
427 if (kv.second == "default")
428 return STV_DEFAULT;
429 else if (kv.second == "internal")
430 return STV_INTERNAL;
431 else if (kv.second == "hidden")
432 return STV_HIDDEN;
433 else if (kv.second == "protected")
434 return STV_PROTECTED;
435 error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
436 }
437 }
438 return STV_PROTECTED;
439 }
440
isKnownZFlag(StringRef s)441 static bool isKnownZFlag(StringRef s) {
442 return s == "combreloc" || s == "copyreloc" || s == "defs" ||
443 s == "execstack" || s == "force-bti" || s == "force-ibt" ||
444 s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
445 s == "initfirst" || s == "interpose" ||
446 s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
447 s == "separate-code" || s == "separate-loadable-segments" ||
448 s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" ||
449 s == "nodelete" || s == "nodlopen" || s == "noexecstack" ||
450 s == "nognustack" || s == "nokeep-text-section-prefix" ||
451 s == "norelro" || s == "noseparate-code" || s == "notext" ||
452 s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
453 s == "rela" || s == "relro" || s == "retpolineplt" ||
454 s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
455 s == "wxneeded" || s.startswith("common-page-size=") ||
456 s.startswith("dead-reloc-in-nonalloc=") ||
457 s.startswith("max-page-size=") || s.startswith("stack-size=") ||
458 s.startswith("start-stop-visibility=");
459 }
460
461 // Report an error for an unknown -z option.
checkZOptions(opt::InputArgList & args)462 static void checkZOptions(opt::InputArgList &args) {
463 for (auto *arg : args.filtered(OPT_z))
464 if (!isKnownZFlag(arg->getValue()))
465 error("unknown -z value: " + StringRef(arg->getValue()));
466 }
467
main(ArrayRef<const char * > argsArr)468 void LinkerDriver::main(ArrayRef<const char *> argsArr) {
469 ELFOptTable parser;
470 opt::InputArgList args = parser.parse(argsArr.slice(1));
471
472 // Interpret this flag early because error() depends on them.
473 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
474 checkZOptions(args);
475
476 // Handle -help
477 if (args.hasArg(OPT_help)) {
478 printHelp();
479 return;
480 }
481
482 // Handle -v or -version.
483 //
484 // A note about "compatible with GNU linkers" message: this is a hack for
485 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
486 // still the newest version in March 2017) or earlier to recognize LLD as
487 // a GNU compatible linker. As long as an output for the -v option
488 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
489 //
490 // This is somewhat ugly hack, but in reality, we had no choice other
491 // than doing this. Considering the very long release cycle of Libtool,
492 // it is not easy to improve it to recognize LLD as a GNU compatible
493 // linker in a timely manner. Even if we can make it, there are still a
494 // lot of "configure" scripts out there that are generated by old version
495 // of Libtool. We cannot convince every software developer to migrate to
496 // the latest version and re-generate scripts. So we have this hack.
497 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
498 message(getLLDVersion() + " (compatible with GNU linkers)");
499
500 if (const char *path = getReproduceOption(args)) {
501 // Note that --reproduce is a debug option so you can ignore it
502 // if you are trying to understand the whole picture of the code.
503 Expected<std::unique_ptr<TarWriter>> errOrWriter =
504 TarWriter::create(path, path::stem(path));
505 if (errOrWriter) {
506 tar = std::move(*errOrWriter);
507 tar->append("response.txt", createResponseFile(args));
508 tar->append("version.txt", getLLDVersion() + "\n");
509 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
510 if (!ltoSampleProfile.empty())
511 readFile(ltoSampleProfile);
512 } else {
513 error("--reproduce: " + toString(errOrWriter.takeError()));
514 }
515 }
516
517 readConfigs(args);
518
519 // The behavior of -v or --version is a bit strange, but this is
520 // needed for compatibility with GNU linkers.
521 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
522 return;
523 if (args.hasArg(OPT_version))
524 return;
525
526 // Initialize time trace profiler.
527 if (config->timeTraceEnabled)
528 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
529
530 {
531 llvm::TimeTraceScope timeScope("ExecuteLinker");
532
533 initLLVM();
534 createFiles(args);
535 if (errorCount())
536 return;
537
538 inferMachineType();
539 setConfigs(args);
540 checkOptions();
541 if (errorCount())
542 return;
543
544 // The Target instance handles target-specific stuff, such as applying
545 // relocations or writing a PLT section. It also contains target-dependent
546 // values such as a default image base address.
547 target = getTarget();
548
549 switch (config->ekind) {
550 case ELF32LEKind:
551 link<ELF32LE>(args);
552 break;
553 case ELF32BEKind:
554 link<ELF32BE>(args);
555 break;
556 case ELF64LEKind:
557 link<ELF64LE>(args);
558 break;
559 case ELF64BEKind:
560 link<ELF64BE>(args);
561 break;
562 default:
563 llvm_unreachable("unknown Config->EKind");
564 }
565 }
566
567 if (config->timeTraceEnabled) {
568 if (auto E = timeTraceProfilerWrite(args.getLastArgValue(OPT_time_trace_file_eq).str(),
569 config->outputFile)) {
570 handleAllErrors(std::move(E), [&](const StringError &SE) {
571 error(SE.getMessage());
572 });
573 return;
574 }
575
576 timeTraceProfilerCleanup();
577 }
578 }
579
getRpath(opt::InputArgList & args)580 static std::string getRpath(opt::InputArgList &args) {
581 std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
582 return llvm::join(v.begin(), v.end(), ":");
583 }
584
585 // Determines what we should do if there are remaining unresolved
586 // symbols after the name resolution.
getUnresolvedSymbolPolicy(opt::InputArgList & args)587 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
588 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
589 OPT_warn_unresolved_symbols, true)
590 ? UnresolvedPolicy::ReportError
591 : UnresolvedPolicy::Warn;
592
593 // Process the last of -unresolved-symbols, -no-undefined or -z defs.
594 for (auto *arg : llvm::reverse(args)) {
595 switch (arg->getOption().getID()) {
596 case OPT_unresolved_symbols: {
597 StringRef s = arg->getValue();
598 if (s == "ignore-all" || s == "ignore-in-object-files")
599 return UnresolvedPolicy::Ignore;
600 if (s == "ignore-in-shared-libs" || s == "report-all")
601 return errorOrWarn;
602 error("unknown --unresolved-symbols value: " + s);
603 continue;
604 }
605 case OPT_no_undefined:
606 return errorOrWarn;
607 case OPT_z:
608 if (StringRef(arg->getValue()) == "defs")
609 return errorOrWarn;
610 if (StringRef(arg->getValue()) == "undefs")
611 return UnresolvedPolicy::Ignore;
612 continue;
613 }
614 }
615
616 // -shared implies -unresolved-symbols=ignore-all because missing
617 // symbols are likely to be resolved at runtime using other DSOs.
618 if (config->shared)
619 return UnresolvedPolicy::Ignore;
620 return errorOrWarn;
621 }
622
getTarget2(opt::InputArgList & args)623 static Target2Policy getTarget2(opt::InputArgList &args) {
624 StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
625 if (s == "rel")
626 return Target2Policy::Rel;
627 if (s == "abs")
628 return Target2Policy::Abs;
629 if (s == "got-rel")
630 return Target2Policy::GotRel;
631 error("unknown --target2 option: " + s);
632 return Target2Policy::GotRel;
633 }
634
isOutputFormatBinary(opt::InputArgList & args)635 static bool isOutputFormatBinary(opt::InputArgList &args) {
636 StringRef s = args.getLastArgValue(OPT_oformat, "elf");
637 if (s == "binary")
638 return true;
639 if (!s.startswith("elf"))
640 error("unknown --oformat value: " + s);
641 return false;
642 }
643
getDiscard(opt::InputArgList & args)644 static DiscardPolicy getDiscard(opt::InputArgList &args) {
645 auto *arg =
646 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
647 if (!arg)
648 return DiscardPolicy::Default;
649 if (arg->getOption().getID() == OPT_discard_all)
650 return DiscardPolicy::All;
651 if (arg->getOption().getID() == OPT_discard_locals)
652 return DiscardPolicy::Locals;
653 return DiscardPolicy::None;
654 }
655
getDynamicLinker(opt::InputArgList & args)656 static StringRef getDynamicLinker(opt::InputArgList &args) {
657 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
658 if (!arg)
659 return "";
660 if (arg->getOption().getID() == OPT_no_dynamic_linker) {
661 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
662 config->noDynamicLinker = true;
663 return "";
664 }
665 return arg->getValue();
666 }
667
getICF(opt::InputArgList & args)668 static ICFLevel getICF(opt::InputArgList &args) {
669 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
670 if (!arg || arg->getOption().getID() == OPT_icf_none)
671 return ICFLevel::None;
672 if (arg->getOption().getID() == OPT_icf_safe)
673 return ICFLevel::Safe;
674 return ICFLevel::All;
675 }
676
getStrip(opt::InputArgList & args)677 static StripPolicy getStrip(opt::InputArgList &args) {
678 if (args.hasArg(OPT_relocatable))
679 return StripPolicy::None;
680
681 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
682 if (!arg)
683 return StripPolicy::None;
684 if (arg->getOption().getID() == OPT_strip_all)
685 return StripPolicy::All;
686 return StripPolicy::Debug;
687 }
688
parseSectionAddress(StringRef s,opt::InputArgList & args,const opt::Arg & arg)689 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
690 const opt::Arg &arg) {
691 uint64_t va = 0;
692 if (s.startswith("0x"))
693 s = s.drop_front(2);
694 if (!to_integer(s, va, 16))
695 error("invalid argument: " + arg.getAsString(args));
696 return va;
697 }
698
getSectionStartMap(opt::InputArgList & args)699 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
700 StringMap<uint64_t> ret;
701 for (auto *arg : args.filtered(OPT_section_start)) {
702 StringRef name;
703 StringRef addr;
704 std::tie(name, addr) = StringRef(arg->getValue()).split('=');
705 ret[name] = parseSectionAddress(addr, args, *arg);
706 }
707
708 if (auto *arg = args.getLastArg(OPT_Ttext))
709 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
710 if (auto *arg = args.getLastArg(OPT_Tdata))
711 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
712 if (auto *arg = args.getLastArg(OPT_Tbss))
713 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
714 return ret;
715 }
716
getSortSection(opt::InputArgList & args)717 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
718 StringRef s = args.getLastArgValue(OPT_sort_section);
719 if (s == "alignment")
720 return SortSectionPolicy::Alignment;
721 if (s == "name")
722 return SortSectionPolicy::Name;
723 if (!s.empty())
724 error("unknown --sort-section rule: " + s);
725 return SortSectionPolicy::Default;
726 }
727
getOrphanHandling(opt::InputArgList & args)728 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
729 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
730 if (s == "warn")
731 return OrphanHandlingPolicy::Warn;
732 if (s == "error")
733 return OrphanHandlingPolicy::Error;
734 if (s != "place")
735 error("unknown --orphan-handling mode: " + s);
736 return OrphanHandlingPolicy::Place;
737 }
738
739 // Parse --build-id or --build-id=<style>. We handle "tree" as a
740 // synonym for "sha1" because all our hash functions including
741 // -build-id=sha1 are actually tree hashes for performance reasons.
742 static std::pair<BuildIdKind, std::vector<uint8_t>>
getBuildId(opt::InputArgList & args)743 getBuildId(opt::InputArgList &args) {
744 auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
745 if (!arg)
746 return {BuildIdKind::None, {}};
747
748 if (arg->getOption().getID() == OPT_build_id)
749 return {BuildIdKind::Fast, {}};
750
751 StringRef s = arg->getValue();
752 if (s == "fast")
753 return {BuildIdKind::Fast, {}};
754 if (s == "md5")
755 return {BuildIdKind::Md5, {}};
756 if (s == "sha1" || s == "tree")
757 return {BuildIdKind::Sha1, {}};
758 if (s == "uuid")
759 return {BuildIdKind::Uuid, {}};
760 if (s.startswith("0x"))
761 return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
762
763 if (s != "none")
764 error("unknown --build-id style: " + s);
765 return {BuildIdKind::None, {}};
766 }
767
getPackDynRelocs(opt::InputArgList & args)768 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
769 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
770 if (s == "android")
771 return {true, false};
772 if (s == "relr")
773 return {false, true};
774 if (s == "android+relr")
775 return {true, true};
776
777 if (s != "none")
778 error("unknown -pack-dyn-relocs format: " + s);
779 return {false, false};
780 }
781
readCallGraph(MemoryBufferRef mb)782 static void readCallGraph(MemoryBufferRef mb) {
783 // Build a map from symbol name to section
784 DenseMap<StringRef, Symbol *> map;
785 for (InputFile *file : objectFiles)
786 for (Symbol *sym : file->getSymbols())
787 map[sym->getName()] = sym;
788
789 auto findSection = [&](StringRef name) -> InputSectionBase * {
790 Symbol *sym = map.lookup(name);
791 if (!sym) {
792 if (config->warnSymbolOrdering)
793 warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
794 return nullptr;
795 }
796 maybeWarnUnorderableSymbol(sym);
797
798 if (Defined *dr = dyn_cast_or_null<Defined>(sym))
799 return dyn_cast_or_null<InputSectionBase>(dr->section);
800 return nullptr;
801 };
802
803 for (StringRef line : args::getLines(mb)) {
804 SmallVector<StringRef, 3> fields;
805 line.split(fields, ' ');
806 uint64_t count;
807
808 if (fields.size() != 3 || !to_integer(fields[2], count)) {
809 error(mb.getBufferIdentifier() + ": parse error");
810 return;
811 }
812
813 if (InputSectionBase *from = findSection(fields[0]))
814 if (InputSectionBase *to = findSection(fields[1]))
815 config->callGraphProfile[std::make_pair(from, to)] += count;
816 }
817 }
818
readCallGraphsFromObjectFiles()819 template <class ELFT> static void readCallGraphsFromObjectFiles() {
820 for (auto file : objectFiles) {
821 auto *obj = cast<ObjFile<ELFT>>(file);
822
823 for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
824 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
825 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
826 if (!fromSym || !toSym)
827 continue;
828
829 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
830 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
831 if (from && to)
832 config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
833 }
834 }
835 }
836
getCompressDebugSections(opt::InputArgList & args)837 static bool getCompressDebugSections(opt::InputArgList &args) {
838 StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
839 if (s == "none")
840 return false;
841 if (s != "zlib")
842 error("unknown --compress-debug-sections value: " + s);
843 if (!zlib::isAvailable())
844 error("--compress-debug-sections: zlib is not available");
845 return true;
846 }
847
getAliasSpelling(opt::Arg * arg)848 static StringRef getAliasSpelling(opt::Arg *arg) {
849 if (const opt::Arg *alias = arg->getAlias())
850 return alias->getSpelling();
851 return arg->getSpelling();
852 }
853
getOldNewOptions(opt::InputArgList & args,unsigned id)854 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
855 unsigned id) {
856 auto *arg = args.getLastArg(id);
857 if (!arg)
858 return {"", ""};
859
860 StringRef s = arg->getValue();
861 std::pair<StringRef, StringRef> ret = s.split(';');
862 if (ret.second.empty())
863 error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
864 return ret;
865 }
866
867 // Parse the symbol ordering file and warn for any duplicate entries.
getSymbolOrderingFile(MemoryBufferRef mb)868 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
869 SetVector<StringRef> names;
870 for (StringRef s : args::getLines(mb))
871 if (!names.insert(s) && config->warnSymbolOrdering)
872 warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
873
874 return names.takeVector();
875 }
876
getIsRela(opt::InputArgList & args)877 static bool getIsRela(opt::InputArgList &args) {
878 // If -z rel or -z rela is specified, use the last option.
879 for (auto *arg : args.filtered_reverse(OPT_z)) {
880 StringRef s(arg->getValue());
881 if (s == "rel")
882 return false;
883 if (s == "rela")
884 return true;
885 }
886
887 // Otherwise use the psABI defined relocation entry format.
888 uint16_t m = config->emachine;
889 return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
890 m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
891 }
892
parseClangOption(StringRef opt,const Twine & msg)893 static void parseClangOption(StringRef opt, const Twine &msg) {
894 std::string err;
895 raw_string_ostream os(err);
896
897 const char *argv[] = {config->progName.data(), opt.data()};
898 if (cl::ParseCommandLineOptions(2, argv, "", &os))
899 return;
900 os.flush();
901 error(msg + ": " + StringRef(err).trim());
902 }
903
904 // Initializes Config members by the command line options.
readConfigs(opt::InputArgList & args)905 static void readConfigs(opt::InputArgList &args) {
906 errorHandler().verbose = args.hasArg(OPT_verbose);
907 errorHandler().fatalWarnings =
908 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
909 errorHandler().vsDiagnostics =
910 args.hasArg(OPT_visual_studio_diagnostics_format, false);
911
912 config->allowMultipleDefinition =
913 args.hasFlag(OPT_allow_multiple_definition,
914 OPT_no_allow_multiple_definition, false) ||
915 hasZOption(args, "muldefs");
916 config->allowShlibUndefined =
917 args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
918 args.hasArg(OPT_shared));
919 config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
920 config->bsymbolic = args.hasArg(OPT_Bsymbolic);
921 config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions);
922 config->checkSections =
923 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
924 config->chroot = args.getLastArgValue(OPT_chroot);
925 config->compressDebugSections = getCompressDebugSections(args);
926 config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false);
927 config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
928 !args.hasArg(OPT_relocatable));
929 config->optimizeBBJumps =
930 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
931 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
932 config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
933 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
934 config->disableVerify = args.hasArg(OPT_disable_verify);
935 config->discard = getDiscard(args);
936 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
937 config->dynamicLinker = getDynamicLinker(args);
938 config->ehFrameHdr =
939 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
940 config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
941 config->emitRelocs = args.hasArg(OPT_emit_relocs);
942 config->callGraphProfileSort = args.hasFlag(
943 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
944 config->enableNewDtags =
945 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
946 config->entry = args.getLastArgValue(OPT_entry);
947
948 errorHandler().errorHandlingScript =
949 args.getLastArgValue(OPT_error_handling_script);
950
951 config->executeOnly =
952 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
953 config->exportDynamic =
954 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
955 config->filterList = args::getStrings(args, OPT_filter);
956 config->fini = args.getLastArgValue(OPT_fini, "_fini");
957 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
958 !args.hasArg(OPT_relocatable);
959 config->fixCortexA8 =
960 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
961 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
962 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
963 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
964 config->icf = getICF(args);
965 config->ignoreDataAddressEquality =
966 args.hasArg(OPT_ignore_data_address_equality);
967 config->ignoreFunctionAddressEquality =
968 args.hasArg(OPT_ignore_function_address_equality);
969 config->init = args.getLastArgValue(OPT_init, "_init");
970 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
971 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
972 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
973 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
974 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
975 config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager);
976 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
977 config->ltoWholeProgramVisibility =
978 args.hasArg(OPT_lto_whole_program_visibility);
979 config->ltoo = args::getInteger(args, OPT_lto_O, 2);
980 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
981 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
982 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
983 config->ltoBasicBlockSections =
984 args.getLastArgValue(OPT_lto_basic_block_sections);
985 config->ltoUniqueBasicBlockSectionNames =
986 args.hasFlag(OPT_lto_unique_basic_block_section_names,
987 OPT_no_lto_unique_basic_block_section_names, false);
988 config->mapFile = args.getLastArgValue(OPT_Map);
989 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
990 config->mergeArmExidx =
991 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
992 config->mmapOutputFile =
993 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
994 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
995 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
996 config->nostdlib = args.hasArg(OPT_nostdlib);
997 config->oFormatBinary = isOutputFormatBinary(args);
998 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
999 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1000 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
1001 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
1002 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
1003 config->optimize = args::getInteger(args, OPT_O, 1);
1004 config->orphanHandling = getOrphanHandling(args);
1005 config->outputFile = args.getLastArgValue(OPT_o);
1006 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
1007 config->printIcfSections =
1008 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
1009 config->printGcSections =
1010 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
1011 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1012 config->printSymbolOrder =
1013 args.getLastArgValue(OPT_print_symbol_order);
1014 config->rpath = getRpath(args);
1015 config->relocatable = args.hasArg(OPT_relocatable);
1016 config->saveTemps = args.hasArg(OPT_save_temps);
1017 if (args.hasArg(OPT_shuffle_sections))
1018 config->shuffleSectionSeed = args::getInteger(args, OPT_shuffle_sections, 0);
1019 config->searchPaths = args::getStrings(args, OPT_library_path);
1020 config->sectionStartMap = getSectionStartMap(args);
1021 config->shared = args.hasArg(OPT_shared);
1022 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1023 config->soName = args.getLastArgValue(OPT_soname);
1024 config->sortSection = getSortSection(args);
1025 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1026 config->strip = getStrip(args);
1027 config->sysroot = args.getLastArgValue(OPT_sysroot);
1028 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1029 config->target2 = getTarget2(args);
1030 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1031 config->thinLTOCachePolicy = CHECK(
1032 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1033 "--thinlto-cache-policy: invalid cache policy");
1034 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1035 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1036 args.hasArg(OPT_thinlto_index_only_eq);
1037 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1038 config->thinLTOObjectSuffixReplace =
1039 getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1040 config->thinLTOPrefixReplace =
1041 getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
1042 config->thinLTOModulesToCompile =
1043 args::getStrings(args, OPT_thinlto_single_module_eq);
1044 config->timeTraceEnabled = args.hasArg(OPT_time_trace);
1045 config->timeTraceGranularity =
1046 args::getInteger(args, OPT_time_trace_granularity, 500);
1047 config->trace = args.hasArg(OPT_trace);
1048 config->undefined = args::getStrings(args, OPT_undefined);
1049 config->undefinedVersion =
1050 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
1051 config->unique = args.hasArg(OPT_unique);
1052 config->useAndroidRelrTags = args.hasFlag(
1053 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1054 config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
1055 config->warnBackrefs =
1056 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1057 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1058 config->warnIfuncTextrel =
1059 args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
1060 config->warnSymbolOrdering =
1061 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1062 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1063 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1064 config->zForceBti = hasZOption(args, "force-bti");
1065 config->zForceIbt = hasZOption(args, "force-ibt");
1066 config->zGlobal = hasZOption(args, "global");
1067 config->zGnustack = getZGnuStack(args);
1068 config->zHazardplt = hasZOption(args, "hazardplt");
1069 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1070 config->zInitfirst = hasZOption(args, "initfirst");
1071 config->zInterpose = hasZOption(args, "interpose");
1072 config->zKeepTextSectionPrefix = getZFlag(
1073 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1074 config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1075 config->zNodelete = hasZOption(args, "nodelete");
1076 config->zNodlopen = hasZOption(args, "nodlopen");
1077 config->zNow = getZFlag(args, "now", "lazy", false);
1078 config->zOrigin = hasZOption(args, "origin");
1079 config->zPacPlt = hasZOption(args, "pac-plt");
1080 config->zRelro = getZFlag(args, "relro", "norelro", true);
1081 config->zRetpolineplt = hasZOption(args, "retpolineplt");
1082 config->zRodynamic = hasZOption(args, "rodynamic");
1083 config->zSeparate = getZSeparate(args);
1084 config->zShstk = hasZOption(args, "shstk");
1085 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1086 config->zStartStopVisibility = getZStartStopVisibility(args);
1087 config->zText = getZFlag(args, "text", "notext", true);
1088 config->zWxneeded = hasZOption(args, "wxneeded");
1089
1090 for (opt::Arg *arg : args.filtered(OPT_z)) {
1091 std::pair<StringRef, StringRef> option =
1092 StringRef(arg->getValue()).split('=');
1093 if (option.first != "dead-reloc-in-nonalloc")
1094 continue;
1095 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1096 std::pair<StringRef, StringRef> kv = option.second.split('=');
1097 if (kv.first.empty() || kv.second.empty()) {
1098 error(errPrefix + "expected <section_glob>=<value>");
1099 continue;
1100 }
1101 uint64_t v;
1102 if (!to_integer(kv.second, v))
1103 error(errPrefix + "expected a non-negative integer, but got '" +
1104 kv.second + "'");
1105 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1106 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1107 else
1108 error(errPrefix + toString(pat.takeError()));
1109 }
1110
1111 cl::ResetAllOptionOccurrences();
1112
1113 // Parse LTO options.
1114 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1115 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
1116 arg->getSpelling());
1117
1118 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1119 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1120
1121 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1122 // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
1123 // unsupported LLVMgold.so option and error.
1124 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
1125 if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
1126 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1127 "'");
1128
1129 // Parse -mllvm options.
1130 for (auto *arg : args.filtered(OPT_mllvm))
1131 parseClangOption(arg->getValue(), arg->getSpelling());
1132
1133 // --threads= takes a positive integer and provides the default value for
1134 // --thinlto-jobs=.
1135 if (auto *arg = args.getLastArg(OPT_threads)) {
1136 StringRef v(arg->getValue());
1137 unsigned threads = 0;
1138 if (!llvm::to_integer(v, threads, 0) || threads == 0)
1139 error(arg->getSpelling() + ": expected a positive integer, but got '" +
1140 arg->getValue() + "'");
1141 parallel::strategy = hardware_concurrency(threads);
1142 config->thinLTOJobs = v;
1143 }
1144 if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
1145 config->thinLTOJobs = arg->getValue();
1146
1147 if (config->ltoo > 3)
1148 error("invalid optimization level for LTO: " + Twine(config->ltoo));
1149 if (config->ltoPartitions == 0)
1150 error("--lto-partitions: number of threads must be > 0");
1151 if (!get_threadpool_strategy(config->thinLTOJobs))
1152 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1153
1154 if (config->splitStackAdjustSize < 0)
1155 error("--split-stack-adjust-size: size must be >= 0");
1156
1157 // The text segment is traditionally the first segment, whose address equals
1158 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1159 // is an old-fashioned option that does not play well with lld's layout.
1160 // Suggest --image-base as a likely alternative.
1161 if (args.hasArg(OPT_Ttext_segment))
1162 error("-Ttext-segment is not supported. Use --image-base if you "
1163 "intend to set the base address");
1164
1165 // Parse ELF{32,64}{LE,BE} and CPU type.
1166 if (auto *arg = args.getLastArg(OPT_m)) {
1167 StringRef s = arg->getValue();
1168 std::tie(config->ekind, config->emachine, config->osabi) =
1169 parseEmulation(s);
1170 config->mipsN32Abi =
1171 (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1172 config->emulation = s;
1173 }
1174
1175 // Parse -hash-style={sysv,gnu,both}.
1176 if (auto *arg = args.getLastArg(OPT_hash_style)) {
1177 StringRef s = arg->getValue();
1178 if (s == "sysv")
1179 config->sysvHash = true;
1180 else if (s == "gnu")
1181 config->gnuHash = true;
1182 else if (s == "both")
1183 config->sysvHash = config->gnuHash = true;
1184 else
1185 error("unknown -hash-style: " + s);
1186 }
1187
1188 if (args.hasArg(OPT_print_map))
1189 config->mapFile = "-";
1190
1191 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1192 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1193 // it.
1194 if (config->nmagic || config->omagic)
1195 config->zRelro = false;
1196
1197 std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1198
1199 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1200 getPackDynRelocs(args);
1201
1202 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1203 if (args.hasArg(OPT_call_graph_ordering_file))
1204 error("--symbol-ordering-file and --call-graph-order-file "
1205 "may not be used together");
1206 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1207 config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1208 // Also need to disable CallGraphProfileSort to prevent
1209 // LLD order symbols with CGProfile
1210 config->callGraphProfileSort = false;
1211 }
1212 }
1213
1214 assert(config->versionDefinitions.empty());
1215 config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}});
1216 config->versionDefinitions.push_back(
1217 {"global", (uint16_t)VER_NDX_GLOBAL, {}});
1218
1219 // If --retain-symbol-file is used, we'll keep only the symbols listed in
1220 // the file and discard all others.
1221 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1222 config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(
1223 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1224 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1225 for (StringRef s : args::getLines(*buffer))
1226 config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(
1227 {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1228 }
1229
1230 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1231 StringRef pattern(arg->getValue());
1232 if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1233 config->warnBackrefsExclude.push_back(std::move(*pat));
1234 else
1235 error(arg->getSpelling() + ": " + toString(pat.takeError()));
1236 }
1237
1238 // When producing an executable, --dynamic-list specifies non-local defined
1239 // symbols whith are required to be exported. When producing a shared object,
1240 // symbols not specified by --dynamic-list are non-preemptible.
1241 config->symbolic =
1242 args.hasArg(OPT_Bsymbolic) || args.hasArg(OPT_dynamic_list);
1243 for (auto *arg : args.filtered(OPT_dynamic_list))
1244 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1245 readDynamicList(*buffer);
1246
1247 // --export-dynamic-symbol specifies additional --dynamic-list symbols if any
1248 // other option expresses a symbolic intention: -no-pie, -pie, -Bsymbolic,
1249 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1250 for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1251 config->dynamicList.push_back(
1252 {arg->getValue(), /*isExternCpp=*/false,
1253 /*hasWildcard=*/hasWildcard(arg->getValue())});
1254
1255 for (auto *arg : args.filtered(OPT_version_script))
1256 if (Optional<std::string> path = searchScript(arg->getValue())) {
1257 if (Optional<MemoryBufferRef> buffer = readFile(*path))
1258 readVersionScript(*buffer);
1259 } else {
1260 error(Twine("cannot find version script ") + arg->getValue());
1261 }
1262 }
1263
1264 // Some Config members do not directly correspond to any particular
1265 // command line options, but computed based on other Config values.
1266 // This function initialize such members. See Config.h for the details
1267 // of these values.
setConfigs(opt::InputArgList & args)1268 static void setConfigs(opt::InputArgList &args) {
1269 ELFKind k = config->ekind;
1270 uint16_t m = config->emachine;
1271
1272 config->copyRelocs = (config->relocatable || config->emitRelocs);
1273 config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1274 config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1275 config->endianness = config->isLE ? endianness::little : endianness::big;
1276 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1277 config->isPic = config->pie || config->shared;
1278 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1279 config->wordsize = config->is64 ? 8 : 4;
1280
1281 // ELF defines two different ways to store relocation addends as shown below:
1282 //
1283 // Rel: Addends are stored to the location where relocations are applied. It
1284 // cannot pack the full range of addend values for all relocation types, but
1285 // this only affects relocation types that we don't support emitting as
1286 // dynamic relocations (see getDynRel).
1287 // Rela: Addends are stored as part of relocation entry.
1288 //
1289 // In other words, Rela makes it easy to read addends at the price of extra
1290 // 4 or 8 byte for each relocation entry.
1291 //
1292 // We pick the format for dynamic relocations according to the psABI for each
1293 // processor, but a contrary choice can be made if the dynamic loader
1294 // supports.
1295 config->isRela = getIsRela(args);
1296
1297 // If the output uses REL relocations we must store the dynamic relocation
1298 // addends to the output sections. We also store addends for RELA relocations
1299 // if --apply-dynamic-relocs is used.
1300 // We default to not writing the addends when using RELA relocations since
1301 // any standard conforming tool can find it in r_addend.
1302 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1303 OPT_no_apply_dynamic_relocs, false) ||
1304 !config->isRela;
1305
1306 config->tocOptimize =
1307 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1308 config->pcRelOptimize =
1309 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1310 }
1311
1312 // Returns a value of "-format" option.
isFormatBinary(StringRef s)1313 static bool isFormatBinary(StringRef s) {
1314 if (s == "binary")
1315 return true;
1316 if (s == "elf" || s == "default")
1317 return false;
1318 error("unknown -format value: " + s +
1319 " (supported formats: elf, default, binary)");
1320 return false;
1321 }
1322
createFiles(opt::InputArgList & args)1323 void LinkerDriver::createFiles(opt::InputArgList &args) {
1324 llvm::TimeTraceScope timeScope("Load input files");
1325 // For --{push,pop}-state.
1326 std::vector<std::tuple<bool, bool, bool>> stack;
1327
1328 // Iterate over argv to process input files and positional arguments.
1329 InputFile::isInGroup = false;
1330 for (auto *arg : args) {
1331 switch (arg->getOption().getID()) {
1332 case OPT_library:
1333 addLibrary(arg->getValue());
1334 break;
1335 case OPT_INPUT:
1336 addFile(arg->getValue(), /*withLOption=*/false);
1337 break;
1338 case OPT_defsym: {
1339 StringRef from;
1340 StringRef to;
1341 std::tie(from, to) = StringRef(arg->getValue()).split('=');
1342 if (from.empty() || to.empty())
1343 error("-defsym: syntax error: " + StringRef(arg->getValue()));
1344 else
1345 readDefsym(from, MemoryBufferRef(to, "-defsym"));
1346 break;
1347 }
1348 case OPT_script:
1349 if (Optional<std::string> path = searchScript(arg->getValue())) {
1350 if (Optional<MemoryBufferRef> mb = readFile(*path))
1351 readLinkerScript(*mb);
1352 break;
1353 }
1354 error(Twine("cannot find linker script ") + arg->getValue());
1355 break;
1356 case OPT_as_needed:
1357 config->asNeeded = true;
1358 break;
1359 case OPT_format:
1360 config->formatBinary = isFormatBinary(arg->getValue());
1361 break;
1362 case OPT_no_as_needed:
1363 config->asNeeded = false;
1364 break;
1365 case OPT_Bstatic:
1366 case OPT_omagic:
1367 case OPT_nmagic:
1368 config->isStatic = true;
1369 break;
1370 case OPT_Bdynamic:
1371 config->isStatic = false;
1372 break;
1373 case OPT_whole_archive:
1374 inWholeArchive = true;
1375 break;
1376 case OPT_no_whole_archive:
1377 inWholeArchive = false;
1378 break;
1379 case OPT_just_symbols:
1380 if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1381 files.push_back(createObjectFile(*mb));
1382 files.back()->justSymbols = true;
1383 }
1384 break;
1385 case OPT_start_group:
1386 if (InputFile::isInGroup)
1387 error("nested --start-group");
1388 InputFile::isInGroup = true;
1389 break;
1390 case OPT_end_group:
1391 if (!InputFile::isInGroup)
1392 error("stray --end-group");
1393 InputFile::isInGroup = false;
1394 ++InputFile::nextGroupId;
1395 break;
1396 case OPT_start_lib:
1397 if (inLib)
1398 error("nested --start-lib");
1399 if (InputFile::isInGroup)
1400 error("may not nest --start-lib in --start-group");
1401 inLib = true;
1402 InputFile::isInGroup = true;
1403 break;
1404 case OPT_end_lib:
1405 if (!inLib)
1406 error("stray --end-lib");
1407 inLib = false;
1408 InputFile::isInGroup = false;
1409 ++InputFile::nextGroupId;
1410 break;
1411 case OPT_push_state:
1412 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1413 break;
1414 case OPT_pop_state:
1415 if (stack.empty()) {
1416 error("unbalanced --push-state/--pop-state");
1417 break;
1418 }
1419 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1420 stack.pop_back();
1421 break;
1422 }
1423 }
1424
1425 if (files.empty() && errorCount() == 0)
1426 error("no input files");
1427 }
1428
1429 // If -m <machine_type> was not given, infer it from object files.
inferMachineType()1430 void LinkerDriver::inferMachineType() {
1431 if (config->ekind != ELFNoneKind)
1432 return;
1433
1434 for (InputFile *f : files) {
1435 if (f->ekind == ELFNoneKind)
1436 continue;
1437 config->ekind = f->ekind;
1438 config->emachine = f->emachine;
1439 config->osabi = f->osabi;
1440 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1441 return;
1442 }
1443 error("target emulation unknown: -m or at least one .o file required");
1444 }
1445
1446 // Parse -z max-page-size=<value>. The default value is defined by
1447 // each target.
getMaxPageSize(opt::InputArgList & args)1448 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1449 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1450 target->defaultMaxPageSize);
1451 if (!isPowerOf2_64(val))
1452 error("max-page-size: value isn't a power of 2");
1453 if (config->nmagic || config->omagic) {
1454 if (val != target->defaultMaxPageSize)
1455 warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1456 return 1;
1457 }
1458 return val;
1459 }
1460
1461 // Parse -z common-page-size=<value>. The default value is defined by
1462 // each target.
getCommonPageSize(opt::InputArgList & args)1463 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1464 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1465 target->defaultCommonPageSize);
1466 if (!isPowerOf2_64(val))
1467 error("common-page-size: value isn't a power of 2");
1468 if (config->nmagic || config->omagic) {
1469 if (val != target->defaultCommonPageSize)
1470 warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1471 return 1;
1472 }
1473 // commonPageSize can't be larger than maxPageSize.
1474 if (val > config->maxPageSize)
1475 val = config->maxPageSize;
1476 return val;
1477 }
1478
1479 // Parses -image-base option.
getImageBase(opt::InputArgList & args)1480 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1481 // Because we are using "Config->maxPageSize" here, this function has to be
1482 // called after the variable is initialized.
1483 auto *arg = args.getLastArg(OPT_image_base);
1484 if (!arg)
1485 return None;
1486
1487 StringRef s = arg->getValue();
1488 uint64_t v;
1489 if (!to_integer(s, v)) {
1490 error("-image-base: number expected, but got " + s);
1491 return 0;
1492 }
1493 if ((v % config->maxPageSize) != 0)
1494 warn("-image-base: address isn't multiple of page size: " + s);
1495 return v;
1496 }
1497
1498 // Parses `--exclude-libs=lib,lib,...`.
1499 // The library names may be delimited by commas or colons.
getExcludeLibs(opt::InputArgList & args)1500 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1501 DenseSet<StringRef> ret;
1502 for (auto *arg : args.filtered(OPT_exclude_libs)) {
1503 StringRef s = arg->getValue();
1504 for (;;) {
1505 size_t pos = s.find_first_of(",:");
1506 if (pos == StringRef::npos)
1507 break;
1508 ret.insert(s.substr(0, pos));
1509 s = s.substr(pos + 1);
1510 }
1511 ret.insert(s);
1512 }
1513 return ret;
1514 }
1515
1516 // Handles the -exclude-libs option. If a static library file is specified
1517 // by the -exclude-libs option, all public symbols from the archive become
1518 // private unless otherwise specified by version scripts or something.
1519 // A special library name "ALL" means all archive files.
1520 //
1521 // This is not a popular option, but some programs such as bionic libc use it.
excludeLibs(opt::InputArgList & args)1522 static void excludeLibs(opt::InputArgList &args) {
1523 DenseSet<StringRef> libs = getExcludeLibs(args);
1524 bool all = libs.count("ALL");
1525
1526 auto visit = [&](InputFile *file) {
1527 if (!file->archiveName.empty())
1528 if (all || libs.count(path::filename(file->archiveName)))
1529 for (Symbol *sym : file->getSymbols())
1530 if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
1531 sym->versionId = VER_NDX_LOCAL;
1532 };
1533
1534 for (InputFile *file : objectFiles)
1535 visit(file);
1536
1537 for (BitcodeFile *file : bitcodeFiles)
1538 visit(file);
1539 }
1540
1541 // Force Sym to be entered in the output.
handleUndefined(Symbol * sym)1542 static void handleUndefined(Symbol *sym) {
1543 // Since a symbol may not be used inside the program, LTO may
1544 // eliminate it. Mark the symbol as "used" to prevent it.
1545 sym->isUsedInRegularObj = true;
1546
1547 if (sym->isLazy())
1548 sym->fetch();
1549 }
1550
1551 // As an extension to GNU linkers, lld supports a variant of `-u`
1552 // which accepts wildcard patterns. All symbols that match a given
1553 // pattern are handled as if they were given by `-u`.
handleUndefinedGlob(StringRef arg)1554 static void handleUndefinedGlob(StringRef arg) {
1555 Expected<GlobPattern> pat = GlobPattern::create(arg);
1556 if (!pat) {
1557 error("--undefined-glob: " + toString(pat.takeError()));
1558 return;
1559 }
1560
1561 std::vector<Symbol *> syms;
1562 for (Symbol *sym : symtab->symbols()) {
1563 // Calling Sym->fetch() from here is not safe because it may
1564 // add new symbols to the symbol table, invalidating the
1565 // current iterator. So we just keep a note.
1566 if (pat->match(sym->getName()))
1567 syms.push_back(sym);
1568 }
1569
1570 for (Symbol *sym : syms)
1571 handleUndefined(sym);
1572 }
1573
handleLibcall(StringRef name)1574 static void handleLibcall(StringRef name) {
1575 Symbol *sym = symtab->find(name);
1576 if (!sym || !sym->isLazy())
1577 return;
1578
1579 MemoryBufferRef mb;
1580 if (auto *lo = dyn_cast<LazyObject>(sym))
1581 mb = lo->file->mb;
1582 else
1583 mb = cast<LazyArchive>(sym)->getMemberBuffer();
1584
1585 if (isBitcode(mb))
1586 sym->fetch();
1587 }
1588
1589 // Handle --dependency-file=<path>. If that option is given, lld creates a
1590 // file at a given path with the following contents:
1591 //
1592 // <output-file>: <input-file> ...
1593 //
1594 // <input-file>:
1595 //
1596 // where <output-file> is a pathname of an output file and <input-file>
1597 // ... is a list of pathnames of all input files. `make` command can read a
1598 // file in the above format and interpret it as a dependency info. We write
1599 // phony targets for every <input-file> to avoid an error when that file is
1600 // removed.
1601 //
1602 // This option is useful if you want to make your final executable to depend
1603 // on all input files including system libraries. Here is why.
1604 //
1605 // When you write a Makefile, you usually write it so that the final
1606 // executable depends on all user-generated object files. Normally, you
1607 // don't make your executable to depend on system libraries (such as libc)
1608 // because you don't know the exact paths of libraries, even though system
1609 // libraries that are linked to your executable statically are technically a
1610 // part of your program. By using --dependency-file option, you can make
1611 // lld to dump dependency info so that you can maintain exact dependencies
1612 // easily.
writeDependencyFile()1613 static void writeDependencyFile() {
1614 std::error_code ec;
1615 raw_fd_ostream os(config->dependencyFile, ec, sys::fs::F_None);
1616 if (ec) {
1617 error("cannot open " + config->dependencyFile + ": " + ec.message());
1618 return;
1619 }
1620
1621 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1622 // * A space is escaped by a backslash which itself must be escaped.
1623 // * A hash sign is escaped by a single backslash.
1624 // * $ is escapes as $$.
1625 auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1626 llvm::SmallString<256> nativePath;
1627 llvm::sys::path::native(filename.str(), nativePath);
1628 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1629 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1630 if (nativePath[i] == '#') {
1631 os << '\\';
1632 } else if (nativePath[i] == ' ') {
1633 os << '\\';
1634 unsigned j = i;
1635 while (j > 0 && nativePath[--j] == '\\')
1636 os << '\\';
1637 } else if (nativePath[i] == '$') {
1638 os << '$';
1639 }
1640 os << nativePath[i];
1641 }
1642 };
1643
1644 os << config->outputFile << ":";
1645 for (StringRef path : config->dependencyFiles) {
1646 os << " \\\n ";
1647 printFilename(os, path);
1648 }
1649 os << "\n";
1650
1651 for (StringRef path : config->dependencyFiles) {
1652 os << "\n";
1653 printFilename(os, path);
1654 os << ":\n";
1655 }
1656 }
1657
1658 // Replaces common symbols with defined symbols reside in .bss sections.
1659 // This function is called after all symbol names are resolved. As a
1660 // result, the passes after the symbol resolution won't see any
1661 // symbols of type CommonSymbol.
replaceCommonSymbols()1662 static void replaceCommonSymbols() {
1663 llvm::TimeTraceScope timeScope("Replace common symbols");
1664 for (Symbol *sym : symtab->symbols()) {
1665 auto *s = dyn_cast<CommonSymbol>(sym);
1666 if (!s)
1667 continue;
1668
1669 auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1670 bss->file = s->file;
1671 bss->markDead();
1672 inputSections.push_back(bss);
1673 s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1674 /*value=*/0, s->size, bss});
1675 }
1676 }
1677
1678 // If all references to a DSO happen to be weak, the DSO is not added
1679 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1680 // created from the DSO. Otherwise, they become dangling references
1681 // that point to a non-existent DSO.
demoteSharedSymbols()1682 static void demoteSharedSymbols() {
1683 llvm::TimeTraceScope timeScope("Demote shared symbols");
1684 for (Symbol *sym : symtab->symbols()) {
1685 auto *s = dyn_cast<SharedSymbol>(sym);
1686 if (!s || s->getFile().isNeeded)
1687 continue;
1688
1689 bool used = s->used;
1690 s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1691 s->used = used;
1692 }
1693 }
1694
1695 // The section referred to by `s` is considered address-significant. Set the
1696 // keepUnique flag on the section if appropriate.
markAddrsig(Symbol * s)1697 static void markAddrsig(Symbol *s) {
1698 if (auto *d = dyn_cast_or_null<Defined>(s))
1699 if (d->section)
1700 // We don't need to keep text sections unique under --icf=all even if they
1701 // are address-significant.
1702 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1703 d->section->keepUnique = true;
1704 }
1705
1706 // Record sections that define symbols mentioned in --keep-unique <symbol>
1707 // and symbols referred to by address-significance tables. These sections are
1708 // ineligible for ICF.
1709 template <class ELFT>
findKeepUniqueSections(opt::InputArgList & args)1710 static void findKeepUniqueSections(opt::InputArgList &args) {
1711 for (auto *arg : args.filtered(OPT_keep_unique)) {
1712 StringRef name = arg->getValue();
1713 auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1714 if (!d || !d->section) {
1715 warn("could not find symbol " + name + " to keep unique");
1716 continue;
1717 }
1718 d->section->keepUnique = true;
1719 }
1720
1721 // --icf=all --ignore-data-address-equality means that we can ignore
1722 // the dynsym and address-significance tables entirely.
1723 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1724 return;
1725
1726 // Symbols in the dynsym could be address-significant in other executables
1727 // or DSOs, so we conservatively mark them as address-significant.
1728 for (Symbol *sym : symtab->symbols())
1729 if (sym->includeInDynsym())
1730 markAddrsig(sym);
1731
1732 // Visit the address-significance table in each object file and mark each
1733 // referenced symbol as address-significant.
1734 for (InputFile *f : objectFiles) {
1735 auto *obj = cast<ObjFile<ELFT>>(f);
1736 ArrayRef<Symbol *> syms = obj->getSymbols();
1737 if (obj->addrsigSec) {
1738 ArrayRef<uint8_t> contents =
1739 check(obj->getObj().getSectionContents(*obj->addrsigSec));
1740 const uint8_t *cur = contents.begin();
1741 while (cur != contents.end()) {
1742 unsigned size;
1743 const char *err;
1744 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1745 if (err)
1746 fatal(toString(f) + ": could not decode addrsig section: " + err);
1747 markAddrsig(syms[symIndex]);
1748 cur += size;
1749 }
1750 } else {
1751 // If an object file does not have an address-significance table,
1752 // conservatively mark all of its symbols as address-significant.
1753 for (Symbol *s : syms)
1754 markAddrsig(s);
1755 }
1756 }
1757 }
1758
1759 // This function reads a symbol partition specification section. These sections
1760 // are used to control which partition a symbol is allocated to. See
1761 // https://lld.llvm.org/Partitions.html for more details on partitions.
1762 template <typename ELFT>
readSymbolPartitionSection(InputSectionBase * s)1763 static void readSymbolPartitionSection(InputSectionBase *s) {
1764 // Read the relocation that refers to the partition's entry point symbol.
1765 Symbol *sym;
1766 if (s->areRelocsRela)
1767 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1768 else
1769 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1770 if (!isa<Defined>(sym) || !sym->includeInDynsym())
1771 return;
1772
1773 StringRef partName = reinterpret_cast<const char *>(s->data().data());
1774 for (Partition &part : partitions) {
1775 if (part.name == partName) {
1776 sym->partition = part.getNumber();
1777 return;
1778 }
1779 }
1780
1781 // Forbid partitions from being used on incompatible targets, and forbid them
1782 // from being used together with various linker features that assume a single
1783 // set of output sections.
1784 if (script->hasSectionsCommand)
1785 error(toString(s->file) +
1786 ": partitions cannot be used with the SECTIONS command");
1787 if (script->hasPhdrsCommands())
1788 error(toString(s->file) +
1789 ": partitions cannot be used with the PHDRS command");
1790 if (!config->sectionStartMap.empty())
1791 error(toString(s->file) + ": partitions cannot be used with "
1792 "--section-start, -Ttext, -Tdata or -Tbss");
1793 if (config->emachine == EM_MIPS)
1794 error(toString(s->file) + ": partitions cannot be used on this target");
1795
1796 // Impose a limit of no more than 254 partitions. This limit comes from the
1797 // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1798 // the amount of space devoted to the partition number in RankFlags.
1799 if (partitions.size() == 254)
1800 fatal("may not have more than 254 partitions");
1801
1802 partitions.emplace_back();
1803 Partition &newPart = partitions.back();
1804 newPart.name = partName;
1805 sym->partition = newPart.getNumber();
1806 }
1807
addUndefined(StringRef name)1808 static Symbol *addUndefined(StringRef name) {
1809 return symtab->addSymbol(
1810 Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1811 }
1812
addUnusedUndefined(StringRef name)1813 static Symbol *addUnusedUndefined(StringRef name) {
1814 Undefined sym{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0};
1815 sym.isUsedInRegularObj = false;
1816 return symtab->addSymbol(sym);
1817 }
1818
1819 // This function is where all the optimizations of link-time
1820 // optimization takes place. When LTO is in use, some input files are
1821 // not in native object file format but in the LLVM bitcode format.
1822 // This function compiles bitcode files into a few big native files
1823 // using LLVM functions and replaces bitcode symbols with the results.
1824 // Because all bitcode files that the program consists of are passed to
1825 // the compiler at once, it can do a whole-program optimization.
compileBitcodeFiles()1826 template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1827 llvm::TimeTraceScope timeScope("LTO");
1828 // Compile bitcode files and replace bitcode symbols.
1829 lto.reset(new BitcodeCompiler);
1830 for (BitcodeFile *file : bitcodeFiles)
1831 lto->add(*file);
1832
1833 for (InputFile *file : lto->compile()) {
1834 auto *obj = cast<ObjFile<ELFT>>(file);
1835 obj->parse(/*ignoreComdats=*/true);
1836
1837 // Parse '@' in symbol names for non-relocatable output.
1838 if (!config->relocatable)
1839 for (Symbol *sym : obj->getGlobalSymbols())
1840 sym->parseSymbolVersion();
1841 objectFiles.push_back(file);
1842 }
1843 }
1844
1845 // The --wrap option is a feature to rename symbols so that you can write
1846 // wrappers for existing functions. If you pass `-wrap=foo`, all
1847 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
1848 // expected to write `__wrap_foo` function as a wrapper). The original
1849 // symbol becomes accessible as `__real_foo`, so you can call that from your
1850 // wrapper.
1851 //
1852 // This data structure is instantiated for each -wrap option.
1853 struct WrappedSymbol {
1854 Symbol *sym;
1855 Symbol *real;
1856 Symbol *wrap;
1857 };
1858
1859 // Handles -wrap option.
1860 //
1861 // This function instantiates wrapper symbols. At this point, they seem
1862 // like they are not being used at all, so we explicitly set some flags so
1863 // that LTO won't eliminate them.
addWrappedSymbols(opt::InputArgList & args)1864 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1865 std::vector<WrappedSymbol> v;
1866 DenseSet<StringRef> seen;
1867
1868 for (auto *arg : args.filtered(OPT_wrap)) {
1869 StringRef name = arg->getValue();
1870 if (!seen.insert(name).second)
1871 continue;
1872
1873 Symbol *sym = symtab->find(name);
1874 if (!sym)
1875 continue;
1876
1877 Symbol *real = addUnusedUndefined(saver.save("__real_" + name));
1878 Symbol *wrap = addUnusedUndefined(saver.save("__wrap_" + name));
1879 v.push_back({sym, real, wrap});
1880
1881 // We want to tell LTO not to inline symbols to be overwritten
1882 // because LTO doesn't know the final symbol contents after renaming.
1883 real->canInline = false;
1884 sym->canInline = false;
1885
1886 // Tell LTO not to eliminate these symbols.
1887 sym->isUsedInRegularObj = true;
1888 if (!wrap->isUndefined())
1889 wrap->isUsedInRegularObj = true;
1890 }
1891 return v;
1892 }
1893
1894 // Do renaming for -wrap by updating pointers to symbols.
1895 //
1896 // When this function is executed, only InputFiles and symbol table
1897 // contain pointers to symbol objects. We visit them to replace pointers,
1898 // so that wrapped symbols are swapped as instructed by the command line.
wrapSymbols(ArrayRef<WrappedSymbol> wrapped)1899 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1900 DenseMap<Symbol *, Symbol *> map;
1901 for (const WrappedSymbol &w : wrapped) {
1902 map[w.sym] = w.wrap;
1903 map[w.real] = w.sym;
1904 }
1905
1906 // Update pointers in input files.
1907 parallelForEach(objectFiles, [&](InputFile *file) {
1908 MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1909 for (size_t i = 0, e = syms.size(); i != e; ++i)
1910 if (Symbol *s = map.lookup(syms[i]))
1911 syms[i] = s;
1912 });
1913
1914 // Update pointers in the symbol table.
1915 for (const WrappedSymbol &w : wrapped)
1916 symtab->wrap(w.sym, w.real, w.wrap);
1917 }
1918
1919 // To enable CET (x86's hardware-assited control flow enforcement), each
1920 // source file must be compiled with -fcf-protection. Object files compiled
1921 // with the flag contain feature flags indicating that they are compatible
1922 // with CET. We enable the feature only when all object files are compatible
1923 // with CET.
1924 //
1925 // This is also the case with AARCH64's BTI and PAC which use the similar
1926 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
getAndFeatures()1927 template <class ELFT> static uint32_t getAndFeatures() {
1928 if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1929 config->emachine != EM_AARCH64)
1930 return 0;
1931
1932 uint32_t ret = -1;
1933 for (InputFile *f : objectFiles) {
1934 uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1935 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1936 warn(toString(f) + ": -z force-bti: file does not have "
1937 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
1938 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1939 } else if (config->zForceIbt &&
1940 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
1941 warn(toString(f) + ": -z force-ibt: file does not have "
1942 "GNU_PROPERTY_X86_FEATURE_1_IBT property");
1943 features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
1944 }
1945 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
1946 warn(toString(f) + ": -z pac-plt: file does not have "
1947 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
1948 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1949 }
1950 ret &= features;
1951 }
1952
1953 // Force enable Shadow Stack.
1954 if (config->zShstk)
1955 ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
1956
1957 return ret;
1958 }
1959
1960 // Do actual linking. Note that when this function is called,
1961 // all linker scripts have already been parsed.
link(opt::InputArgList & args)1962 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1963 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
1964 // If a -hash-style option was not given, set to a default value,
1965 // which varies depending on the target.
1966 if (!args.hasArg(OPT_hash_style)) {
1967 if (config->emachine == EM_MIPS)
1968 config->sysvHash = true;
1969 else
1970 config->sysvHash = config->gnuHash = true;
1971 }
1972
1973 // Default output filename is "a.out" by the Unix tradition.
1974 if (config->outputFile.empty())
1975 config->outputFile = "a.out";
1976
1977 // Fail early if the output file or map file is not writable. If a user has a
1978 // long link, e.g. due to a large LTO link, they do not wish to run it and
1979 // find that it failed because there was a mistake in their command-line.
1980 {
1981 llvm::TimeTraceScope timeScope("Create output files");
1982 if (auto e = tryCreateFile(config->outputFile))
1983 error("cannot open output file " + config->outputFile + ": " +
1984 e.message());
1985 if (auto e = tryCreateFile(config->mapFile))
1986 error("cannot open map file " + config->mapFile + ": " + e.message());
1987 }
1988 if (errorCount())
1989 return;
1990
1991 // Use default entry point name if no name was given via the command
1992 // line nor linker scripts. For some reason, MIPS entry point name is
1993 // different from others.
1994 config->warnMissingEntry =
1995 (!config->entry.empty() || (!config->shared && !config->relocatable));
1996 if (config->entry.empty() && !config->relocatable)
1997 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
1998
1999 // Handle --trace-symbol.
2000 for (auto *arg : args.filtered(OPT_trace_symbol))
2001 symtab->insert(arg->getValue())->traced = true;
2002
2003 // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2004 // -u foo a.a b.so will fetch a.a.
2005 for (StringRef name : config->undefined)
2006 addUnusedUndefined(name)->referenced = true;
2007
2008 // Add all files to the symbol table. This will add almost all
2009 // symbols that we need to the symbol table. This process might
2010 // add files to the link, via autolinking, these files are always
2011 // appended to the Files vector.
2012 {
2013 llvm::TimeTraceScope timeScope("Parse input files");
2014 for (size_t i = 0; i < files.size(); ++i) {
2015 llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
2016 parseFile(files[i]);
2017 }
2018 }
2019
2020 // Now that we have every file, we can decide if we will need a
2021 // dynamic symbol table.
2022 // We need one if we were asked to export dynamic symbols or if we are
2023 // producing a shared library.
2024 // We also need one if any shared libraries are used and for pie executables
2025 // (probably because the dynamic linker needs it).
2026 config->hasDynSymTab =
2027 !sharedFiles.empty() || config->isPic || config->exportDynamic;
2028
2029 // Some symbols (such as __ehdr_start) are defined lazily only when there
2030 // are undefined symbols for them, so we add these to trigger that logic.
2031 for (StringRef name : script->referencedSymbols)
2032 addUndefined(name);
2033
2034 // Prevent LTO from removing any definition referenced by -u.
2035 for (StringRef name : config->undefined)
2036 if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
2037 sym->isUsedInRegularObj = true;
2038
2039 // If an entry symbol is in a static archive, pull out that file now.
2040 if (Symbol *sym = symtab->find(config->entry))
2041 handleUndefined(sym);
2042
2043 // Handle the `--undefined-glob <pattern>` options.
2044 for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2045 handleUndefinedGlob(pat);
2046
2047 // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2048 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2049 sym->isUsedInRegularObj = true;
2050 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2051 sym->isUsedInRegularObj = true;
2052
2053 // If any of our inputs are bitcode files, the LTO code generator may create
2054 // references to certain library functions that might not be explicit in the
2055 // bitcode file's symbol table. If any of those library functions are defined
2056 // in a bitcode file in an archive member, we need to arrange to use LTO to
2057 // compile those archive members by adding them to the link beforehand.
2058 //
2059 // However, adding all libcall symbols to the link can have undesired
2060 // consequences. For example, the libgcc implementation of
2061 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2062 // that aborts the program if the Linux kernel does not support 64-bit
2063 // atomics, which would prevent the program from running even if it does not
2064 // use 64-bit atomics.
2065 //
2066 // Therefore, we only add libcall symbols to the link before LTO if we have
2067 // to, i.e. if the symbol's definition is in bitcode. Any other required
2068 // libcall symbols will be added to the link after LTO when we add the LTO
2069 // object file to the link.
2070 if (!bitcodeFiles.empty())
2071 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2072 handleLibcall(s);
2073
2074 // Return if there were name resolution errors.
2075 if (errorCount())
2076 return;
2077
2078 // We want to declare linker script's symbols early,
2079 // so that we can version them.
2080 // They also might be exported if referenced by DSOs.
2081 script->declareSymbols();
2082
2083 // Handle the -exclude-libs option.
2084 if (args.hasArg(OPT_exclude_libs))
2085 excludeLibs(args);
2086
2087 // Create elfHeader early. We need a dummy section in
2088 // addReservedSymbols to mark the created symbols as not absolute.
2089 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2090 Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2091
2092 // Create wrapped symbols for -wrap option.
2093 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2094
2095 // We need to create some reserved symbols such as _end. Create them.
2096 if (!config->relocatable)
2097 addReservedSymbols();
2098
2099 // Apply version scripts.
2100 //
2101 // For a relocatable output, version scripts don't make sense, and
2102 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2103 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2104 if (!config->relocatable) {
2105 llvm::TimeTraceScope timeScope("Process symbol versions");
2106 symtab->scanVersionScript();
2107 }
2108
2109 // Do link-time optimization if given files are LLVM bitcode files.
2110 // This compiles bitcode files into real object files.
2111 //
2112 // With this the symbol table should be complete. After this, no new names
2113 // except a few linker-synthesized ones will be added to the symbol table.
2114 compileBitcodeFiles<ELFT>();
2115
2116 // Symbol resolution finished. Report backward reference problems.
2117 reportBackrefs();
2118 if (errorCount())
2119 return;
2120
2121 // If -thinlto-index-only is given, we should create only "index
2122 // files" and not object files. Index file creation is already done
2123 // in addCombinedLTOObject, so we are done if that's the case.
2124 // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the
2125 // options to create output files in bitcode or assembly code
2126 // repsectively. No object files are generated.
2127 // Also bail out here when only certain thinLTO modules are specified for
2128 // compilation. The intermediate object file are the expected output.
2129 if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm ||
2130 !config->thinLTOModulesToCompile.empty())
2131 return;
2132
2133 // Apply symbol renames for -wrap.
2134 if (!wrapped.empty())
2135 wrapSymbols(wrapped);
2136
2137 {
2138 llvm::TimeTraceScope timeScope("Aggregate sections");
2139 // Now that we have a complete list of input files.
2140 // Beyond this point, no new files are added.
2141 // Aggregate all input sections into one place.
2142 for (InputFile *f : objectFiles)
2143 for (InputSectionBase *s : f->getSections())
2144 if (s && s != &InputSection::discarded)
2145 inputSections.push_back(s);
2146 for (BinaryFile *f : binaryFiles)
2147 for (InputSectionBase *s : f->getSections())
2148 inputSections.push_back(cast<InputSection>(s));
2149 }
2150
2151 {
2152 llvm::TimeTraceScope timeScope("Strip sections");
2153 llvm::erase_if(inputSections, [](InputSectionBase *s) {
2154 if (s->type == SHT_LLVM_SYMPART) {
2155 readSymbolPartitionSection<ELFT>(s);
2156 return true;
2157 }
2158
2159 // We do not want to emit debug sections if --strip-all
2160 // or -strip-debug are given.
2161 if (config->strip == StripPolicy::None)
2162 return false;
2163
2164 if (isDebugSection(*s))
2165 return true;
2166 if (auto *isec = dyn_cast<InputSection>(s))
2167 if (InputSectionBase *rel = isec->getRelocatedSection())
2168 if (isDebugSection(*rel))
2169 return true;
2170
2171 return false;
2172 });
2173 }
2174
2175 // Since we now have a complete set of input files, we can create
2176 // a .d file to record build dependencies.
2177 if (!config->dependencyFile.empty())
2178 writeDependencyFile();
2179
2180 // Now that the number of partitions is fixed, save a pointer to the main
2181 // partition.
2182 mainPart = &partitions[0];
2183
2184 // Read .note.gnu.property sections from input object files which
2185 // contain a hint to tweak linker's and loader's behaviors.
2186 config->andFeatures = getAndFeatures<ELFT>();
2187
2188 // The Target instance handles target-specific stuff, such as applying
2189 // relocations or writing a PLT section. It also contains target-dependent
2190 // values such as a default image base address.
2191 target = getTarget();
2192
2193 config->eflags = target->calcEFlags();
2194 // maxPageSize (sometimes called abi page size) is the maximum page size that
2195 // the output can be run on. For example if the OS can use 4k or 64k page
2196 // sizes then maxPageSize must be 64k for the output to be useable on both.
2197 // All important alignment decisions must use this value.
2198 config->maxPageSize = getMaxPageSize(args);
2199 // commonPageSize is the most common page size that the output will be run on.
2200 // For example if an OS can use 4k or 64k page sizes and 4k is more common
2201 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2202 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2203 // is limited to writing trap instructions on the last executable segment.
2204 config->commonPageSize = getCommonPageSize(args);
2205
2206 config->imageBase = getImageBase(args);
2207
2208 if (config->emachine == EM_ARM) {
2209 // FIXME: These warnings can be removed when lld only uses these features
2210 // when the input objects have been compiled with an architecture that
2211 // supports them.
2212 if (config->armHasBlx == false)
2213 warn("lld uses blx instruction, no object with architecture supporting "
2214 "feature detected");
2215 }
2216
2217 // This adds a .comment section containing a version string.
2218 if (!config->relocatable)
2219 inputSections.push_back(createCommentSection());
2220
2221 // Replace common symbols with regular symbols.
2222 replaceCommonSymbols();
2223
2224 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2225 splitSections<ELFT>();
2226
2227 // Garbage collection and removal of shared symbols from unused shared objects.
2228 markLive<ELFT>();
2229 demoteSharedSymbols();
2230
2231 // Make copies of any input sections that need to be copied into each
2232 // partition.
2233 copySectionsIntoPartitions();
2234
2235 // Create synthesized sections such as .got and .plt. This is called before
2236 // processSectionCommands() so that they can be placed by SECTIONS commands.
2237 createSyntheticSections<ELFT>();
2238
2239 // Some input sections that are used for exception handling need to be moved
2240 // into synthetic sections. Do that now so that they aren't assigned to
2241 // output sections in the usual way.
2242 if (!config->relocatable)
2243 combineEhSections();
2244
2245 {
2246 llvm::TimeTraceScope timeScope("Assign sections");
2247
2248 // Create output sections described by SECTIONS commands.
2249 script->processSectionCommands();
2250
2251 // Linker scripts control how input sections are assigned to output
2252 // sections. Input sections that were not handled by scripts are called
2253 // "orphans", and they are assigned to output sections by the default rule.
2254 // Process that.
2255 script->addOrphanSections();
2256 }
2257
2258 {
2259 llvm::TimeTraceScope timeScope("Merge/finalize input sections");
2260
2261 // Migrate InputSectionDescription::sectionBases to sections. This includes
2262 // merging MergeInputSections into a single MergeSyntheticSection. From this
2263 // point onwards InputSectionDescription::sections should be used instead of
2264 // sectionBases.
2265 for (BaseCommand *base : script->sectionCommands)
2266 if (auto *sec = dyn_cast<OutputSection>(base))
2267 sec->finalizeInputSections();
2268 llvm::erase_if(inputSections, [](InputSectionBase *s) {
2269 return isa<MergeInputSection>(s);
2270 });
2271 }
2272
2273 // Two input sections with different output sections should not be folded.
2274 // ICF runs after processSectionCommands() so that we know the output sections.
2275 if (config->icf != ICFLevel::None) {
2276 findKeepUniqueSections<ELFT>(args);
2277 doIcf<ELFT>();
2278 }
2279
2280 // Read the callgraph now that we know what was gced or icfed
2281 if (config->callGraphProfileSort) {
2282 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2283 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2284 readCallGraph(*buffer);
2285 readCallGraphsFromObjectFiles<ELFT>();
2286 }
2287
2288 // Write the result to the file.
2289 writeResult<ELFT>();
2290 }
2291