1 //===- Driver.cpp ---------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lld/Common/Driver.h"
11 #include "InputChunks.h"
12 #include "InputElement.h"
14 #include "SymbolTable.h"
16 #include "lld/Common/Args.h"
17 #include "lld/Common/CommonLinkerContext.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Filesystem.h"
20 #include "lld/Common/Memory.h"
21 #include "lld/Common/Reproduce.h"
22 #include "lld/Common/Strings.h"
23 #include "lld/Common/Version.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/Object/Wasm.h"
27 #include "llvm/Option/Arg.h"
28 #include "llvm/Option/ArgList.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Parallel.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/TarWriter.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/TargetParser/Host.h"
38 #define DEBUG_TYPE "lld"
41 using namespace llvm::object
;
42 using namespace llvm::opt
;
43 using namespace llvm::sys
;
44 using namespace llvm::wasm
;
47 Configuration
*config
;
51 // Create enum with OPT_xxx values for each option in Options.td
54 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
55 #include "Options.inc"
59 // This function is called on startup. We need this for LTO since
60 // LTO calls LLVM functions to compile bitcode files to native code.
61 // Technically this can be delayed until we read bitcode files, but
62 // we don't bother to do lazily because the initialization is fast.
63 static void initLLVM() {
64 InitializeAllTargets();
65 InitializeAllTargetMCs();
66 InitializeAllAsmPrinters();
67 InitializeAllAsmParsers();
72 void linkerMain(ArrayRef
<const char *> argsArr
);
75 void createFiles(opt::InputArgList
&args
);
76 void addFile(StringRef path
);
77 void addLibrary(StringRef name
);
79 // True if we are in --whole-archive and --no-whole-archive.
80 bool inWholeArchive
= false;
82 std::vector
<InputFile
*> files
;
84 } // anonymous namespace
86 bool link(ArrayRef
<const char *> args
, llvm::raw_ostream
&stdoutOS
,
87 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
) {
88 // This driver-specific context will be freed later by unsafeLldMain().
89 auto *ctx
= new CommonLinkerContext
;
91 ctx
->e
.initialize(stdoutOS
, stderrOS
, exitEarly
, disableOutput
);
92 ctx
->e
.logName
= args::getFilenameWithoutExe(args
[0]);
93 ctx
->e
.errorLimitExceededMsg
= "too many errors emitted, stopping now (use "
94 "-error-limit=0 to see all errors)";
96 config
= make
<Configuration
>();
97 symtab
= make
<SymbolTable
>();
100 LinkerDriver().linkerMain(args
);
102 return errorCount() == 0;
105 // Create prefix string literals used in Options.td
106 #define PREFIX(NAME, VALUE) \
107 static constexpr StringLiteral NAME##_init[] = VALUE; \
108 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
109 std::size(NAME##_init) - 1);
110 #include "Options.inc"
113 // Create table mapping all options defined in Options.td
114 static constexpr opt::OptTable::Info optInfo
[] = {
115 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
116 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES) \
117 {PREFIX, NAME, HELPTEXT, \
118 METAVAR, OPT_##ID, opt::Option::KIND##Class, \
119 PARAM, FLAGS, VISIBILITY, \
120 OPT_##GROUP, OPT_##ALIAS, ALIASARGS, \
122 #include "Options.inc"
127 class WasmOptTable
: public opt::GenericOptTable
{
129 WasmOptTable() : opt::GenericOptTable(optInfo
) {}
130 opt::InputArgList
parse(ArrayRef
<const char *> argv
);
134 // Set color diagnostics according to -color-diagnostics={auto,always,never}
135 // or -no-color-diagnostics flags.
136 static void handleColorDiagnostics(opt::InputArgList
&args
) {
137 auto *arg
= args
.getLastArg(OPT_color_diagnostics
, OPT_color_diagnostics_eq
,
138 OPT_no_color_diagnostics
);
141 if (arg
->getOption().getID() == OPT_color_diagnostics
) {
142 lld::errs().enable_colors(true);
143 } else if (arg
->getOption().getID() == OPT_no_color_diagnostics
) {
144 lld::errs().enable_colors(false);
146 StringRef s
= arg
->getValue();
148 lld::errs().enable_colors(true);
149 else if (s
== "never")
150 lld::errs().enable_colors(false);
151 else if (s
!= "auto")
152 error("unknown option: --color-diagnostics=" + s
);
156 static cl::TokenizerCallback
getQuotingStyle(opt::InputArgList
&args
) {
157 if (auto *arg
= args
.getLastArg(OPT_rsp_quoting
)) {
158 StringRef s
= arg
->getValue();
159 if (s
!= "windows" && s
!= "posix")
160 error("invalid response file quoting: " + s
);
162 return cl::TokenizeWindowsCommandLine
;
163 return cl::TokenizeGNUCommandLine
;
165 if (Triple(sys::getProcessTriple()).isOSWindows())
166 return cl::TokenizeWindowsCommandLine
;
167 return cl::TokenizeGNUCommandLine
;
170 // Find a file by concatenating given paths.
171 static std::optional
<std::string
> findFile(StringRef path1
,
172 const Twine
&path2
) {
174 path::append(s
, path1
, path2
);
176 return std::string(s
);
180 opt::InputArgList
WasmOptTable::parse(ArrayRef
<const char *> argv
) {
181 SmallVector
<const char *, 256> vec(argv
.data(), argv
.data() + argv
.size());
183 unsigned missingIndex
;
184 unsigned missingCount
;
186 // We need to get the quoting style for response files before parsing all
187 // options so we parse here before and ignore all the options but
189 opt::InputArgList args
= this->ParseArgs(vec
, missingIndex
, missingCount
);
191 // Expand response files (arguments in the form of @<filename>)
192 // and then parse the argument again.
193 cl::ExpandResponseFiles(saver(), getQuotingStyle(args
), vec
);
194 args
= this->ParseArgs(vec
, missingIndex
, missingCount
);
196 handleColorDiagnostics(args
);
198 error(Twine(args
.getArgString(missingIndex
)) + ": missing argument");
200 for (auto *arg
: args
.filtered(OPT_UNKNOWN
))
201 error("unknown argument: " + arg
->getAsString(args
));
205 // Currently we allow a ".imports" to live alongside a library. This can
206 // be used to specify a list of symbols which can be undefined at link
207 // time (imported from the environment. For example libc.a include an
208 // import file that lists the syscall functions it relies on at runtime.
209 // In the long run this information would be better stored as a symbol
210 // attribute/flag in the object file itself.
211 // See: https://github.com/WebAssembly/tool-conventions/issues/35
212 static void readImportFile(StringRef filename
) {
213 if (std::optional
<MemoryBufferRef
> buf
= readFile(filename
))
214 for (StringRef sym
: args::getLines(*buf
))
215 config
->allowUndefinedSymbols
.insert(sym
);
218 // Returns slices of MB by parsing MB as an archive file.
219 // Each slice consists of a member file in the archive.
220 std::vector
<MemoryBufferRef
> static getArchiveMembers(MemoryBufferRef mb
) {
221 std::unique_ptr
<Archive
> file
=
222 CHECK(Archive::create(mb
),
223 mb
.getBufferIdentifier() + ": failed to parse archive");
225 std::vector
<MemoryBufferRef
> v
;
226 Error err
= Error::success();
227 for (const Archive::Child
&c
: file
->children(err
)) {
228 MemoryBufferRef mbref
=
229 CHECK(c
.getMemoryBufferRef(),
230 mb
.getBufferIdentifier() +
231 ": could not get the buffer for a child of the archive");
235 fatal(mb
.getBufferIdentifier() +
236 ": Archive::children failed: " + toString(std::move(err
)));
238 // Take ownership of memory buffers created for members of thin archives.
239 for (std::unique_ptr
<MemoryBuffer
> &mb
: file
->takeThinBuffers())
240 make
<std::unique_ptr
<MemoryBuffer
>>(std::move(mb
));
245 void LinkerDriver::addFile(StringRef path
) {
246 std::optional
<MemoryBufferRef
> buffer
= readFile(path
);
249 MemoryBufferRef mbref
= *buffer
;
251 switch (identify_magic(mbref
.getBuffer())) {
252 case file_magic::archive
: {
253 SmallString
<128> importFile
= path
;
254 path::replace_extension(importFile
, ".imports");
255 if (fs::exists(importFile
))
256 readImportFile(importFile
.str());
258 // Handle -whole-archive.
259 if (inWholeArchive
) {
260 for (MemoryBufferRef
&m
: getArchiveMembers(mbref
)) {
261 auto *object
= createObjectFile(m
, path
);
262 // Mark object as live; object members are normally not
263 // live by default but -whole-archive is designed to treat
266 files
.push_back(object
);
272 std::unique_ptr
<Archive
> file
=
273 CHECK(Archive::create(mbref
), path
+ ": failed to parse archive");
275 if (!file
->isEmpty() && !file
->hasSymbolTable()) {
276 error(mbref
.getBufferIdentifier() +
277 ": archive has no index; run ranlib to add one");
280 files
.push_back(make
<ArchiveFile
>(mbref
));
283 case file_magic::bitcode
:
284 case file_magic::wasm_object
:
285 files
.push_back(createObjectFile(mbref
));
287 case file_magic::unknown
:
288 if (mbref
.getBuffer().starts_with("#STUB")) {
289 files
.push_back(make
<StubFile
>(mbref
));
294 error("unknown file type: " + mbref
.getBufferIdentifier());
298 static std::optional
<std::string
> findFromSearchPaths(StringRef path
) {
299 for (StringRef dir
: config
->searchPaths
)
300 if (std::optional
<std::string
> s
= findFile(dir
, path
))
305 // This is for -l<basename>. We'll look for lib<basename>.a from
307 static std::optional
<std::string
> searchLibraryBaseName(StringRef name
) {
308 for (StringRef dir
: config
->searchPaths
) {
309 // Currently we don't enable dynamic linking at all unless -shared or -pie
310 // are used, so don't even look for .so files in that case..
311 if (config
->isPic
&& !config
->isStatic
)
312 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".so"))
314 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".a"))
320 // This is for -l<namespec>.
321 static std::optional
<std::string
> searchLibrary(StringRef name
) {
322 if (name
.starts_with(":"))
323 return findFromSearchPaths(name
.substr(1));
324 return searchLibraryBaseName(name
);
327 // Add a given library by searching it from input search paths.
328 void LinkerDriver::addLibrary(StringRef name
) {
329 if (std::optional
<std::string
> path
= searchLibrary(name
))
330 addFile(saver().save(*path
));
332 error("unable to find library -l" + name
, ErrorTag::LibNotFound
, {name
});
335 void LinkerDriver::createFiles(opt::InputArgList
&args
) {
336 for (auto *arg
: args
) {
337 switch (arg
->getOption().getID()) {
339 addLibrary(arg
->getValue());
342 addFile(arg
->getValue());
345 config
->isStatic
= true;
348 config
->isStatic
= false;
350 case OPT_whole_archive
:
351 inWholeArchive
= true;
353 case OPT_no_whole_archive
:
354 inWholeArchive
= false;
358 if (files
.empty() && errorCount() == 0)
359 error("no input files");
362 static StringRef
getEntry(opt::InputArgList
&args
) {
363 auto *arg
= args
.getLastArg(OPT_entry
, OPT_no_entry
);
365 if (args
.hasArg(OPT_relocatable
))
367 if (args
.hasArg(OPT_shared
))
368 return "__wasm_call_ctors";
371 if (arg
->getOption().getID() == OPT_no_entry
)
373 return arg
->getValue();
376 // Determines what we should do if there are remaining unresolved
377 // symbols after the name resolution.
378 static UnresolvedPolicy
getUnresolvedSymbolPolicy(opt::InputArgList
&args
) {
379 UnresolvedPolicy errorOrWarn
= args
.hasFlag(OPT_error_unresolved_symbols
,
380 OPT_warn_unresolved_symbols
, true)
381 ? UnresolvedPolicy::ReportError
382 : UnresolvedPolicy::Warn
;
384 if (auto *arg
= args
.getLastArg(OPT_unresolved_symbols
)) {
385 StringRef s
= arg
->getValue();
386 if (s
== "ignore-all")
387 return UnresolvedPolicy::Ignore
;
388 if (s
== "import-dynamic")
389 return UnresolvedPolicy::ImportDynamic
;
390 if (s
== "report-all")
392 error("unknown --unresolved-symbols value: " + s
);
398 // Parse --build-id or --build-id=<style>. We handle "tree" as a
399 // synonym for "sha1" because all our hash functions including
400 // -build-id=sha1 are actually tree hashes for performance reasons.
401 static std::pair
<BuildIdKind
, SmallVector
<uint8_t, 0>>
402 getBuildId(opt::InputArgList
&args
) {
403 auto *arg
= args
.getLastArg(OPT_build_id
, OPT_build_id_eq
);
405 return {BuildIdKind::None
, {}};
407 if (arg
->getOption().getID() == OPT_build_id
)
408 return {BuildIdKind::Fast
, {}};
410 StringRef s
= arg
->getValue();
412 return {BuildIdKind::Fast
, {}};
413 if (s
== "sha1" || s
== "tree")
414 return {BuildIdKind::Sha1
, {}};
416 return {BuildIdKind::Uuid
, {}};
417 if (s
.starts_with("0x"))
418 return {BuildIdKind::Hexstring
, parseHex(s
.substr(2))};
421 error("unknown --build-id style: " + s
);
422 return {BuildIdKind::None
, {}};
425 // Initializes Config members by the command line options.
426 static void readConfigs(opt::InputArgList
&args
) {
427 config
->bsymbolic
= args
.hasArg(OPT_Bsymbolic
);
428 config
->checkFeatures
=
429 args
.hasFlag(OPT_check_features
, OPT_no_check_features
, true);
430 config
->compressRelocations
= args
.hasArg(OPT_compress_relocations
);
431 config
->demangle
= args
.hasFlag(OPT_demangle
, OPT_no_demangle
, true);
432 config
->disableVerify
= args
.hasArg(OPT_disable_verify
);
433 config
->emitRelocs
= args
.hasArg(OPT_emit_relocs
);
434 config
->experimentalPic
= args
.hasArg(OPT_experimental_pic
);
435 config
->entry
= getEntry(args
);
436 config
->exportAll
= args
.hasArg(OPT_export_all
);
437 config
->exportTable
= args
.hasArg(OPT_export_table
);
438 config
->growableTable
= args
.hasArg(OPT_growable_table
);
440 if (args
.hasArg(OPT_import_memory_with_name
)) {
441 config
->memoryImport
=
442 args
.getLastArgValue(OPT_import_memory_with_name
).split(",");
443 } else if (args
.hasArg(OPT_import_memory
)) {
444 config
->memoryImport
=
445 std::pair
<llvm::StringRef
, llvm::StringRef
>(defaultModule
, memoryName
);
447 config
->memoryImport
=
448 std::optional
<std::pair
<llvm::StringRef
, llvm::StringRef
>>();
451 if (args
.hasArg(OPT_export_memory_with_name
)) {
452 config
->memoryExport
=
453 args
.getLastArgValue(OPT_export_memory_with_name
);
454 } else if (args
.hasArg(OPT_export_memory
)) {
455 config
->memoryExport
= memoryName
;
457 config
->memoryExport
= std::optional
<llvm::StringRef
>();
460 config
->sharedMemory
= args
.hasArg(OPT_shared_memory
);
461 config
->soName
= args
.getLastArgValue(OPT_soname
);
462 config
->importTable
= args
.hasArg(OPT_import_table
);
463 config
->importUndefined
= args
.hasArg(OPT_import_undefined
);
464 config
->ltoo
= args::getInteger(args
, OPT_lto_O
, 2);
465 if (config
->ltoo
> 3)
466 error("invalid optimization level for LTO: " + Twine(config
->ltoo
));
468 args::getInteger(args
, OPT_lto_CGO
, args::getCGOptLevel(config
->ltoo
));
469 if (auto level
= CodeGenOpt::getLevel(ltoCgo
))
470 config
->ltoCgo
= *level
;
472 error("invalid codegen optimization level for LTO: " + Twine(ltoCgo
));
473 config
->ltoPartitions
= args::getInteger(args
, OPT_lto_partitions
, 1);
474 config
->ltoDebugPassManager
= args
.hasArg(OPT_lto_debug_pass_manager
);
475 config
->mapFile
= args
.getLastArgValue(OPT_Map
);
476 config
->optimize
= args::getInteger(args
, OPT_O
, 1);
477 config
->outputFile
= args
.getLastArgValue(OPT_o
);
478 config
->relocatable
= args
.hasArg(OPT_relocatable
);
480 args
.hasFlag(OPT_gc_sections
, OPT_no_gc_sections
, !config
->relocatable
);
481 for (auto *arg
: args
.filtered(OPT_keep_section
))
482 config
->keepSections
.insert(arg
->getValue());
483 config
->mergeDataSegments
=
484 args
.hasFlag(OPT_merge_data_segments
, OPT_no_merge_data_segments
,
485 !config
->relocatable
);
486 config
->pie
= args
.hasFlag(OPT_pie
, OPT_no_pie
, false);
487 config
->printGcSections
=
488 args
.hasFlag(OPT_print_gc_sections
, OPT_no_print_gc_sections
, false);
489 config
->saveTemps
= args
.hasArg(OPT_save_temps
);
490 config
->searchPaths
= args::getStrings(args
, OPT_library_path
);
491 config
->shared
= args
.hasArg(OPT_shared
);
492 config
->stripAll
= args
.hasArg(OPT_strip_all
);
493 config
->stripDebug
= args
.hasArg(OPT_strip_debug
);
494 config
->stackFirst
= args
.hasArg(OPT_stack_first
);
495 config
->trace
= args
.hasArg(OPT_trace
);
496 config
->thinLTOCacheDir
= args
.getLastArgValue(OPT_thinlto_cache_dir
);
497 config
->thinLTOCachePolicy
= CHECK(
498 parseCachePruningPolicy(args
.getLastArgValue(OPT_thinlto_cache_policy
)),
499 "--thinlto-cache-policy: invalid cache policy");
500 config
->unresolvedSymbols
= getUnresolvedSymbolPolicy(args
);
501 config
->whyExtract
= args
.getLastArgValue(OPT_why_extract
);
502 errorHandler().verbose
= args
.hasArg(OPT_verbose
);
503 LLVM_DEBUG(errorHandler().verbose
= true);
505 config
->tableBase
= args::getInteger(args
, OPT_table_base
, 0);
506 config
->globalBase
= args::getInteger(args
, OPT_global_base
, 0);
507 config
->initialHeap
= args::getInteger(args
, OPT_initial_heap
, 0);
508 config
->initialMemory
= args::getInteger(args
, OPT_initial_memory
, 0);
509 config
->maxMemory
= args::getInteger(args
, OPT_max_memory
, 0);
511 args::getZOptionValue(args
, OPT_z
, "stack-size", WasmPageSize
);
513 // Default value of exportDynamic depends on `-shared`
514 config
->exportDynamic
=
515 args
.hasFlag(OPT_export_dynamic
, OPT_no_export_dynamic
, config
->shared
);
518 if (auto *arg
= args
.getLastArg(OPT_m
)) {
519 StringRef s
= arg
->getValue();
521 config
->is64
= false;
522 else if (s
== "wasm64")
525 error("invalid target architecture: " + s
);
528 // --threads= takes a positive integer and provides the default value for
530 if (auto *arg
= args
.getLastArg(OPT_threads
)) {
531 StringRef
v(arg
->getValue());
532 unsigned threads
= 0;
533 if (!llvm::to_integer(v
, threads
, 0) || threads
== 0)
534 error(arg
->getSpelling() + ": expected a positive integer, but got '" +
535 arg
->getValue() + "'");
536 parallel::strategy
= hardware_concurrency(threads
);
537 config
->thinLTOJobs
= v
;
539 if (auto *arg
= args
.getLastArg(OPT_thinlto_jobs
))
540 config
->thinLTOJobs
= arg
->getValue();
542 if (auto *arg
= args
.getLastArg(OPT_features
)) {
544 std::optional
<std::vector
<std::string
>>(std::vector
<std::string
>());
545 for (StringRef s
: arg
->getValues())
546 config
->features
->push_back(std::string(s
));
549 if (auto *arg
= args
.getLastArg(OPT_extra_features
)) {
550 config
->extraFeatures
=
551 std::optional
<std::vector
<std::string
>>(std::vector
<std::string
>());
552 for (StringRef s
: arg
->getValues())
553 config
->extraFeatures
->push_back(std::string(s
));
556 // Legacy --allow-undefined flag which is equivalent to
557 // --unresolve-symbols=ignore + --import-undefined
558 if (args
.hasArg(OPT_allow_undefined
)) {
559 config
->importUndefined
= true;
560 config
->unresolvedSymbols
= UnresolvedPolicy::Ignore
;
563 if (args
.hasArg(OPT_print_map
))
564 config
->mapFile
= "-";
566 std::tie(config
->buildId
, config
->buildIdVector
) = getBuildId(args
);
569 // Some Config members do not directly correspond to any particular
570 // command line options, but computed based on other Config values.
571 // This function initialize such members. See Config.h for the details
573 static void setConfigs() {
574 config
->isPic
= config
->pie
|| config
->shared
;
577 if (config
->exportTable
)
578 error("-shared/-pie is incompatible with --export-table");
579 config
->importTable
= true;
581 // Default table base. Defaults to 1, reserving 0 for the NULL function
583 if (!config
->tableBase
)
584 config
->tableBase
= 1;
585 // The default offset for static/global data, for when --global-base is
586 // not specified on the command line. The precise value of 1024 is
587 // somewhat arbitrary, and pre-dates wasm-ld (Its the value that
588 // emscripten used prior to wasm-ld).
589 if (!config
->globalBase
&& !config
->relocatable
&& !config
->stackFirst
)
590 config
->globalBase
= 1024;
593 if (config
->relocatable
) {
594 if (config
->exportTable
)
595 error("--relocatable is incompatible with --export-table");
596 if (config
->growableTable
)
597 error("--relocatable is incompatible with --growable-table");
598 // Ignore any --import-table, as it's redundant.
599 config
->importTable
= true;
602 if (config
->shared
) {
603 if (config
->memoryExport
.has_value()) {
604 error("--export-memory is incompatible with --shared");
606 if (!config
->memoryImport
.has_value()) {
607 config
->memoryImport
=
608 std::pair
<llvm::StringRef
, llvm::StringRef
>(defaultModule
, memoryName
);
612 // If neither export-memory nor import-memory is specified, default to
613 // exporting memory under its default name.
614 if (!config
->memoryExport
.has_value() && !config
->memoryImport
.has_value()) {
615 config
->memoryExport
= memoryName
;
619 // Some command line options or some combinations of them are not allowed.
620 // This function checks for such errors.
621 static void checkOptions(opt::InputArgList
&args
) {
622 if (!config
->stripDebug
&& !config
->stripAll
&& config
->compressRelocations
)
623 error("--compress-relocations is incompatible with output debug"
624 " information. Please pass --strip-debug or --strip-all");
626 if (config
->ltoPartitions
== 0)
627 error("--lto-partitions: number of threads must be > 0");
628 if (!get_threadpool_strategy(config
->thinLTOJobs
))
629 error("--thinlto-jobs: invalid job count: " + config
->thinLTOJobs
);
631 if (config
->pie
&& config
->shared
)
632 error("-shared and -pie may not be used together");
634 if (config
->outputFile
.empty())
635 error("no output file specified");
637 if (config
->importTable
&& config
->exportTable
)
638 error("--import-table and --export-table may not be used together");
640 if (config
->relocatable
) {
641 if (!config
->entry
.empty())
642 error("entry point specified for relocatable output file");
643 if (config
->gcSections
)
644 error("-r and --gc-sections may not be used together");
645 if (config
->compressRelocations
)
646 error("-r -and --compress-relocations may not be used together");
647 if (args
.hasArg(OPT_undefined
))
648 error("-r -and --undefined may not be used together");
650 error("-r and -pie may not be used together");
651 if (config
->sharedMemory
)
652 error("-r and --shared-memory may not be used together");
653 if (config
->globalBase
)
654 error("-r and --global-base may not by used together");
657 // To begin to prepare for Module Linking-style shared libraries, start
658 // warning about uses of `-shared` and related flags outside of Experimental
659 // mode, to give anyone using them a heads-up that they will be changing.
661 // Also, warn about flags which request explicit exports.
662 if (!config
->experimentalPic
) {
663 // -shared will change meaning when Module Linking is implemented.
664 if (config
->shared
) {
665 warn("creating shared libraries, with -shared, is not yet stable");
668 // -pie will change meaning when Module Linking is implemented.
670 warn("creating PIEs, with -pie, is not yet stable");
673 if (config
->unresolvedSymbols
== UnresolvedPolicy::ImportDynamic
) {
674 warn("dynamic imports are not yet stable "
675 "(--unresolved-symbols=import-dynamic)");
679 if (config
->bsymbolic
&& !config
->shared
) {
680 warn("-Bsymbolic is only meaningful when combined with -shared");
684 if (config
->globalBase
)
685 error("--global-base may not be used with -shared/-pie");
686 if (config
->tableBase
)
687 error("--table-base may not be used with -shared/-pie");
691 static const char *getReproduceOption(opt::InputArgList
&args
) {
692 if (auto *arg
= args
.getLastArg(OPT_reproduce
))
693 return arg
->getValue();
694 return getenv("LLD_REPRODUCE");
697 // Force Sym to be entered in the output. Used for -u or equivalent.
698 static Symbol
*handleUndefined(StringRef name
, const char *option
) {
699 Symbol
*sym
= symtab
->find(name
);
703 // Since symbol S may not be used inside the program, LTO may
704 // eliminate it. Mark the symbol as "used" to prevent it.
705 sym
->isUsedInRegularObj
= true;
707 if (auto *lazySym
= dyn_cast
<LazySymbol
>(sym
)) {
709 if (!config
->whyExtract
.empty())
710 config
->whyExtractRecords
.emplace_back(option
, sym
->getFile(), *sym
);
716 static void handleLibcall(StringRef name
) {
717 Symbol
*sym
= symtab
->find(name
);
721 if (auto *lazySym
= dyn_cast
<LazySymbol
>(sym
)) {
722 MemoryBufferRef mb
= lazySym
->getMemberBuffer();
724 if (!config
->whyExtract
.empty())
725 config
->whyExtractRecords
.emplace_back("<libcall>", sym
->getFile(),
732 static void writeWhyExtract() {
733 if (config
->whyExtract
.empty())
737 raw_fd_ostream
os(config
->whyExtract
, ec
, sys::fs::OF_None
);
739 error("cannot open --why-extract= file " + config
->whyExtract
+ ": " +
744 os
<< "reference\textracted\tsymbol\n";
745 for (auto &entry
: config
->whyExtractRecords
) {
746 os
<< std::get
<0>(entry
) << '\t' << toString(std::get
<1>(entry
)) << '\t'
747 << toString(std::get
<2>(entry
)) << '\n';
751 // Equivalent of demote demoteSharedAndLazySymbols() in the ELF linker
752 static void demoteLazySymbols() {
753 for (Symbol
*sym
: symtab
->symbols()) {
754 if (auto* s
= dyn_cast
<LazySymbol
>(sym
)) {
756 LLVM_DEBUG(llvm::dbgs()
757 << "demoting lazy func: " << s
->getName() << "\n");
758 replaceSymbol
<UndefinedFunction
>(s
, s
->getName(), std::nullopt
,
759 std::nullopt
, WASM_SYMBOL_BINDING_WEAK
,
760 s
->getFile(), s
->signature
);
766 static UndefinedGlobal
*
767 createUndefinedGlobal(StringRef name
, llvm::wasm::WasmGlobalType
*type
) {
768 auto *sym
= cast
<UndefinedGlobal
>(symtab
->addUndefinedGlobal(
769 name
, std::nullopt
, std::nullopt
, WASM_SYMBOL_UNDEFINED
, nullptr, type
));
770 config
->allowUndefinedSymbols
.insert(sym
->getName());
771 sym
->isUsedInRegularObj
= true;
775 static InputGlobal
*createGlobal(StringRef name
, bool isMutable
) {
776 llvm::wasm::WasmGlobal wasmGlobal
;
777 bool is64
= config
->is64
.value_or(false);
778 wasmGlobal
.Type
= {uint8_t(is64
? WASM_TYPE_I64
: WASM_TYPE_I32
), isMutable
};
779 wasmGlobal
.InitExpr
= intConst(0, is64
);
780 wasmGlobal
.SymbolName
= name
;
781 return make
<InputGlobal
>(wasmGlobal
, nullptr);
784 static GlobalSymbol
*createGlobalVariable(StringRef name
, bool isMutable
) {
785 InputGlobal
*g
= createGlobal(name
, isMutable
);
786 return symtab
->addSyntheticGlobal(name
, WASM_SYMBOL_VISIBILITY_HIDDEN
, g
);
789 static GlobalSymbol
*createOptionalGlobal(StringRef name
, bool isMutable
) {
790 InputGlobal
*g
= createGlobal(name
, isMutable
);
791 return symtab
->addOptionalGlobalSymbol(name
, g
);
794 // Create ABI-defined synthetic symbols
795 static void createSyntheticSymbols() {
796 if (config
->relocatable
)
799 static WasmSignature nullSignature
= {{}, {}};
800 static WasmSignature i32ArgSignature
= {{}, {ValType::I32
}};
801 static WasmSignature i64ArgSignature
= {{}, {ValType::I64
}};
802 static llvm::wasm::WasmGlobalType globalTypeI32
= {WASM_TYPE_I32
, false};
803 static llvm::wasm::WasmGlobalType globalTypeI64
= {WASM_TYPE_I64
, false};
804 static llvm::wasm::WasmGlobalType mutableGlobalTypeI32
= {WASM_TYPE_I32
,
806 static llvm::wasm::WasmGlobalType mutableGlobalTypeI64
= {WASM_TYPE_I64
,
808 WasmSym::callCtors
= symtab
->addSyntheticFunction(
809 "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN
,
810 make
<SyntheticFunction
>(nullSignature
, "__wasm_call_ctors"));
812 bool is64
= config
->is64
.value_or(false);
815 WasmSym::stackPointer
=
816 createUndefinedGlobal("__stack_pointer", config
->is64
.value_or(false)
817 ? &mutableGlobalTypeI64
818 : &mutableGlobalTypeI32
);
819 // For PIC code, we import two global variables (__memory_base and
820 // __table_base) from the environment and use these as the offset at
821 // which to load our static data and function table.
823 // https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md
824 auto *globalType
= is64
? &globalTypeI64
: &globalTypeI32
;
825 WasmSym::memoryBase
= createUndefinedGlobal("__memory_base", globalType
);
826 WasmSym::tableBase
= createUndefinedGlobal("__table_base", globalType
);
827 WasmSym::memoryBase
->markLive();
828 WasmSym::tableBase
->markLive();
830 WasmSym::tableBase32
=
831 createUndefinedGlobal("__table_base32", &globalTypeI32
);
832 WasmSym::tableBase32
->markLive();
834 WasmSym::tableBase32
= nullptr;
838 WasmSym::stackPointer
= createGlobalVariable("__stack_pointer", true);
839 WasmSym::stackPointer
->markLive();
842 if (config
->sharedMemory
) {
843 WasmSym::tlsBase
= createGlobalVariable("__tls_base", true);
844 WasmSym::tlsSize
= createGlobalVariable("__tls_size", false);
845 WasmSym::tlsAlign
= createGlobalVariable("__tls_align", false);
846 WasmSym::initTLS
= symtab
->addSyntheticFunction(
847 "__wasm_init_tls", WASM_SYMBOL_VISIBILITY_HIDDEN
,
848 make
<SyntheticFunction
>(
849 is64
? i64ArgSignature
: i32ArgSignature
,
854 config
->unresolvedSymbols
== UnresolvedPolicy::ImportDynamic
) {
855 // For PIC code, or when dynamically importing addresses, we create
856 // synthetic functions that apply relocations. These get called from
857 // __wasm_call_ctors before the user-level constructors.
858 WasmSym::applyDataRelocs
= symtab
->addSyntheticFunction(
859 "__wasm_apply_data_relocs",
860 WASM_SYMBOL_VISIBILITY_DEFAULT
| WASM_SYMBOL_EXPORTED
,
861 make
<SyntheticFunction
>(nullSignature
, "__wasm_apply_data_relocs"));
865 static void createOptionalSymbols() {
866 if (config
->relocatable
)
869 WasmSym::dsoHandle
= symtab
->addOptionalDataSymbol("__dso_handle");
872 WasmSym::dataEnd
= symtab
->addOptionalDataSymbol("__data_end");
874 if (!config
->isPic
) {
875 WasmSym::stackLow
= symtab
->addOptionalDataSymbol("__stack_low");
876 WasmSym::stackHigh
= symtab
->addOptionalDataSymbol("__stack_high");
877 WasmSym::globalBase
= symtab
->addOptionalDataSymbol("__global_base");
878 WasmSym::heapBase
= symtab
->addOptionalDataSymbol("__heap_base");
879 WasmSym::heapEnd
= symtab
->addOptionalDataSymbol("__heap_end");
880 WasmSym::definedMemoryBase
= symtab
->addOptionalDataSymbol("__memory_base");
881 WasmSym::definedTableBase
= symtab
->addOptionalDataSymbol("__table_base");
882 if (config
->is64
.value_or(false))
883 WasmSym::definedTableBase32
=
884 symtab
->addOptionalDataSymbol("__table_base32");
887 // For non-shared memory programs we still need to define __tls_base since we
888 // allow object files built with TLS to be linked into single threaded
889 // programs, and such object files can contain references to this symbol.
891 // However, in this case __tls_base is immutable and points directly to the
892 // start of the `.tdata` static segment.
894 // __tls_size and __tls_align are not needed in this case since they are only
895 // needed for __wasm_init_tls (which we do not create in this case).
896 if (!config
->sharedMemory
)
897 WasmSym::tlsBase
= createOptionalGlobal("__tls_base", false);
900 static void processStubLibrariesPreLTO() {
901 log("-- processStubLibrariesPreLTO");
902 for (auto &stub_file
: symtab
->stubFiles
) {
903 LLVM_DEBUG(llvm::dbgs()
904 << "processing stub file: " << stub_file
->getName() << "\n");
905 for (auto [name
, deps
]: stub_file
->symbolDependencies
) {
906 auto* sym
= symtab
->find(name
);
907 // If the symbol is not present at all (yet), or if it is present but
908 // undefined, then mark the dependent symbols as used by a regular
909 // object so they will be preserved and exported by the LTO process.
910 if (!sym
|| sym
->isUndefined()) {
911 for (const auto dep
: deps
) {
912 auto* needed
= symtab
->find(dep
);
914 needed
->isUsedInRegularObj
= true;
922 static void processStubLibraries() {
923 log("-- processStubLibraries");
924 bool depsAdded
= false;
927 for (auto &stub_file
: symtab
->stubFiles
) {
928 LLVM_DEBUG(llvm::dbgs()
929 << "processing stub file: " << stub_file
->getName() << "\n");
930 for (auto [name
, deps
]: stub_file
->symbolDependencies
) {
931 auto* sym
= symtab
->find(name
);
932 if (!sym
|| !sym
->isUndefined()) {
933 if (sym
&& sym
->traced
)
934 message(toString(stub_file
) + ": stub symbol not needed: " + name
);
936 LLVM_DEBUG(llvm::dbgs() << "stub symbol not needed: `" << name
<< "`\n");
939 // The first stub library to define a given symbol sets this and
940 // definitions in later stub libraries are ignored.
941 if (sym
->forceImport
)
942 continue; // Already handled
943 sym
->forceImport
= true;
945 message(toString(stub_file
) + ": importing " + name
);
947 LLVM_DEBUG(llvm::dbgs()
948 << toString(stub_file
) << ": importing " << name
<< "\n");
949 for (const auto dep
: deps
) {
950 auto* needed
= symtab
->find(dep
);
952 error(toString(stub_file
) + ": undefined symbol: " + dep
+
953 ". Required by " + toString(*sym
));
954 } else if (needed
->isUndefined()) {
955 error(toString(stub_file
) +
956 ": undefined symbol: " + toString(*needed
) +
957 ". Required by " + toString(*sym
));
960 message(toString(stub_file
) + ": exported " + toString(*needed
) +
961 " due to import of " + name
);
963 LLVM_DEBUG(llvm::dbgs()
964 << "force export: " << toString(*needed
) << "\n");
965 needed
->forceExport
= true;
966 if (auto *lazy
= dyn_cast
<LazySymbol
>(needed
)) {
969 if (!config
->whyExtract
.empty())
970 config
->whyExtractRecords
.emplace_back(stub_file
->getName(),
971 sym
->getFile(), *sym
);
979 log("-- done processStubLibraries");
982 // Reconstructs command line arguments so that so that you can re-run
983 // the same command with the same inputs. This is for --reproduce.
984 static std::string
createResponseFile(const opt::InputArgList
&args
) {
986 raw_svector_ostream
os(data
);
988 // Copy the command line to the output while rewriting paths.
989 for (auto *arg
: args
) {
990 switch (arg
->getOption().getID()) {
994 os
<< quote(relativeToRoot(arg
->getValue())) << "\n";
997 // If -o path contains directories, "lld @response.txt" will likely
998 // fail because the archive we are creating doesn't contain empty
999 // directories for the output path (-o doesn't create directories).
1000 // Strip directories to prevent the issue.
1001 os
<< "-o " << quote(sys::path::filename(arg
->getValue())) << "\n";
1004 os
<< toString(*arg
) << "\n";
1007 return std::string(data
.str());
1010 // The --wrap option is a feature to rename symbols so that you can write
1011 // wrappers for existing functions. If you pass `-wrap=foo`, all
1012 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1013 // expected to write `wrap_foo` function as a wrapper). The original
1014 // symbol becomes accessible as `real_foo`, so you can call that from your
1017 // This data structure is instantiated for each -wrap option.
1018 struct WrappedSymbol
{
1024 static Symbol
*addUndefined(StringRef name
) {
1025 return symtab
->addUndefinedFunction(name
, std::nullopt
, std::nullopt
,
1026 WASM_SYMBOL_UNDEFINED
, nullptr, nullptr,
1030 // Handles -wrap option.
1032 // This function instantiates wrapper symbols. At this point, they seem
1033 // like they are not being used at all, so we explicitly set some flags so
1034 // that LTO won't eliminate them.
1035 static std::vector
<WrappedSymbol
> addWrappedSymbols(opt::InputArgList
&args
) {
1036 std::vector
<WrappedSymbol
> v
;
1037 DenseSet
<StringRef
> seen
;
1039 for (auto *arg
: args
.filtered(OPT_wrap
)) {
1040 StringRef name
= arg
->getValue();
1041 if (!seen
.insert(name
).second
)
1044 Symbol
*sym
= symtab
->find(name
);
1048 Symbol
*real
= addUndefined(saver().save("__real_" + name
));
1049 Symbol
*wrap
= addUndefined(saver().save("__wrap_" + name
));
1050 v
.push_back({sym
, real
, wrap
});
1052 // We want to tell LTO not to inline symbols to be overwritten
1053 // because LTO doesn't know the final symbol contents after renaming.
1054 real
->canInline
= false;
1055 sym
->canInline
= false;
1057 // Tell LTO not to eliminate these symbols.
1058 sym
->isUsedInRegularObj
= true;
1059 wrap
->isUsedInRegularObj
= true;
1060 real
->isUsedInRegularObj
= false;
1065 // Do renaming for -wrap by updating pointers to symbols.
1067 // When this function is executed, only InputFiles and symbol table
1068 // contain pointers to symbol objects. We visit them to replace pointers,
1069 // so that wrapped symbols are swapped as instructed by the command line.
1070 static void wrapSymbols(ArrayRef
<WrappedSymbol
> wrapped
) {
1071 DenseMap
<Symbol
*, Symbol
*> map
;
1072 for (const WrappedSymbol
&w
: wrapped
) {
1073 map
[w
.sym
] = w
.wrap
;
1074 map
[w
.real
] = w
.sym
;
1077 // Update pointers in input files.
1078 parallelForEach(symtab
->objectFiles
, [&](InputFile
*file
) {
1079 MutableArrayRef
<Symbol
*> syms
= file
->getMutableSymbols();
1080 for (size_t i
= 0, e
= syms
.size(); i
!= e
; ++i
)
1081 if (Symbol
*s
= map
.lookup(syms
[i
]))
1085 // Update pointers in the symbol table.
1086 for (const WrappedSymbol
&w
: wrapped
)
1087 symtab
->wrap(w
.sym
, w
.real
, w
.wrap
);
1090 static void splitSections() {
1091 // splitIntoPieces needs to be called on each MergeInputChunk
1092 // before calling finalizeContents().
1093 LLVM_DEBUG(llvm::dbgs() << "splitSections\n");
1094 parallelForEach(symtab
->objectFiles
, [](ObjFile
*file
) {
1095 for (InputChunk
*seg
: file
->segments
) {
1096 if (auto *s
= dyn_cast
<MergeInputChunk
>(seg
))
1097 s
->splitIntoPieces();
1099 for (InputChunk
*sec
: file
->customSections
) {
1100 if (auto *s
= dyn_cast
<MergeInputChunk
>(sec
))
1101 s
->splitIntoPieces();
1106 static bool isKnownZFlag(StringRef s
) {
1107 // For now, we only support a very limited set of -z flags
1108 return s
.starts_with("stack-size=");
1111 // Report a warning for an unknown -z option.
1112 static void checkZOptions(opt::InputArgList
&args
) {
1113 for (auto *arg
: args
.filtered(OPT_z
))
1114 if (!isKnownZFlag(arg
->getValue()))
1115 warn("unknown -z value: " + StringRef(arg
->getValue()));
1118 void LinkerDriver::linkerMain(ArrayRef
<const char *> argsArr
) {
1119 WasmOptTable parser
;
1120 opt::InputArgList args
= parser
.parse(argsArr
.slice(1));
1122 // Interpret these flags early because error()/warn() depend on them.
1123 errorHandler().errorLimit
= args::getInteger(args
, OPT_error_limit
, 20);
1124 errorHandler().fatalWarnings
=
1125 args
.hasFlag(OPT_fatal_warnings
, OPT_no_fatal_warnings
, false);
1126 checkZOptions(args
);
1129 if (args
.hasArg(OPT_help
)) {
1130 parser
.printHelp(lld::outs(),
1131 (std::string(argsArr
[0]) + " [options] file...").c_str(),
1132 "LLVM Linker", false);
1137 if (args
.hasArg(OPT_version
) || args
.hasArg(OPT_v
)) {
1138 lld::outs() << getLLDVersion() << "\n";
1142 // Handle --reproduce
1143 if (const char *path
= getReproduceOption(args
)) {
1144 Expected
<std::unique_ptr
<TarWriter
>> errOrWriter
=
1145 TarWriter::create(path
, path::stem(path
));
1147 tar
= std::move(*errOrWriter
);
1148 tar
->append("response.txt", createResponseFile(args
));
1149 tar
->append("version.txt", getLLDVersion() + "\n");
1151 error("--reproduce: " + toString(errOrWriter
.takeError()));
1155 // Parse and evaluate -mllvm options.
1156 std::vector
<const char *> v
;
1157 v
.push_back("wasm-ld (LLVM option parsing)");
1158 for (auto *arg
: args
.filtered(OPT_mllvm
))
1159 v
.push_back(arg
->getValue());
1160 cl::ResetAllOptionOccurrences();
1161 cl::ParseCommandLineOptions(v
.size(), v
.data());
1174 if (auto *arg
= args
.getLastArg(OPT_allow_undefined_file
))
1175 readImportFile(arg
->getValue());
1177 // Fail early if the output file or map file is not writable. If a user has a
1178 // long link, e.g. due to a large LTO link, they do not wish to run it and
1179 // find that it failed because there was a mistake in their command-line.
1180 if (auto e
= tryCreateFile(config
->outputFile
))
1181 error("cannot open output file " + config
->outputFile
+ ": " + e
.message());
1182 if (auto e
= tryCreateFile(config
->mapFile
))
1183 error("cannot open map file " + config
->mapFile
+ ": " + e
.message());
1187 // Handle --trace-symbol.
1188 for (auto *arg
: args
.filtered(OPT_trace_symbol
))
1189 symtab
->trace(arg
->getValue());
1191 for (auto *arg
: args
.filtered(OPT_export_if_defined
))
1192 config
->exportedSymbols
.insert(arg
->getValue());
1194 for (auto *arg
: args
.filtered(OPT_export
)) {
1195 config
->exportedSymbols
.insert(arg
->getValue());
1196 config
->requiredExports
.push_back(arg
->getValue());
1199 createSyntheticSymbols();
1201 // Add all files to the symbol table. This will add almost all
1202 // symbols that we need to the symbol table.
1203 for (InputFile
*f
: files
)
1208 // Handle the `--undefined <sym>` options.
1209 for (auto *arg
: args
.filtered(OPT_undefined
))
1210 handleUndefined(arg
->getValue(), "<internal>");
1212 // Handle the `--export <sym>` options
1213 // This works like --undefined but also exports the symbol if its found
1214 for (auto &iter
: config
->exportedSymbols
)
1215 handleUndefined(iter
.first(), "--export");
1217 Symbol
*entrySym
= nullptr;
1218 if (!config
->relocatable
&& !config
->entry
.empty()) {
1219 entrySym
= handleUndefined(config
->entry
, "--entry");
1220 if (entrySym
&& entrySym
->isDefined())
1221 entrySym
->forceExport
= true;
1223 error("entry symbol not defined (pass --no-entry to suppress): " +
1227 // If the user code defines a `__wasm_call_dtors` function, remember it so
1228 // that we can call it from the command export wrappers. Unlike
1229 // `__wasm_call_ctors` which we synthesize, `__wasm_call_dtors` is defined
1230 // by libc/etc., because destructors are registered dynamically with
1231 // `__cxa_atexit` and friends.
1232 if (!config
->relocatable
&& !config
->shared
&&
1233 !WasmSym::callCtors
->isUsedInRegularObj
&&
1234 WasmSym::callCtors
->getName() != config
->entry
&&
1235 !config
->exportedSymbols
.count(WasmSym::callCtors
->getName())) {
1236 if (Symbol
*callDtors
=
1237 handleUndefined("__wasm_call_dtors", "<internal>")) {
1238 if (auto *callDtorsFunc
= dyn_cast
<DefinedFunction
>(callDtors
)) {
1239 if (callDtorsFunc
->signature
&&
1240 (!callDtorsFunc
->signature
->Params
.empty() ||
1241 !callDtorsFunc
->signature
->Returns
.empty())) {
1242 error("__wasm_call_dtors must have no argument or return values");
1244 WasmSym::callDtors
= callDtorsFunc
;
1246 error("__wasm_call_dtors must be a function");
1254 // Create wrapped symbols for -wrap option.
1255 std::vector
<WrappedSymbol
> wrapped
= addWrappedSymbols(args
);
1257 // If any of our inputs are bitcode files, the LTO code generator may create
1258 // references to certain library functions that might not be explicit in the
1259 // bitcode file's symbol table. If any of those library functions are defined
1260 // in a bitcode file in an archive member, we need to arrange to use LTO to
1261 // compile those archive members by adding them to the link beforehand.
1263 // We only need to add libcall symbols to the link before LTO if the symbol's
1264 // definition is in bitcode. Any other required libcall symbols will be added
1265 // to the link after LTO when we add the LTO object file to the link.
1266 if (!symtab
->bitcodeFiles
.empty())
1267 for (auto *s
: lto::LTO::getRuntimeLibcallSymbols())
1272 // We process the stub libraries once beofore LTO to ensure that any possible
1273 // required exports are preserved by the LTO process.
1274 processStubLibrariesPreLTO();
1276 // Do link-time optimization if given files are LLVM bitcode files.
1277 // This compiles bitcode files into real object files.
1278 symtab
->compileBitcodeFiles();
1282 // The LTO process can generate new undefined symbols, specifically libcall
1283 // functions. Because those symbols might be declared in a stub library we
1284 // need the process the stub libraries once again after LTO to handle all
1285 // undefined symbols, including ones that didn't exist prior to LTO.
1286 processStubLibraries();
1290 createOptionalSymbols();
1292 // Resolve any variant symbols that were created due to signature
1294 symtab
->handleSymbolVariants();
1298 // Apply symbol renames for -wrap.
1299 if (!wrapped
.empty())
1300 wrapSymbols(wrapped
);
1302 for (auto &iter
: config
->exportedSymbols
) {
1303 Symbol
*sym
= symtab
->find(iter
.first());
1304 if (sym
&& sym
->isDefined())
1305 sym
->forceExport
= true;
1308 if (!config
->relocatable
&& !config
->isPic
) {
1309 // Add synthetic dummies for weak undefined functions. Must happen
1310 // after LTO otherwise functions may not yet have signatures.
1311 symtab
->handleWeakUndefines();
1315 entrySym
->setHidden(false);
1320 // Split WASM_SEG_FLAG_STRINGS sections into pieces in preparation for garbage
1324 // Any remaining lazy symbols should be demoted to Undefined
1325 demoteLazySymbols();
1327 // Do size optimizations: garbage collection
1330 // Provide the indirect function table if needed.
1331 WasmSym::indirectFunctionTable
=
1332 symtab
->resolveIndirectFunctionTable(/*required =*/false);
1337 // Write the result to the file.
1341 } // namespace lld::wasm