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