Re-land [LLD] Allow usage of LLD as a library
[llvm-project.git] / lld / wasm / Driver.cpp
blob8e2c93772abda60ba41d9e483e5710812679081d
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 //===----------------------------------------------------------------------===//
9 #include "lld/Common/Driver.h"
10 #include "Config.h"
11 #include "InputChunks.h"
12 #include "InputElement.h"
13 #include "MarkLive.h"
14 #include "SymbolTable.h"
15 #include "Writer.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"
36 #include <optional>
38 #define DEBUG_TYPE "lld"
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::sys;
43 using namespace llvm::wasm;
45 namespace lld::wasm {
46 Configuration *config;
48 namespace {
50 // Create enum with OPT_xxx values for each option in Options.td
51 enum {
52 OPT_INVALID = 0,
53 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
54 #include "Options.inc"
55 #undef OPTION
58 // This function is called on startup. We need this for LTO since
59 // LTO calls LLVM functions to compile bitcode files to native code.
60 // Technically this can be delayed until we read bitcode files, but
61 // we don't bother to do lazily because the initialization is fast.
62 static void initLLVM() {
63 InitializeAllTargets();
64 InitializeAllTargetMCs();
65 InitializeAllAsmPrinters();
66 InitializeAllAsmParsers();
69 class LinkerDriver {
70 public:
71 void linkerMain(ArrayRef<const char *> argsArr);
73 private:
74 void createFiles(opt::InputArgList &args);
75 void addFile(StringRef path);
76 void addLibrary(StringRef name);
78 // True if we are in --whole-archive and --no-whole-archive.
79 bool inWholeArchive = false;
81 std::vector<InputFile *> files;
83 } // anonymous namespace
85 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
86 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
87 // This driver-specific context will be freed later by unsafeLldMain().
88 auto *ctx = new CommonLinkerContext;
90 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
91 ctx->e.logName = args::getFilenameWithoutExe(args[0]);
92 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
93 "-error-limit=0 to see all errors)";
95 config = make<Configuration>();
96 symtab = make<SymbolTable>();
98 initLLVM();
99 LinkerDriver().linkerMain(args);
101 return errorCount() == 0;
104 // Create prefix string literals used in Options.td
105 #define PREFIX(NAME, VALUE) \
106 static constexpr StringLiteral NAME##_init[] = VALUE; \
107 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
108 std::size(NAME##_init) - 1);
109 #include "Options.inc"
110 #undef PREFIX
112 // Create table mapping all options defined in Options.td
113 static constexpr opt::OptTable::Info optInfo[] = {
114 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
115 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
116 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
117 #include "Options.inc"
118 #undef OPTION
121 namespace {
122 class WasmOptTable : public opt::GenericOptTable {
123 public:
124 WasmOptTable() : opt::GenericOptTable(optInfo) {}
125 opt::InputArgList parse(ArrayRef<const char *> argv);
127 } // namespace
129 // Set color diagnostics according to -color-diagnostics={auto,always,never}
130 // or -no-color-diagnostics flags.
131 static void handleColorDiagnostics(opt::InputArgList &args) {
132 auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
133 OPT_no_color_diagnostics);
134 if (!arg)
135 return;
136 if (arg->getOption().getID() == OPT_color_diagnostics) {
137 lld::errs().enable_colors(true);
138 } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
139 lld::errs().enable_colors(false);
140 } else {
141 StringRef s = arg->getValue();
142 if (s == "always")
143 lld::errs().enable_colors(true);
144 else if (s == "never")
145 lld::errs().enable_colors(false);
146 else if (s != "auto")
147 error("unknown option: --color-diagnostics=" + s);
151 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
152 if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
153 StringRef s = arg->getValue();
154 if (s != "windows" && s != "posix")
155 error("invalid response file quoting: " + s);
156 if (s == "windows")
157 return cl::TokenizeWindowsCommandLine;
158 return cl::TokenizeGNUCommandLine;
160 if (Triple(sys::getProcessTriple()).isOSWindows())
161 return cl::TokenizeWindowsCommandLine;
162 return cl::TokenizeGNUCommandLine;
165 // Find a file by concatenating given paths.
166 static std::optional<std::string> findFile(StringRef path1,
167 const Twine &path2) {
168 SmallString<128> s;
169 path::append(s, path1, path2);
170 if (fs::exists(s))
171 return std::string(s);
172 return std::nullopt;
175 opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> argv) {
176 SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
178 unsigned missingIndex;
179 unsigned missingCount;
181 // We need to get the quoting style for response files before parsing all
182 // options so we parse here before and ignore all the options but
183 // --rsp-quoting.
184 opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
186 // Expand response files (arguments in the form of @<filename>)
187 // and then parse the argument again.
188 cl::ExpandResponseFiles(saver(), getQuotingStyle(args), vec);
189 args = this->ParseArgs(vec, missingIndex, missingCount);
191 handleColorDiagnostics(args);
192 if (missingCount)
193 error(Twine(args.getArgString(missingIndex)) + ": missing argument");
195 for (auto *arg : args.filtered(OPT_UNKNOWN))
196 error("unknown argument: " + arg->getAsString(args));
197 return args;
200 // Currently we allow a ".imports" to live alongside a library. This can
201 // be used to specify a list of symbols which can be undefined at link
202 // time (imported from the environment. For example libc.a include an
203 // import file that lists the syscall functions it relies on at runtime.
204 // In the long run this information would be better stored as a symbol
205 // attribute/flag in the object file itself.
206 // See: https://github.com/WebAssembly/tool-conventions/issues/35
207 static void readImportFile(StringRef filename) {
208 if (std::optional<MemoryBufferRef> buf = readFile(filename))
209 for (StringRef sym : args::getLines(*buf))
210 config->allowUndefinedSymbols.insert(sym);
213 // Returns slices of MB by parsing MB as an archive file.
214 // Each slice consists of a member file in the archive.
215 std::vector<MemoryBufferRef> static getArchiveMembers(MemoryBufferRef mb) {
216 std::unique_ptr<Archive> file =
217 CHECK(Archive::create(mb),
218 mb.getBufferIdentifier() + ": failed to parse archive");
220 std::vector<MemoryBufferRef> v;
221 Error err = Error::success();
222 for (const Archive::Child &c : file->children(err)) {
223 MemoryBufferRef mbref =
224 CHECK(c.getMemoryBufferRef(),
225 mb.getBufferIdentifier() +
226 ": could not get the buffer for a child of the archive");
227 v.push_back(mbref);
229 if (err)
230 fatal(mb.getBufferIdentifier() +
231 ": Archive::children failed: " + toString(std::move(err)));
233 // Take ownership of memory buffers created for members of thin archives.
234 for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
235 make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
237 return v;
240 void LinkerDriver::addFile(StringRef path) {
241 std::optional<MemoryBufferRef> buffer = readFile(path);
242 if (!buffer)
243 return;
244 MemoryBufferRef mbref = *buffer;
246 switch (identify_magic(mbref.getBuffer())) {
247 case file_magic::archive: {
248 SmallString<128> importFile = path;
249 path::replace_extension(importFile, ".imports");
250 if (fs::exists(importFile))
251 readImportFile(importFile.str());
253 // Handle -whole-archive.
254 if (inWholeArchive) {
255 for (MemoryBufferRef &m : getArchiveMembers(mbref)) {
256 auto *object = createObjectFile(m, path);
257 // Mark object as live; object members are normally not
258 // live by default but -whole-archive is designed to treat
259 // them as such.
260 object->markLive();
261 files.push_back(object);
264 return;
267 std::unique_ptr<Archive> file =
268 CHECK(Archive::create(mbref), path + ": failed to parse archive");
270 if (!file->isEmpty() && !file->hasSymbolTable()) {
271 error(mbref.getBufferIdentifier() +
272 ": archive has no index; run ranlib to add one");
275 files.push_back(make<ArchiveFile>(mbref));
276 return;
278 case file_magic::bitcode:
279 case file_magic::wasm_object:
280 files.push_back(createObjectFile(mbref));
281 break;
282 case file_magic::unknown:
283 if (mbref.getBuffer().starts_with("#STUB")) {
284 files.push_back(make<StubFile>(mbref));
285 break;
287 [[fallthrough]];
288 default:
289 error("unknown file type: " + mbref.getBufferIdentifier());
293 static std::optional<std::string> findFromSearchPaths(StringRef path) {
294 for (StringRef dir : config->searchPaths)
295 if (std::optional<std::string> s = findFile(dir, path))
296 return s;
297 return std::nullopt;
300 // This is for -l<basename>. We'll look for lib<basename>.a from
301 // search paths.
302 static std::optional<std::string> searchLibraryBaseName(StringRef name) {
303 for (StringRef dir : config->searchPaths) {
304 // Currently we don't enable dynamic linking at all unless -shared or -pie
305 // are used, so don't even look for .so files in that case..
306 if (config->isPic && !config->isStatic)
307 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".so"))
308 return s;
309 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".a"))
310 return s;
312 return std::nullopt;
315 // This is for -l<namespec>.
316 static std::optional<std::string> searchLibrary(StringRef name) {
317 if (name.starts_with(":"))
318 return findFromSearchPaths(name.substr(1));
319 return searchLibraryBaseName(name);
322 // Add a given library by searching it from input search paths.
323 void LinkerDriver::addLibrary(StringRef name) {
324 if (std::optional<std::string> path = searchLibrary(name))
325 addFile(saver().save(*path));
326 else
327 error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
330 void LinkerDriver::createFiles(opt::InputArgList &args) {
331 for (auto *arg : args) {
332 switch (arg->getOption().getID()) {
333 case OPT_library:
334 addLibrary(arg->getValue());
335 break;
336 case OPT_INPUT:
337 addFile(arg->getValue());
338 break;
339 case OPT_Bstatic:
340 config->isStatic = true;
341 break;
342 case OPT_Bdynamic:
343 config->isStatic = false;
344 break;
345 case OPT_whole_archive:
346 inWholeArchive = true;
347 break;
348 case OPT_no_whole_archive:
349 inWholeArchive = false;
350 break;
353 if (files.empty() && errorCount() == 0)
354 error("no input files");
357 static StringRef getEntry(opt::InputArgList &args) {
358 auto *arg = args.getLastArg(OPT_entry, OPT_no_entry);
359 if (!arg) {
360 if (args.hasArg(OPT_relocatable))
361 return "";
362 if (args.hasArg(OPT_shared))
363 return "__wasm_call_ctors";
364 return "_start";
366 if (arg->getOption().getID() == OPT_no_entry)
367 return "";
368 return arg->getValue();
371 // Determines what we should do if there are remaining unresolved
372 // symbols after the name resolution.
373 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
374 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
375 OPT_warn_unresolved_symbols, true)
376 ? UnresolvedPolicy::ReportError
377 : UnresolvedPolicy::Warn;
379 if (auto *arg = args.getLastArg(OPT_unresolved_symbols)) {
380 StringRef s = arg->getValue();
381 if (s == "ignore-all")
382 return UnresolvedPolicy::Ignore;
383 if (s == "import-dynamic")
384 return UnresolvedPolicy::ImportDynamic;
385 if (s == "report-all")
386 return errorOrWarn;
387 error("unknown --unresolved-symbols value: " + s);
390 return errorOrWarn;
393 // Parse --build-id or --build-id=<style>. We handle "tree" as a
394 // synonym for "sha1" because all our hash functions including
395 // -build-id=sha1 are actually tree hashes for performance reasons.
396 static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>
397 getBuildId(opt::InputArgList &args) {
398 auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
399 if (!arg)
400 return {BuildIdKind::None, {}};
402 if (arg->getOption().getID() == OPT_build_id)
403 return {BuildIdKind::Fast, {}};
405 StringRef s = arg->getValue();
406 if (s == "fast")
407 return {BuildIdKind::Fast, {}};
408 if (s == "sha1" || s == "tree")
409 return {BuildIdKind::Sha1, {}};
410 if (s == "uuid")
411 return {BuildIdKind::Uuid, {}};
412 if (s.starts_with("0x"))
413 return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
415 if (s != "none")
416 error("unknown --build-id style: " + s);
417 return {BuildIdKind::None, {}};
420 // Initializes Config members by the command line options.
421 static void readConfigs(opt::InputArgList &args) {
422 config->bsymbolic = args.hasArg(OPT_Bsymbolic);
423 config->checkFeatures =
424 args.hasFlag(OPT_check_features, OPT_no_check_features, true);
425 config->compressRelocations = args.hasArg(OPT_compress_relocations);
426 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
427 config->disableVerify = args.hasArg(OPT_disable_verify);
428 config->emitRelocs = args.hasArg(OPT_emit_relocs);
429 config->experimentalPic = args.hasArg(OPT_experimental_pic);
430 config->entry = getEntry(args);
431 config->exportAll = args.hasArg(OPT_export_all);
432 config->exportTable = args.hasArg(OPT_export_table);
433 config->growableTable = args.hasArg(OPT_growable_table);
435 if (args.hasArg(OPT_import_memory_with_name)) {
436 config->memoryImport =
437 args.getLastArgValue(OPT_import_memory_with_name).split(",");
438 } else if (args.hasArg(OPT_import_memory)) {
439 config->memoryImport =
440 std::pair<llvm::StringRef, llvm::StringRef>(defaultModule, memoryName);
441 } else {
442 config->memoryImport =
443 std::optional<std::pair<llvm::StringRef, llvm::StringRef>>();
446 if (args.hasArg(OPT_export_memory_with_name)) {
447 config->memoryExport =
448 args.getLastArgValue(OPT_export_memory_with_name);
449 } else if (args.hasArg(OPT_export_memory)) {
450 config->memoryExport = memoryName;
451 } else {
452 config->memoryExport = std::optional<llvm::StringRef>();
455 config->sharedMemory = args.hasArg(OPT_shared_memory);
456 config->importTable = args.hasArg(OPT_import_table);
457 config->importUndefined = args.hasArg(OPT_import_undefined);
458 config->ltoo = args::getInteger(args, OPT_lto_O, 2);
459 if (config->ltoo > 3)
460 error("invalid optimization level for LTO: " + Twine(config->ltoo));
461 unsigned ltoCgo =
462 args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));
463 if (auto level = CodeGenOpt::getLevel(ltoCgo))
464 config->ltoCgo = *level;
465 else
466 error("invalid codegen optimization level for LTO: " + Twine(ltoCgo));
467 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
468 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
469 config->mapFile = args.getLastArgValue(OPT_Map);
470 config->optimize = args::getInteger(args, OPT_O, 1);
471 config->outputFile = args.getLastArgValue(OPT_o);
472 config->relocatable = args.hasArg(OPT_relocatable);
473 config->gcSections =
474 args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !config->relocatable);
475 config->mergeDataSegments =
476 args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments,
477 !config->relocatable);
478 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
479 config->printGcSections =
480 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
481 config->saveTemps = args.hasArg(OPT_save_temps);
482 config->searchPaths = args::getStrings(args, OPT_library_path);
483 config->shared = args.hasArg(OPT_shared);
484 config->stripAll = args.hasArg(OPT_strip_all);
485 config->stripDebug = args.hasArg(OPT_strip_debug);
486 config->stackFirst = args.hasArg(OPT_stack_first);
487 config->trace = args.hasArg(OPT_trace);
488 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
489 config->thinLTOCachePolicy = CHECK(
490 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
491 "--thinlto-cache-policy: invalid cache policy");
492 config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
493 config->whyExtract = args.getLastArgValue(OPT_why_extract);
494 errorHandler().verbose = args.hasArg(OPT_verbose);
495 LLVM_DEBUG(errorHandler().verbose = true);
497 config->initialMemory = args::getInteger(args, OPT_initial_memory, 0);
498 config->globalBase = args::getInteger(args, OPT_global_base, 0);
499 config->maxMemory = args::getInteger(args, OPT_max_memory, 0);
500 config->zStackSize =
501 args::getZOptionValue(args, OPT_z, "stack-size", WasmPageSize);
503 // Default value of exportDynamic depends on `-shared`
504 config->exportDynamic =
505 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, config->shared);
507 // Parse wasm32/64.
508 if (auto *arg = args.getLastArg(OPT_m)) {
509 StringRef s = arg->getValue();
510 if (s == "wasm32")
511 config->is64 = false;
512 else if (s == "wasm64")
513 config->is64 = true;
514 else
515 error("invalid target architecture: " + s);
518 // --threads= takes a positive integer and provides the default value for
519 // --thinlto-jobs=.
520 if (auto *arg = args.getLastArg(OPT_threads)) {
521 StringRef v(arg->getValue());
522 unsigned threads = 0;
523 if (!llvm::to_integer(v, threads, 0) || threads == 0)
524 error(arg->getSpelling() + ": expected a positive integer, but got '" +
525 arg->getValue() + "'");
526 parallel::strategy = hardware_concurrency(threads);
527 config->thinLTOJobs = v;
529 if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
530 config->thinLTOJobs = arg->getValue();
532 if (auto *arg = args.getLastArg(OPT_features)) {
533 config->features =
534 std::optional<std::vector<std::string>>(std::vector<std::string>());
535 for (StringRef s : arg->getValues())
536 config->features->push_back(std::string(s));
539 if (auto *arg = args.getLastArg(OPT_extra_features)) {
540 config->extraFeatures =
541 std::optional<std::vector<std::string>>(std::vector<std::string>());
542 for (StringRef s : arg->getValues())
543 config->extraFeatures->push_back(std::string(s));
546 // Legacy --allow-undefined flag which is equivalent to
547 // --unresolve-symbols=ignore + --import-undefined
548 if (args.hasArg(OPT_allow_undefined)) {
549 config->importUndefined = true;
550 config->unresolvedSymbols = UnresolvedPolicy::Ignore;
553 if (args.hasArg(OPT_print_map))
554 config->mapFile = "-";
556 std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
559 // Some Config members do not directly correspond to any particular
560 // command line options, but computed based on other Config values.
561 // This function initialize such members. See Config.h for the details
562 // of these values.
563 static void setConfigs() {
564 config->isPic = config->pie || config->shared;
566 if (config->isPic) {
567 if (config->exportTable)
568 error("-shared/-pie is incompatible with --export-table");
569 config->importTable = true;
572 if (config->relocatable) {
573 if (config->exportTable)
574 error("--relocatable is incompatible with --export-table");
575 if (config->growableTable)
576 error("--relocatable is incompatible with --growable-table");
577 // Ignore any --import-table, as it's redundant.
578 config->importTable = true;
581 if (config->shared) {
582 if (config->memoryExport.has_value()) {
583 error("--export-memory is incompatible with --shared");
585 if (!config->memoryImport.has_value()) {
586 config->memoryImport =
587 std::pair<llvm::StringRef, llvm::StringRef>(defaultModule, memoryName);
589 config->importUndefined = true;
592 // If neither export-memory nor import-memory is specified, default to
593 // exporting memory under its default name.
594 if (!config->memoryExport.has_value() && !config->memoryImport.has_value()) {
595 config->memoryExport = memoryName;
599 // Some command line options or some combinations of them are not allowed.
600 // This function checks for such errors.
601 static void checkOptions(opt::InputArgList &args) {
602 if (!config->stripDebug && !config->stripAll && config->compressRelocations)
603 error("--compress-relocations is incompatible with output debug"
604 " information. Please pass --strip-debug or --strip-all");
606 if (config->ltoPartitions == 0)
607 error("--lto-partitions: number of threads must be > 0");
608 if (!get_threadpool_strategy(config->thinLTOJobs))
609 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
611 if (config->pie && config->shared)
612 error("-shared and -pie may not be used together");
614 if (config->outputFile.empty())
615 error("no output file specified");
617 if (config->importTable && config->exportTable)
618 error("--import-table and --export-table may not be used together");
620 if (config->relocatable) {
621 if (!config->entry.empty())
622 error("entry point specified for relocatable output file");
623 if (config->gcSections)
624 error("-r and --gc-sections may not be used together");
625 if (config->compressRelocations)
626 error("-r -and --compress-relocations may not be used together");
627 if (args.hasArg(OPT_undefined))
628 error("-r -and --undefined may not be used together");
629 if (config->pie)
630 error("-r and -pie may not be used together");
631 if (config->sharedMemory)
632 error("-r and --shared-memory may not be used together");
633 if (config->globalBase)
634 error("-r and --global-base may not by used together");
637 // To begin to prepare for Module Linking-style shared libraries, start
638 // warning about uses of `-shared` and related flags outside of Experimental
639 // mode, to give anyone using them a heads-up that they will be changing.
641 // Also, warn about flags which request explicit exports.
642 if (!config->experimentalPic) {
643 // -shared will change meaning when Module Linking is implemented.
644 if (config->shared) {
645 warn("creating shared libraries, with -shared, is not yet stable");
648 // -pie will change meaning when Module Linking is implemented.
649 if (config->pie) {
650 warn("creating PIEs, with -pie, is not yet stable");
653 if (config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic) {
654 warn("dynamic imports are not yet stable "
655 "(--unresolved-symbols=import-dynamic)");
659 if (config->bsymbolic && !config->shared) {
660 warn("-Bsymbolic is only meaningful when combined with -shared");
663 if (config->globalBase && config->isPic) {
664 error("--global-base may not be used with -shared/-pie");
668 static const char *getReproduceOption(opt::InputArgList &args) {
669 if (auto *arg = args.getLastArg(OPT_reproduce))
670 return arg->getValue();
671 return getenv("LLD_REPRODUCE");
674 // Force Sym to be entered in the output. Used for -u or equivalent.
675 static Symbol *handleUndefined(StringRef name, const char *option) {
676 Symbol *sym = symtab->find(name);
677 if (!sym)
678 return nullptr;
680 // Since symbol S may not be used inside the program, LTO may
681 // eliminate it. Mark the symbol as "used" to prevent it.
682 sym->isUsedInRegularObj = true;
684 if (auto *lazySym = dyn_cast<LazySymbol>(sym)) {
685 lazySym->fetch();
686 if (!config->whyExtract.empty())
687 config->whyExtractRecords.emplace_back(option, sym->getFile(), *sym);
690 return sym;
693 static void handleLibcall(StringRef name) {
694 Symbol *sym = symtab->find(name);
695 if (!sym)
696 return;
698 if (auto *lazySym = dyn_cast<LazySymbol>(sym)) {
699 MemoryBufferRef mb = lazySym->getMemberBuffer();
700 if (isBitcode(mb)) {
701 if (!config->whyExtract.empty())
702 config->whyExtractRecords.emplace_back("<libcall>", sym->getFile(),
703 *sym);
704 lazySym->fetch();
709 static void writeWhyExtract() {
710 if (config->whyExtract.empty())
711 return;
713 std::error_code ec;
714 raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None);
715 if (ec) {
716 error("cannot open --why-extract= file " + config->whyExtract + ": " +
717 ec.message());
718 return;
721 os << "reference\textracted\tsymbol\n";
722 for (auto &entry : config->whyExtractRecords) {
723 os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
724 << toString(std::get<2>(entry)) << '\n';
728 // Equivalent of demote demoteSharedAndLazySymbols() in the ELF linker
729 static void demoteLazySymbols() {
730 for (Symbol *sym : symtab->symbols()) {
731 if (auto* s = dyn_cast<LazySymbol>(sym)) {
732 if (s->signature) {
733 LLVM_DEBUG(llvm::dbgs()
734 << "demoting lazy func: " << s->getName() << "\n");
735 replaceSymbol<UndefinedFunction>(s, s->getName(), std::nullopt,
736 std::nullopt, WASM_SYMBOL_BINDING_WEAK,
737 s->getFile(), s->signature);
743 static UndefinedGlobal *
744 createUndefinedGlobal(StringRef name, llvm::wasm::WasmGlobalType *type) {
745 auto *sym = cast<UndefinedGlobal>(symtab->addUndefinedGlobal(
746 name, std::nullopt, std::nullopt, WASM_SYMBOL_UNDEFINED, nullptr, type));
747 config->allowUndefinedSymbols.insert(sym->getName());
748 sym->isUsedInRegularObj = true;
749 return sym;
752 static InputGlobal *createGlobal(StringRef name, bool isMutable) {
753 llvm::wasm::WasmGlobal wasmGlobal;
754 bool is64 = config->is64.value_or(false);
755 wasmGlobal.Type = {uint8_t(is64 ? WASM_TYPE_I64 : WASM_TYPE_I32), isMutable};
756 wasmGlobal.InitExpr = intConst(0, is64);
757 wasmGlobal.SymbolName = name;
758 return make<InputGlobal>(wasmGlobal, nullptr);
761 static GlobalSymbol *createGlobalVariable(StringRef name, bool isMutable) {
762 InputGlobal *g = createGlobal(name, isMutable);
763 return symtab->addSyntheticGlobal(name, WASM_SYMBOL_VISIBILITY_HIDDEN, g);
766 static GlobalSymbol *createOptionalGlobal(StringRef name, bool isMutable) {
767 InputGlobal *g = createGlobal(name, isMutable);
768 return symtab->addOptionalGlobalSymbol(name, g);
771 // Create ABI-defined synthetic symbols
772 static void createSyntheticSymbols() {
773 if (config->relocatable)
774 return;
776 static WasmSignature nullSignature = {{}, {}};
777 static WasmSignature i32ArgSignature = {{}, {ValType::I32}};
778 static WasmSignature i64ArgSignature = {{}, {ValType::I64}};
779 static llvm::wasm::WasmGlobalType globalTypeI32 = {WASM_TYPE_I32, false};
780 static llvm::wasm::WasmGlobalType globalTypeI64 = {WASM_TYPE_I64, false};
781 static llvm::wasm::WasmGlobalType mutableGlobalTypeI32 = {WASM_TYPE_I32,
782 true};
783 static llvm::wasm::WasmGlobalType mutableGlobalTypeI64 = {WASM_TYPE_I64,
784 true};
785 WasmSym::callCtors = symtab->addSyntheticFunction(
786 "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
787 make<SyntheticFunction>(nullSignature, "__wasm_call_ctors"));
789 bool is64 = config->is64.value_or(false);
791 if (config->isPic) {
792 WasmSym::stackPointer =
793 createUndefinedGlobal("__stack_pointer", config->is64.value_or(false)
794 ? &mutableGlobalTypeI64
795 : &mutableGlobalTypeI32);
796 // For PIC code, we import two global variables (__memory_base and
797 // __table_base) from the environment and use these as the offset at
798 // which to load our static data and function table.
799 // See:
800 // https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md
801 auto *globalType = is64 ? &globalTypeI64 : &globalTypeI32;
802 WasmSym::memoryBase = createUndefinedGlobal("__memory_base", globalType);
803 WasmSym::tableBase = createUndefinedGlobal("__table_base", globalType);
804 WasmSym::memoryBase->markLive();
805 WasmSym::tableBase->markLive();
806 if (is64) {
807 WasmSym::tableBase32 =
808 createUndefinedGlobal("__table_base32", &globalTypeI32);
809 WasmSym::tableBase32->markLive();
810 } else {
811 WasmSym::tableBase32 = nullptr;
813 } else {
814 // For non-PIC code
815 WasmSym::stackPointer = createGlobalVariable("__stack_pointer", true);
816 WasmSym::stackPointer->markLive();
819 if (config->sharedMemory) {
820 WasmSym::tlsBase = createGlobalVariable("__tls_base", true);
821 WasmSym::tlsSize = createGlobalVariable("__tls_size", false);
822 WasmSym::tlsAlign = createGlobalVariable("__tls_align", false);
823 WasmSym::initTLS = symtab->addSyntheticFunction(
824 "__wasm_init_tls", WASM_SYMBOL_VISIBILITY_HIDDEN,
825 make<SyntheticFunction>(
826 is64 ? i64ArgSignature : i32ArgSignature,
827 "__wasm_init_tls"));
830 if (config->isPic ||
831 config->unresolvedSymbols == UnresolvedPolicy::ImportDynamic) {
832 // For PIC code, or when dynamically importing addresses, we create
833 // synthetic functions that apply relocations. These get called from
834 // __wasm_call_ctors before the user-level constructors.
835 WasmSym::applyDataRelocs = symtab->addSyntheticFunction(
836 "__wasm_apply_data_relocs",
837 WASM_SYMBOL_VISIBILITY_DEFAULT | WASM_SYMBOL_EXPORTED,
838 make<SyntheticFunction>(nullSignature, "__wasm_apply_data_relocs"));
842 static void createOptionalSymbols() {
843 if (config->relocatable)
844 return;
846 WasmSym::dsoHandle = symtab->addOptionalDataSymbol("__dso_handle");
848 if (!config->shared)
849 WasmSym::dataEnd = symtab->addOptionalDataSymbol("__data_end");
851 if (!config->isPic) {
852 WasmSym::stackLow = symtab->addOptionalDataSymbol("__stack_low");
853 WasmSym::stackHigh = symtab->addOptionalDataSymbol("__stack_high");
854 WasmSym::globalBase = symtab->addOptionalDataSymbol("__global_base");
855 WasmSym::heapBase = symtab->addOptionalDataSymbol("__heap_base");
856 WasmSym::heapEnd = symtab->addOptionalDataSymbol("__heap_end");
857 WasmSym::definedMemoryBase = symtab->addOptionalDataSymbol("__memory_base");
858 WasmSym::definedTableBase = symtab->addOptionalDataSymbol("__table_base");
859 if (config->is64.value_or(false))
860 WasmSym::definedTableBase32 =
861 symtab->addOptionalDataSymbol("__table_base32");
864 // For non-shared memory programs we still need to define __tls_base since we
865 // allow object files built with TLS to be linked into single threaded
866 // programs, and such object files can contain references to this symbol.
868 // However, in this case __tls_base is immutable and points directly to the
869 // start of the `.tdata` static segment.
871 // __tls_size and __tls_align are not needed in this case since they are only
872 // needed for __wasm_init_tls (which we do not create in this case).
873 if (!config->sharedMemory)
874 WasmSym::tlsBase = createOptionalGlobal("__tls_base", false);
877 static void processStubLibrariesPreLTO() {
878 log("-- processStubLibrariesPreLTO");
879 for (auto &stub_file : symtab->stubFiles) {
880 LLVM_DEBUG(llvm::dbgs()
881 << "processing stub file: " << stub_file->getName() << "\n");
882 for (auto [name, deps]: stub_file->symbolDependencies) {
883 auto* sym = symtab->find(name);
884 // If the symbol is not present at all (yet), or if it is present but
885 // undefined, then mark the dependent symbols as used by a regular
886 // object so they will be preserved and exported by the LTO process.
887 if (!sym || sym->isUndefined()) {
888 for (const auto dep : deps) {
889 auto* needed = symtab->find(dep);
890 if (needed ) {
891 needed->isUsedInRegularObj = true;
899 static void processStubLibraries() {
900 log("-- processStubLibraries");
901 for (auto &stub_file : symtab->stubFiles) {
902 LLVM_DEBUG(llvm::dbgs()
903 << "processing stub file: " << stub_file->getName() << "\n");
904 for (auto [name, deps]: stub_file->symbolDependencies) {
905 auto* sym = symtab->find(name);
906 if (!sym || !sym->isUndefined()) {
907 LLVM_DEBUG(llvm::dbgs() << "stub symbol not needed: " << name << "\n");
908 continue;
910 // The first stub library to define a given symbol sets this and
911 // definitions in later stub libraries are ignored.
912 if (sym->forceImport)
913 continue; // Already handled
914 sym->forceImport = true;
915 if (sym->traced)
916 message(toString(stub_file) + ": importing " + name);
917 else
918 LLVM_DEBUG(llvm::dbgs()
919 << toString(stub_file) << ": importing " << name << "\n");
920 for (const auto dep : deps) {
921 auto* needed = symtab->find(dep);
922 if (!needed) {
923 error(toString(stub_file) + ": undefined symbol: " + dep +
924 ". Required by " + toString(*sym));
925 } else if (needed->isUndefined()) {
926 error(toString(stub_file) +
927 ": undefined symbol: " + toString(*needed) +
928 ". Required by " + toString(*sym));
929 } else {
930 if (needed->traced)
931 message(toString(stub_file) + ": exported " + toString(*needed) +
932 " due to import of " + name);
933 else
934 LLVM_DEBUG(llvm::dbgs()
935 << "force export: " << toString(*needed) << "\n");
936 needed->forceExport = true;
937 if (auto *lazy = dyn_cast<LazySymbol>(needed)) {
938 lazy->fetch();
939 if (!config->whyExtract.empty())
940 config->whyExtractRecords.emplace_back(stub_file->getName(),
941 sym->getFile(), *sym);
947 log("-- done processStubLibraries");
950 // Reconstructs command line arguments so that so that you can re-run
951 // the same command with the same inputs. This is for --reproduce.
952 static std::string createResponseFile(const opt::InputArgList &args) {
953 SmallString<0> data;
954 raw_svector_ostream os(data);
956 // Copy the command line to the output while rewriting paths.
957 for (auto *arg : args) {
958 switch (arg->getOption().getID()) {
959 case OPT_reproduce:
960 break;
961 case OPT_INPUT:
962 os << quote(relativeToRoot(arg->getValue())) << "\n";
963 break;
964 case OPT_o:
965 // If -o path contains directories, "lld @response.txt" will likely
966 // fail because the archive we are creating doesn't contain empty
967 // directories for the output path (-o doesn't create directories).
968 // Strip directories to prevent the issue.
969 os << "-o " << quote(sys::path::filename(arg->getValue())) << "\n";
970 break;
971 default:
972 os << toString(*arg) << "\n";
975 return std::string(data.str());
978 // The --wrap option is a feature to rename symbols so that you can write
979 // wrappers for existing functions. If you pass `-wrap=foo`, all
980 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
981 // expected to write `wrap_foo` function as a wrapper). The original
982 // symbol becomes accessible as `real_foo`, so you can call that from your
983 // wrapper.
985 // This data structure is instantiated for each -wrap option.
986 struct WrappedSymbol {
987 Symbol *sym;
988 Symbol *real;
989 Symbol *wrap;
992 static Symbol *addUndefined(StringRef name) {
993 return symtab->addUndefinedFunction(name, std::nullopt, std::nullopt,
994 WASM_SYMBOL_UNDEFINED, nullptr, nullptr,
995 false);
998 // Handles -wrap option.
1000 // This function instantiates wrapper symbols. At this point, they seem
1001 // like they are not being used at all, so we explicitly set some flags so
1002 // that LTO won't eliminate them.
1003 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1004 std::vector<WrappedSymbol> v;
1005 DenseSet<StringRef> seen;
1007 for (auto *arg : args.filtered(OPT_wrap)) {
1008 StringRef name = arg->getValue();
1009 if (!seen.insert(name).second)
1010 continue;
1012 Symbol *sym = symtab->find(name);
1013 if (!sym)
1014 continue;
1016 Symbol *real = addUndefined(saver().save("__real_" + name));
1017 Symbol *wrap = addUndefined(saver().save("__wrap_" + name));
1018 v.push_back({sym, real, wrap});
1020 // We want to tell LTO not to inline symbols to be overwritten
1021 // because LTO doesn't know the final symbol contents after renaming.
1022 real->canInline = false;
1023 sym->canInline = false;
1025 // Tell LTO not to eliminate these symbols.
1026 sym->isUsedInRegularObj = true;
1027 wrap->isUsedInRegularObj = true;
1028 real->isUsedInRegularObj = false;
1030 return v;
1033 // Do renaming for -wrap by updating pointers to symbols.
1035 // When this function is executed, only InputFiles and symbol table
1036 // contain pointers to symbol objects. We visit them to replace pointers,
1037 // so that wrapped symbols are swapped as instructed by the command line.
1038 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1039 DenseMap<Symbol *, Symbol *> map;
1040 for (const WrappedSymbol &w : wrapped) {
1041 map[w.sym] = w.wrap;
1042 map[w.real] = w.sym;
1045 // Update pointers in input files.
1046 parallelForEach(symtab->objectFiles, [&](InputFile *file) {
1047 MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1048 for (size_t i = 0, e = syms.size(); i != e; ++i)
1049 if (Symbol *s = map.lookup(syms[i]))
1050 syms[i] = s;
1053 // Update pointers in the symbol table.
1054 for (const WrappedSymbol &w : wrapped)
1055 symtab->wrap(w.sym, w.real, w.wrap);
1058 static void splitSections() {
1059 // splitIntoPieces needs to be called on each MergeInputChunk
1060 // before calling finalizeContents().
1061 LLVM_DEBUG(llvm::dbgs() << "splitSections\n");
1062 parallelForEach(symtab->objectFiles, [](ObjFile *file) {
1063 for (InputChunk *seg : file->segments) {
1064 if (auto *s = dyn_cast<MergeInputChunk>(seg))
1065 s->splitIntoPieces();
1067 for (InputChunk *sec : file->customSections) {
1068 if (auto *s = dyn_cast<MergeInputChunk>(sec))
1069 s->splitIntoPieces();
1074 static bool isKnownZFlag(StringRef s) {
1075 // For now, we only support a very limited set of -z flags
1076 return s.starts_with("stack-size=");
1079 // Report a warning for an unknown -z option.
1080 static void checkZOptions(opt::InputArgList &args) {
1081 for (auto *arg : args.filtered(OPT_z))
1082 if (!isKnownZFlag(arg->getValue()))
1083 warn("unknown -z value: " + StringRef(arg->getValue()));
1086 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1087 WasmOptTable parser;
1088 opt::InputArgList args = parser.parse(argsArr.slice(1));
1090 // Interpret these flags early because error()/warn() depend on them.
1091 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
1092 errorHandler().fatalWarnings =
1093 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
1094 checkZOptions(args);
1096 // Handle --help
1097 if (args.hasArg(OPT_help)) {
1098 parser.printHelp(lld::outs(),
1099 (std::string(argsArr[0]) + " [options] file...").c_str(),
1100 "LLVM Linker", false);
1101 return;
1104 // Handle --version
1105 if (args.hasArg(OPT_version) || args.hasArg(OPT_v)) {
1106 lld::outs() << getLLDVersion() << "\n";
1107 return;
1110 // Handle --reproduce
1111 if (const char *path = getReproduceOption(args)) {
1112 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1113 TarWriter::create(path, path::stem(path));
1114 if (errOrWriter) {
1115 tar = std::move(*errOrWriter);
1116 tar->append("response.txt", createResponseFile(args));
1117 tar->append("version.txt", getLLDVersion() + "\n");
1118 } else {
1119 error("--reproduce: " + toString(errOrWriter.takeError()));
1123 // Parse and evaluate -mllvm options.
1124 std::vector<const char *> v;
1125 v.push_back("wasm-ld (LLVM option parsing)");
1126 for (auto *arg : args.filtered(OPT_mllvm))
1127 v.push_back(arg->getValue());
1128 cl::ResetAllOptionOccurrences();
1129 cl::ParseCommandLineOptions(v.size(), v.data());
1131 readConfigs(args);
1132 setConfigs();
1134 createFiles(args);
1135 if (errorCount())
1136 return;
1138 checkOptions(args);
1139 if (errorCount())
1140 return;
1142 if (auto *arg = args.getLastArg(OPT_allow_undefined_file))
1143 readImportFile(arg->getValue());
1145 // Fail early if the output file or map file is not writable. If a user has a
1146 // long link, e.g. due to a large LTO link, they do not wish to run it and
1147 // find that it failed because there was a mistake in their command-line.
1148 if (auto e = tryCreateFile(config->outputFile))
1149 error("cannot open output file " + config->outputFile + ": " + e.message());
1150 if (auto e = tryCreateFile(config->mapFile))
1151 error("cannot open map file " + config->mapFile + ": " + e.message());
1152 if (errorCount())
1153 return;
1155 // Handle --trace-symbol.
1156 for (auto *arg : args.filtered(OPT_trace_symbol))
1157 symtab->trace(arg->getValue());
1159 for (auto *arg : args.filtered(OPT_export_if_defined))
1160 config->exportedSymbols.insert(arg->getValue());
1162 for (auto *arg : args.filtered(OPT_export)) {
1163 config->exportedSymbols.insert(arg->getValue());
1164 config->requiredExports.push_back(arg->getValue());
1167 createSyntheticSymbols();
1169 // Add all files to the symbol table. This will add almost all
1170 // symbols that we need to the symbol table.
1171 for (InputFile *f : files)
1172 symtab->addFile(f);
1173 if (errorCount())
1174 return;
1176 // Handle the `--undefined <sym>` options.
1177 for (auto *arg : args.filtered(OPT_undefined))
1178 handleUndefined(arg->getValue(), "<internal>");
1180 // Handle the `--export <sym>` options
1181 // This works like --undefined but also exports the symbol if its found
1182 for (auto &iter : config->exportedSymbols)
1183 handleUndefined(iter.first(), "--export");
1185 Symbol *entrySym = nullptr;
1186 if (!config->relocatable && !config->entry.empty()) {
1187 entrySym = handleUndefined(config->entry, "--entry");
1188 if (entrySym && entrySym->isDefined())
1189 entrySym->forceExport = true;
1190 else
1191 error("entry symbol not defined (pass --no-entry to suppress): " +
1192 config->entry);
1195 // If the user code defines a `__wasm_call_dtors` function, remember it so
1196 // that we can call it from the command export wrappers. Unlike
1197 // `__wasm_call_ctors` which we synthesize, `__wasm_call_dtors` is defined
1198 // by libc/etc., because destructors are registered dynamically with
1199 // `__cxa_atexit` and friends.
1200 if (!config->relocatable && !config->shared &&
1201 !WasmSym::callCtors->isUsedInRegularObj &&
1202 WasmSym::callCtors->getName() != config->entry &&
1203 !config->exportedSymbols.count(WasmSym::callCtors->getName())) {
1204 if (Symbol *callDtors =
1205 handleUndefined("__wasm_call_dtors", "<internal>")) {
1206 if (auto *callDtorsFunc = dyn_cast<DefinedFunction>(callDtors)) {
1207 if (callDtorsFunc->signature &&
1208 (!callDtorsFunc->signature->Params.empty() ||
1209 !callDtorsFunc->signature->Returns.empty())) {
1210 error("__wasm_call_dtors must have no argument or return values");
1212 WasmSym::callDtors = callDtorsFunc;
1213 } else {
1214 error("__wasm_call_dtors must be a function");
1219 if (errorCount())
1220 return;
1222 // Create wrapped symbols for -wrap option.
1223 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1225 // If any of our inputs are bitcode files, the LTO code generator may create
1226 // references to certain library functions that might not be explicit in the
1227 // bitcode file's symbol table. If any of those library functions are defined
1228 // in a bitcode file in an archive member, we need to arrange to use LTO to
1229 // compile those archive members by adding them to the link beforehand.
1231 // We only need to add libcall symbols to the link before LTO if the symbol's
1232 // definition is in bitcode. Any other required libcall symbols will be added
1233 // to the link after LTO when we add the LTO object file to the link.
1234 if (!symtab->bitcodeFiles.empty())
1235 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1236 handleLibcall(s);
1237 if (errorCount())
1238 return;
1240 // We process the stub libraries once beofore LTO to ensure that any possible
1241 // required exports are preserved by the LTO process.
1242 processStubLibrariesPreLTO();
1244 // Do link-time optimization if given files are LLVM bitcode files.
1245 // This compiles bitcode files into real object files.
1246 symtab->compileBitcodeFiles();
1247 if (errorCount())
1248 return;
1250 // The LTO process can generate new undefined symbols, specifically libcall
1251 // functions. Because those symbols might be declared in a stub library we
1252 // need the process the stub libraries once again after LTO to handle all
1253 // undefined symbols, including ones that didn't exist prior to LTO.
1254 processStubLibraries();
1256 writeWhyExtract();
1258 createOptionalSymbols();
1260 // Resolve any variant symbols that were created due to signature
1261 // mismatchs.
1262 symtab->handleSymbolVariants();
1263 if (errorCount())
1264 return;
1266 // Apply symbol renames for -wrap.
1267 if (!wrapped.empty())
1268 wrapSymbols(wrapped);
1270 for (auto &iter : config->exportedSymbols) {
1271 Symbol *sym = symtab->find(iter.first());
1272 if (sym && sym->isDefined())
1273 sym->forceExport = true;
1276 if (!config->relocatable && !config->isPic) {
1277 // Add synthetic dummies for weak undefined functions. Must happen
1278 // after LTO otherwise functions may not yet have signatures.
1279 symtab->handleWeakUndefines();
1282 if (entrySym)
1283 entrySym->setHidden(false);
1285 if (errorCount())
1286 return;
1288 // Split WASM_SEG_FLAG_STRINGS sections into pieces in preparation for garbage
1289 // collection.
1290 splitSections();
1292 // Any remaining lazy symbols should be demoted to Undefined
1293 demoteLazySymbols();
1295 // Do size optimizations: garbage collection
1296 markLive();
1298 // Provide the indirect function table if needed.
1299 WasmSym::indirectFunctionTable =
1300 symtab->resolveIndirectFunctionTable(/*required =*/false);
1302 if (errorCount())
1303 return;
1305 // Write the result to the file.
1306 writeResult();
1309 } // namespace lld::wasm