1 //===- Driver.cpp ---------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lld/Common/Driver.h" 10 #include "Config.h" 11 #include "InputChunks.h" 12 #include "InputGlobal.h" 13 #include "MarkLive.h" 14 #include "SymbolTable.h" 15 #include "Writer.h" 16 #include "lld/Common/Args.h" 17 #include "lld/Common/ErrorHandler.h" 18 #include "lld/Common/Memory.h" 19 #include "lld/Common/Reproduce.h" 20 #include "lld/Common/Strings.h" 21 #include "lld/Common/Threads.h" 22 #include "lld/Common/Version.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Object/Wasm.h" 25 #include "llvm/Option/Arg.h" 26 #include "llvm/Option/ArgList.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/Process.h" 30 #include "llvm/Support/TarWriter.h" 31 #include "llvm/Support/TargetSelect.h" 32 33 #define DEBUG_TYPE "lld" 34 35 using namespace llvm; 36 using namespace llvm::object; 37 using namespace llvm::sys; 38 using namespace llvm::wasm; 39 40 using namespace lld; 41 using namespace lld::wasm; 42 43 Configuration *lld::wasm::Config; 44 45 namespace { 46 47 // Create enum with OPT_xxx values for each option in Options.td 48 enum { 49 OPT_INVALID = 0, 50 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID, 51 #include "Options.inc" 52 #undef OPTION 53 }; 54 55 // This function is called on startup. We need this for LTO since 56 // LTO calls LLVM functions to compile bitcode files to native code. 57 // Technically this can be delayed until we read bitcode files, but 58 // we don't bother to do lazily because the initialization is fast. 59 static void initLLVM() { 60 InitializeAllTargets(); 61 InitializeAllTargetMCs(); 62 InitializeAllAsmPrinters(); 63 InitializeAllAsmParsers(); 64 } 65 66 class LinkerDriver { 67 public: 68 void link(ArrayRef<const char *> ArgsArr); 69 70 private: 71 void createFiles(opt::InputArgList &Args); 72 void addFile(StringRef Path); 73 void addLibrary(StringRef Name); 74 75 // True if we are in --whole-archive and --no-whole-archive. 76 bool InWholeArchive = false; 77 78 std::vector<InputFile *> Files; 79 }; 80 } // anonymous namespace 81 82 bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly, 83 raw_ostream &Error) { 84 errorHandler().LogName = args::getFilenameWithoutExe(Args[0]); 85 errorHandler().ErrorOS = &Error; 86 errorHandler().ColorDiagnostics = Error.has_colors(); 87 errorHandler().ErrorLimitExceededMsg = 88 "too many errors emitted, stopping now (use " 89 "-error-limit=0 to see all errors)"; 90 91 Config = make<Configuration>(); 92 Symtab = make<SymbolTable>(); 93 94 initLLVM(); 95 LinkerDriver().link(Args); 96 97 // Exit immediately if we don't need to return to the caller. 98 // This saves time because the overhead of calling destructors 99 // for all globally-allocated objects is not negligible. 100 if (CanExitEarly) 101 exitLld(errorCount() ? 1 : 0); 102 103 freeArena(); 104 return !errorCount(); 105 } 106 107 // Create prefix string literals used in Options.td 108 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; 109 #include "Options.inc" 110 #undef PREFIX 111 112 // Create table mapping all options defined in Options.td 113 static const 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 119 }; 120 121 namespace { 122 class WasmOptTable : public llvm::opt::OptTable { 123 public: 124 WasmOptTable() : OptTable(OptInfo) {} 125 opt::InputArgList parse(ArrayRef<const char *> Argv); 126 }; 127 } // namespace 128 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 errorHandler().ColorDiagnostics = true; 138 } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) { 139 errorHandler().ColorDiagnostics = false; 140 } else { 141 StringRef S = Arg->getValue(); 142 if (S == "always") 143 errorHandler().ColorDiagnostics = true; 144 else if (S == "never") 145 errorHandler().ColorDiagnostics = false; 146 else if (S != "auto") 147 error("unknown option: --color-diagnostics=" + S); 148 } 149 } 150 151 // Find a file by concatenating given paths. 152 static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) { 153 SmallString<128> S; 154 path::append(S, Path1, Path2); 155 if (fs::exists(S)) 156 return S.str().str(); 157 return None; 158 } 159 160 opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) { 161 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size()); 162 163 unsigned MissingIndex; 164 unsigned MissingCount; 165 166 // Expand response files (arguments in the form of @<filename>) 167 cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Vec); 168 169 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount); 170 171 handleColorDiagnostics(Args); 172 for (auto *Arg : Args.filtered(OPT_UNKNOWN)) 173 error("unknown argument: " + Arg->getSpelling()); 174 return Args; 175 } 176 177 // Currently we allow a ".imports" to live alongside a library. This can 178 // be used to specify a list of symbols which can be undefined at link 179 // time (imported from the environment. For example libc.a include an 180 // import file that lists the syscall functions it relies on at runtime. 181 // In the long run this information would be better stored as a symbol 182 // attribute/flag in the object file itself. 183 // See: https://github.com/WebAssembly/tool-conventions/issues/35 184 static void readImportFile(StringRef Filename) { 185 if (Optional<MemoryBufferRef> Buf = readFile(Filename)) 186 for (StringRef Sym : args::getLines(*Buf)) 187 Config->AllowUndefinedSymbols.insert(Sym); 188 } 189 190 // Returns slices of MB by parsing MB as an archive file. 191 // Each slice consists of a member file in the archive. 192 std::vector<MemoryBufferRef> static getArchiveMembers(MemoryBufferRef MB) { 193 std::unique_ptr<Archive> File = 194 CHECK(Archive::create(MB), 195 MB.getBufferIdentifier() + ": failed to parse archive"); 196 197 std::vector<MemoryBufferRef> V; 198 Error Err = Error::success(); 199 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) { 200 Archive::Child C = 201 CHECK(COrErr, MB.getBufferIdentifier() + 202 ": could not get the child of the archive"); 203 MemoryBufferRef MBRef = 204 CHECK(C.getMemoryBufferRef(), 205 MB.getBufferIdentifier() + 206 ": could not get the buffer for a child of the archive"); 207 V.push_back(MBRef); 208 } 209 if (Err) 210 fatal(MB.getBufferIdentifier() + 211 ": Archive::children failed: " + toString(std::move(Err))); 212 213 // Take ownership of memory buffers created for members of thin archives. 214 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers()) 215 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); 216 217 return V; 218 } 219 220 void LinkerDriver::addFile(StringRef Path) { 221 Optional<MemoryBufferRef> Buffer = readFile(Path); 222 if (!Buffer.hasValue()) 223 return; 224 MemoryBufferRef MBRef = *Buffer; 225 226 switch (identify_magic(MBRef.getBuffer())) { 227 case file_magic::archive: { 228 // Handle -whole-archive. 229 if (InWholeArchive) { 230 for (MemoryBufferRef &M : getArchiveMembers(MBRef)) 231 Files.push_back(createObjectFile(M, Path)); 232 return; 233 } 234 235 SmallString<128> ImportFile = Path; 236 path::replace_extension(ImportFile, ".imports"); 237 if (fs::exists(ImportFile)) 238 readImportFile(ImportFile.str()); 239 240 Files.push_back(make<ArchiveFile>(MBRef)); 241 return; 242 } 243 case file_magic::bitcode: 244 case file_magic::wasm_object: 245 Files.push_back(createObjectFile(MBRef)); 246 break; 247 default: 248 error("unknown file type: " + MBRef.getBufferIdentifier()); 249 } 250 } 251 252 // Add a given library by searching it from input search paths. 253 void LinkerDriver::addLibrary(StringRef Name) { 254 for (StringRef Dir : Config->SearchPaths) { 255 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) { 256 addFile(*S); 257 return; 258 } 259 } 260 261 error("unable to find library -l" + Name); 262 } 263 264 void LinkerDriver::createFiles(opt::InputArgList &Args) { 265 for (auto *Arg : Args) { 266 switch (Arg->getOption().getUnaliasedOption().getID()) { 267 case OPT_l: 268 addLibrary(Arg->getValue()); 269 break; 270 case OPT_INPUT: 271 addFile(Arg->getValue()); 272 break; 273 case OPT_whole_archive: 274 InWholeArchive = true; 275 break; 276 case OPT_no_whole_archive: 277 InWholeArchive = false; 278 break; 279 } 280 } 281 } 282 283 static StringRef getEntry(opt::InputArgList &Args) { 284 auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry); 285 if (!Arg) { 286 if (Args.hasArg(OPT_relocatable)) 287 return ""; 288 if (Args.hasArg(OPT_shared)) 289 return "__wasm_call_ctors"; 290 return "_start"; 291 } 292 if (Arg->getOption().getID() == OPT_no_entry) 293 return ""; 294 return Arg->getValue(); 295 } 296 297 // Initializes Config members by the command line options. 298 static void readConfigs(opt::InputArgList &Args) { 299 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined); 300 Config->CheckFeatures = 301 Args.hasFlag(OPT_check_features, OPT_no_check_features, true); 302 Config->CompressRelocations = Args.hasArg(OPT_compress_relocations); 303 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true); 304 Config->DisableVerify = Args.hasArg(OPT_disable_verify); 305 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs); 306 Config->Entry = getEntry(Args); 307 Config->ExportAll = Args.hasArg(OPT_export_all); 308 Config->ExportDynamic = Args.hasFlag(OPT_export_dynamic, 309 OPT_no_export_dynamic, false); 310 Config->ExportTable = Args.hasArg(OPT_export_table); 311 errorHandler().FatalWarnings = 312 Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 313 Config->ImportMemory = Args.hasArg(OPT_import_memory); 314 Config->SharedMemory = Args.hasArg(OPT_shared_memory); 315 Config->ImportTable = Args.hasArg(OPT_import_table); 316 Config->LTOO = args::getInteger(Args, OPT_lto_O, 2); 317 Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1); 318 Config->Optimize = args::getInteger(Args, OPT_O, 0); 319 Config->OutputFile = Args.getLastArgValue(OPT_o); 320 Config->Relocatable = Args.hasArg(OPT_relocatable); 321 Config->GcSections = 322 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable); 323 Config->MergeDataSegments = 324 Args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments, 325 !Config->Relocatable); 326 Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false); 327 Config->PrintGcSections = 328 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 329 Config->SaveTemps = Args.hasArg(OPT_save_temps); 330 Config->SearchPaths = args::getStrings(Args, OPT_L); 331 Config->Shared = Args.hasArg(OPT_shared); 332 Config->StripAll = Args.hasArg(OPT_strip_all); 333 Config->StripDebug = Args.hasArg(OPT_strip_debug); 334 Config->StackFirst = Args.hasArg(OPT_stack_first); 335 Config->Trace = Args.hasArg(OPT_trace); 336 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir); 337 Config->ThinLTOCachePolicy = CHECK( 338 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)), 339 "--thinlto-cache-policy: invalid cache policy"); 340 Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u); 341 errorHandler().Verbose = Args.hasArg(OPT_verbose); 342 LLVM_DEBUG(errorHandler().Verbose = true); 343 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true); 344 345 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0); 346 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024); 347 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0); 348 Config->ZStackSize = 349 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize); 350 351 if (auto *Arg = Args.getLastArg(OPT_features)) { 352 Config->Features = 353 llvm::Optional<std::vector<std::string>>(std::vector<std::string>()); 354 for (StringRef S : Arg->getValues()) 355 Config->Features->push_back(S); 356 } 357 } 358 359 // Some Config members do not directly correspond to any particular 360 // command line options, but computed based on other Config values. 361 // This function initialize such members. See Config.h for the details 362 // of these values. 363 static void setConfigs() { 364 Config->Pic = Config->Pie || Config->Shared; 365 366 if (Config->Pic) { 367 if (Config->ExportTable) 368 error("-shared/-pie is incompatible with --export-table"); 369 Config->ImportTable = true; 370 } 371 372 if (Config->Shared) { 373 Config->ImportMemory = true; 374 Config->ExportDynamic = true; 375 Config->AllowUndefined = true; 376 } 377 } 378 379 // Some command line options or some combinations of them are not allowed. 380 // This function checks for such errors. 381 static void checkOptions(opt::InputArgList &Args) { 382 if (!Config->StripDebug && !Config->StripAll && Config->CompressRelocations) 383 error("--compress-relocations is incompatible with output debug" 384 " information. Please pass --strip-debug or --strip-all"); 385 386 if (Config->LTOO > 3) 387 error("invalid optimization level for LTO: " + Twine(Config->LTOO)); 388 if (Config->LTOPartitions == 0) 389 error("--lto-partitions: number of threads must be > 0"); 390 if (Config->ThinLTOJobs == 0) 391 error("--thinlto-jobs: number of threads must be > 0"); 392 393 if (Config->Pie && Config->Shared) 394 error("-shared and -pie may not be used together"); 395 396 if (Config->OutputFile.empty()) 397 error("no output file specified"); 398 399 if (Config->ImportTable && Config->ExportTable) 400 error("--import-table and --export-table may not be used together"); 401 402 if (Config->Relocatable) { 403 if (!Config->Entry.empty()) 404 error("entry point specified for relocatable output file"); 405 if (Config->GcSections) 406 error("-r and --gc-sections may not be used together"); 407 if (Config->CompressRelocations) 408 error("-r -and --compress-relocations may not be used together"); 409 if (Args.hasArg(OPT_undefined)) 410 error("-r -and --undefined may not be used together"); 411 if (Config->Pie) 412 error("-r and -pie may not be used together"); 413 } 414 } 415 416 // Force Sym to be entered in the output. Used for -u or equivalent. 417 static Symbol *handleUndefined(StringRef Name) { 418 Symbol *Sym = Symtab->find(Name); 419 if (!Sym) 420 return nullptr; 421 422 // Since symbol S may not be used inside the program, LTO may 423 // eliminate it. Mark the symbol as "used" to prevent it. 424 Sym->IsUsedInRegularObj = true; 425 426 if (auto *LazySym = dyn_cast<LazySymbol>(Sym)) 427 LazySym->fetch(); 428 429 return Sym; 430 } 431 432 static UndefinedGlobal * 433 createUndefinedGlobal(StringRef Name, llvm::wasm::WasmGlobalType *Type) { 434 auto *Sym = 435 cast<UndefinedGlobal>(Symtab->addUndefinedGlobal(Name, Name, 436 DefaultModule, 0, 437 nullptr, Type)); 438 Config->AllowUndefinedSymbols.insert(Sym->getName()); 439 Sym->IsUsedInRegularObj = true; 440 return Sym; 441 } 442 443 // Create ABI-defined synthetic symbols 444 static void createSyntheticSymbols() { 445 static WasmSignature NullSignature = {{}, {}}; 446 static llvm::wasm::WasmGlobalType GlobalTypeI32 = {WASM_TYPE_I32, false}; 447 static llvm::wasm::WasmGlobalType MutableGlobalTypeI32 = {WASM_TYPE_I32, 448 true}; 449 450 if (!Config->Relocatable) { 451 WasmSym::CallCtors = Symtab->addSyntheticFunction( 452 "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN, 453 make<SyntheticFunction>(NullSignature, "__wasm_call_ctors")); 454 455 if (Config->Pic) { 456 // For PIC code we create a synthetic function call __wasm_apply_relocs 457 // and add this as the first call in __wasm_call_ctors. 458 // We also unconditionally export 459 WasmSym::ApplyRelocs = Symtab->addSyntheticFunction( 460 "__wasm_apply_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN, 461 make<SyntheticFunction>(NullSignature, "__wasm_apply_relocs")); 462 } 463 } 464 465 // The __stack_pointer is imported in the shared library case, and exported 466 // in the non-shared (executable) case. 467 if (Config->Shared) { 468 WasmSym::StackPointer = 469 createUndefinedGlobal("__stack_pointer", &MutableGlobalTypeI32); 470 } else { 471 llvm::wasm::WasmGlobal Global; 472 Global.Type = {WASM_TYPE_I32, true}; 473 Global.InitExpr.Value.Int32 = 0; 474 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST; 475 Global.SymbolName = "__stack_pointer"; 476 auto *StackPointer = make<InputGlobal>(Global, nullptr); 477 StackPointer->Live = true; 478 // For non-PIC code 479 // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN when the mutable global 480 // spec proposal is implemented in all major browsers. 481 // See: https://github.com/WebAssembly/mutable-global 482 WasmSym::StackPointer = Symtab->addSyntheticGlobal( 483 "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer); 484 WasmSym::DataEnd = Symtab->addOptionalDataSymbol("__data_end"); 485 WasmSym::HeapBase = Symtab->addOptionalDataSymbol("__heap_base"); 486 } 487 488 if (Config->Pic) { 489 // For PIC code, we import two global variables (__memory_base and 490 // __table_base) from the environment and use these as the offset at 491 // which to load our static data and function table. 492 // See: 493 // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md 494 WasmSym::MemoryBase = 495 createUndefinedGlobal("__memory_base", &GlobalTypeI32); 496 WasmSym::TableBase = createUndefinedGlobal("__table_base", &GlobalTypeI32); 497 WasmSym::MemoryBase->markLive(); 498 WasmSym::TableBase->markLive(); 499 } 500 501 WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol( 502 "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN); 503 } 504 505 // Reconstructs command line arguments so that so that you can re-run 506 // the same command with the same inputs. This is for --reproduce. 507 static std::string createResponseFile(const opt::InputArgList &Args) { 508 SmallString<0> Data; 509 raw_svector_ostream OS(Data); 510 511 // Copy the command line to the output while rewriting paths. 512 for (auto *Arg : Args) { 513 switch (Arg->getOption().getUnaliasedOption().getID()) { 514 case OPT_reproduce: 515 break; 516 case OPT_INPUT: 517 OS << quote(relativeToRoot(Arg->getValue())) << "\n"; 518 break; 519 case OPT_o: 520 // If -o path contains directories, "lld @response.txt" will likely 521 // fail because the archive we are creating doesn't contain empty 522 // directories for the output path (-o doesn't create directories). 523 // Strip directories to prevent the issue. 524 OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n"; 525 break; 526 default: 527 OS << toString(*Arg) << "\n"; 528 } 529 } 530 return Data.str(); 531 } 532 533 // The --wrap option is a feature to rename symbols so that you can write 534 // wrappers for existing functions. If you pass `-wrap=foo`, all 535 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are 536 // expected to write `wrap_foo` function as a wrapper). The original 537 // symbol becomes accessible as `real_foo`, so you can call that from your 538 // wrapper. 539 // 540 // This data structure is instantiated for each -wrap option. 541 struct WrappedSymbol { 542 Symbol *Sym; 543 Symbol *Real; 544 Symbol *Wrap; 545 }; 546 547 static Symbol *addUndefined(StringRef Name) { 548 return Symtab->addUndefinedFunction(Name, "", "", 0, nullptr, nullptr, false); 549 } 550 551 // Handles -wrap option. 552 // 553 // This function instantiates wrapper symbols. At this point, they seem 554 // like they are not being used at all, so we explicitly set some flags so 555 // that LTO won't eliminate them. 556 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &Args) { 557 std::vector<WrappedSymbol> V; 558 DenseSet<StringRef> Seen; 559 560 for (auto *Arg : Args.filtered(OPT_wrap)) { 561 StringRef Name = Arg->getValue(); 562 if (!Seen.insert(Name).second) 563 continue; 564 565 Symbol *Sym = Symtab->find(Name); 566 if (!Sym) 567 continue; 568 569 Symbol *Real = addUndefined(Saver.save("__real_" + Name)); 570 Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name)); 571 V.push_back({Sym, Real, Wrap}); 572 573 // We want to tell LTO not to inline symbols to be overwritten 574 // because LTO doesn't know the final symbol contents after renaming. 575 Real->CanInline = false; 576 Sym->CanInline = false; 577 578 // Tell LTO not to eliminate these symbols. 579 Sym->IsUsedInRegularObj = true; 580 Wrap->IsUsedInRegularObj = true; 581 Real->IsUsedInRegularObj = false; 582 } 583 return V; 584 } 585 586 // Do renaming for -wrap by updating pointers to symbols. 587 // 588 // When this function is executed, only InputFiles and symbol table 589 // contain pointers to symbol objects. We visit them to replace pointers, 590 // so that wrapped symbols are swapped as instructed by the command line. 591 static void wrapSymbols(ArrayRef<WrappedSymbol> Wrapped) { 592 DenseMap<Symbol *, Symbol *> Map; 593 for (const WrappedSymbol &W : Wrapped) { 594 Map[W.Sym] = W.Wrap; 595 Map[W.Real] = W.Sym; 596 } 597 598 // Update pointers in input files. 599 parallelForEach(Symtab->ObjectFiles, [&](InputFile *File) { 600 MutableArrayRef<Symbol *> Syms = File->getMutableSymbols(); 601 for (size_t I = 0, E = Syms.size(); I != E; ++I) 602 if (Symbol *S = Map.lookup(Syms[I])) 603 Syms[I] = S; 604 }); 605 606 // Update pointers in the symbol table. 607 for (const WrappedSymbol &W : Wrapped) 608 Symtab->wrap(W.Sym, W.Real, W.Wrap); 609 } 610 611 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) { 612 WasmOptTable Parser; 613 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1)); 614 615 // Handle --help 616 if (Args.hasArg(OPT_help)) { 617 Parser.PrintHelp(outs(), 618 (std::string(ArgsArr[0]) + " [options] file...").c_str(), 619 "LLVM Linker", false); 620 return; 621 } 622 623 // Handle --version 624 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) { 625 outs() << getLLDVersion() << "\n"; 626 return; 627 } 628 629 // Handle --reproduce 630 if (auto *Arg = Args.getLastArg(OPT_reproduce)) { 631 StringRef Path = Arg->getValue(); 632 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 633 TarWriter::create(Path, path::stem(Path)); 634 if (ErrOrWriter) { 635 Tar = std::move(*ErrOrWriter); 636 Tar->append("response.txt", createResponseFile(Args)); 637 Tar->append("version.txt", getLLDVersion() + "\n"); 638 } else { 639 error("--reproduce: " + toString(ErrOrWriter.takeError())); 640 } 641 } 642 643 // Parse and evaluate -mllvm options. 644 std::vector<const char *> V; 645 V.push_back("wasm-ld (LLVM option parsing)"); 646 for (auto *Arg : Args.filtered(OPT_mllvm)) 647 V.push_back(Arg->getValue()); 648 cl::ParseCommandLineOptions(V.size(), V.data()); 649 650 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20); 651 652 readConfigs(Args); 653 setConfigs(); 654 checkOptions(Args); 655 656 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file)) 657 readImportFile(Arg->getValue()); 658 659 if (!Args.hasArg(OPT_INPUT)) { 660 error("no input files"); 661 return; 662 } 663 664 // Handle --trace-symbol. 665 for (auto *Arg : Args.filtered(OPT_trace_symbol)) 666 Symtab->trace(Arg->getValue()); 667 668 for (auto *Arg : Args.filtered(OPT_export)) 669 Config->ExportedSymbols.insert(Arg->getValue()); 670 671 if (!Config->Relocatable) 672 createSyntheticSymbols(); 673 674 createFiles(Args); 675 if (errorCount()) 676 return; 677 678 // Add all files to the symbol table. This will add almost all 679 // symbols that we need to the symbol table. 680 for (InputFile *F : Files) 681 Symtab->addFile(F); 682 if (errorCount()) 683 return; 684 685 // Handle the `--undefined <sym>` options. 686 for (auto *Arg : Args.filtered(OPT_undefined)) 687 handleUndefined(Arg->getValue()); 688 689 // Handle the `--export <sym>` options 690 // This works like --undefined but also exports the symbol if its found 691 for (auto *Arg : Args.filtered(OPT_export)) 692 handleUndefined(Arg->getValue()); 693 694 Symbol *EntrySym = nullptr; 695 if (!Config->Relocatable && !Config->Entry.empty()) { 696 EntrySym = handleUndefined(Config->Entry); 697 if (EntrySym && EntrySym->isDefined()) 698 EntrySym->ForceExport = true; 699 else 700 error("entry symbol not defined (pass --no-entry to supress): " + 701 Config->Entry); 702 } 703 704 if (errorCount()) 705 return; 706 707 // Create wrapped symbols for -wrap option. 708 std::vector<WrappedSymbol> Wrapped = addWrappedSymbols(Args); 709 710 // Do link-time optimization if given files are LLVM bitcode files. 711 // This compiles bitcode files into real object files. 712 Symtab->addCombinedLTOObject(); 713 if (errorCount()) 714 return; 715 716 // Resolve any variant symbols that were created due to signature 717 // mismatchs. 718 Symtab->handleSymbolVariants(); 719 if (errorCount()) 720 return; 721 722 // Apply symbol renames for -wrap. 723 if (!Wrapped.empty()) 724 wrapSymbols(Wrapped); 725 726 for (auto *Arg : Args.filtered(OPT_export)) { 727 Symbol *Sym = Symtab->find(Arg->getValue()); 728 if (Sym && Sym->isDefined()) 729 Sym->ForceExport = true; 730 else if (!Config->AllowUndefined) 731 error(Twine("symbol exported via --export not found: ") + 732 Arg->getValue()); 733 } 734 735 if (!Config->Relocatable) { 736 // Add synthetic dummies for weak undefined functions. Must happen 737 // after LTO otherwise functions may not yet have signatures. 738 Symtab->handleWeakUndefines(); 739 } 740 741 if (EntrySym) 742 EntrySym->setHidden(false); 743 744 if (errorCount()) 745 return; 746 747 // Do size optimizations: garbage collection 748 markLive(); 749 750 // Write the result to the file. 751 writeResult(); 752 } 753