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