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 "Driver.h" 10 #include "Config.h" 11 #include "InputFiles.h" 12 #include "LTO.h" 13 #include "ObjC.h" 14 #include "OutputSection.h" 15 #include "OutputSegment.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "SyntheticSections.h" 19 #include "Target.h" 20 #include "Writer.h" 21 22 #include "lld/Common/Args.h" 23 #include "lld/Common/Driver.h" 24 #include "lld/Common/ErrorHandler.h" 25 #include "lld/Common/LLVM.h" 26 #include "lld/Common/Memory.h" 27 #include "lld/Common/Reproduce.h" 28 #include "lld/Common/Version.h" 29 #include "llvm/ADT/DenseSet.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/ADT/StringRef.h" 32 #include "llvm/BinaryFormat/MachO.h" 33 #include "llvm/BinaryFormat/Magic.h" 34 #include "llvm/LTO/LTO.h" 35 #include "llvm/Object/Archive.h" 36 #include "llvm/Option/ArgList.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/FileSystem.h" 39 #include "llvm/Support/Host.h" 40 #include "llvm/Support/MemoryBuffer.h" 41 #include "llvm/Support/Path.h" 42 #include "llvm/Support/TarWriter.h" 43 #include "llvm/Support/TargetSelect.h" 44 #include "llvm/TextAPI/MachO/PackedVersion.h" 45 46 #include <algorithm> 47 48 using namespace llvm; 49 using namespace llvm::MachO; 50 using namespace llvm::object; 51 using namespace llvm::opt; 52 using namespace llvm::sys; 53 using namespace lld; 54 using namespace lld::macho; 55 56 Configuration *lld::macho::config; 57 58 static HeaderFileType getOutputType(const opt::InputArgList &args) { 59 // TODO: -r, -dylinker, -preload... 60 opt::Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute); 61 if (outputArg == nullptr) 62 return MH_EXECUTE; 63 64 switch (outputArg->getOption().getID()) { 65 case OPT_bundle: 66 return MH_BUNDLE; 67 case OPT_dylib: 68 return MH_DYLIB; 69 case OPT_execute: 70 return MH_EXECUTE; 71 default: 72 llvm_unreachable("internal error"); 73 } 74 } 75 76 static Optional<std::string> 77 findAlongPathsWithExtensions(StringRef name, ArrayRef<StringRef> extensions) { 78 SmallString<261> base; 79 for (StringRef dir : config->librarySearchPaths) { 80 base = dir; 81 path::append(base, Twine("lib") + name); 82 for (StringRef ext : extensions) { 83 Twine location = base + ext; 84 if (fs::exists(location)) 85 return location.str(); 86 } 87 } 88 return {}; 89 } 90 91 static Optional<std::string> findLibrary(StringRef name) { 92 if (config->searchDylibsFirst) { 93 if (Optional<std::string> path = 94 findAlongPathsWithExtensions(name, {".tbd", ".dylib"})) 95 return path; 96 return findAlongPathsWithExtensions(name, {".a"}); 97 } 98 return findAlongPathsWithExtensions(name, {".tbd", ".dylib", ".a"}); 99 } 100 101 static Optional<std::string> findFramework(StringRef name) { 102 SmallString<260> symlink; 103 StringRef suffix; 104 std::tie(name, suffix) = name.split(","); 105 for (StringRef dir : config->frameworkSearchPaths) { 106 symlink = dir; 107 path::append(symlink, name + ".framework", name); 108 109 if (!suffix.empty()) { 110 // NOTE: we must resolve the symlink before trying the suffixes, because 111 // there are no symlinks for the suffixed paths. 112 SmallString<260> location; 113 if (!fs::real_path(symlink, location)) { 114 // only append suffix if realpath() succeeds 115 Twine suffixed = location + suffix; 116 if (fs::exists(suffixed)) 117 return suffixed.str(); 118 } 119 // Suffix lookup failed, fall through to the no-suffix case. 120 } 121 122 if (Optional<std::string> path = resolveDylibPath(symlink)) 123 return path; 124 } 125 return {}; 126 } 127 128 static TargetInfo *createTargetInfo(opt::InputArgList &args) { 129 StringRef arch = args.getLastArgValue(OPT_arch, "x86_64"); 130 config->arch = MachO::getArchitectureFromName( 131 args.getLastArgValue(OPT_arch, arch)); 132 switch (config->arch) { 133 case MachO::AK_x86_64: 134 case MachO::AK_x86_64h: 135 return createX86_64TargetInfo(); 136 default: 137 fatal("missing or unsupported -arch " + arch); 138 } 139 } 140 141 static bool warnIfNotDirectory(StringRef option, StringRef path) { 142 if (!fs::exists(path)) { 143 warn("directory not found for option -" + option + path); 144 return false; 145 } else if (!fs::is_directory(path)) { 146 warn("option -" + option + path + " references a non-directory path"); 147 return false; 148 } 149 return true; 150 } 151 152 static std::vector<StringRef> 153 getSearchPaths(unsigned optionCode, opt::InputArgList &args, 154 const std::vector<StringRef> &roots, 155 const SmallVector<StringRef, 2> &systemPaths) { 156 std::vector<StringRef> paths; 157 StringRef optionLetter{optionCode == OPT_F ? "F" : "L"}; 158 for (StringRef path : args::getStrings(args, optionCode)) { 159 // NOTE: only absolute paths are re-rooted to syslibroot(s) 160 bool found = false; 161 if (path::is_absolute(path, path::Style::posix)) { 162 for (StringRef root : roots) { 163 SmallString<261> buffer(root); 164 path::append(buffer, path); 165 // Do not warn about paths that are computed via the syslib roots 166 if (fs::is_directory(buffer)) { 167 paths.push_back(saver.save(buffer.str())); 168 found = true; 169 } 170 } 171 } 172 if (!found && warnIfNotDirectory(optionLetter, path)) 173 paths.push_back(path); 174 } 175 176 // `-Z` suppresses the standard "system" search paths. 177 if (args.hasArg(OPT_Z)) 178 return paths; 179 180 for (auto const &path : systemPaths) { 181 for (auto root : roots) { 182 SmallString<261> buffer(root); 183 path::append(buffer, path); 184 if (fs::is_directory(buffer)) 185 paths.push_back(saver.save(buffer.str())); 186 } 187 } 188 return paths; 189 } 190 191 static std::vector<StringRef> getSystemLibraryRoots(opt::InputArgList &args) { 192 std::vector<StringRef> roots; 193 for (const Arg *arg : args.filtered(OPT_syslibroot)) 194 roots.push_back(arg->getValue()); 195 // NOTE: the final `-syslibroot` being `/` will ignore all roots 196 if (roots.size() && roots.back() == "/") 197 roots.clear(); 198 // NOTE: roots can never be empty - add an empty root to simplify the library 199 // and framework search path computation. 200 if (roots.empty()) 201 roots.emplace_back(""); 202 return roots; 203 } 204 205 static std::vector<StringRef> 206 getLibrarySearchPaths(opt::InputArgList &args, 207 const std::vector<StringRef> &roots) { 208 return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"}); 209 } 210 211 static std::vector<StringRef> 212 getFrameworkSearchPaths(opt::InputArgList &args, 213 const std::vector<StringRef> &roots) { 214 return getSearchPaths(OPT_F, args, roots, 215 {"/Library/Frameworks", "/System/Library/Frameworks"}); 216 } 217 218 namespace { 219 struct ArchiveMember { 220 MemoryBufferRef mbref; 221 uint32_t modTime; 222 }; 223 } // namespace 224 225 // Returns slices of MB by parsing MB as an archive file. 226 // Each slice consists of a member file in the archive. 227 static std::vector<ArchiveMember> getArchiveMembers(MemoryBufferRef mb) { 228 std::unique_ptr<Archive> file = 229 CHECK(Archive::create(mb), 230 mb.getBufferIdentifier() + ": failed to parse archive"); 231 Archive *archive = file.get(); 232 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership 233 234 std::vector<ArchiveMember> v; 235 Error err = Error::success(); 236 237 // Thin archives refer to .o files, so --reproduces needs the .o files too. 238 bool addToTar = archive->isThin() && tar; 239 240 for (const Archive::Child &c : archive->children(err)) { 241 MemoryBufferRef mbref = 242 CHECK(c.getMemoryBufferRef(), 243 mb.getBufferIdentifier() + 244 ": could not get the buffer for a child of the archive"); 245 if (addToTar) 246 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 247 uint32_t modTime = toTimeT( 248 CHECK(c.getLastModified(), mb.getBufferIdentifier() + 249 ": could not get the modification " 250 "time for a child of the archive")); 251 v.push_back({mbref, modTime}); 252 } 253 if (err) 254 fatal(mb.getBufferIdentifier() + 255 ": Archive::children failed: " + toString(std::move(err))); 256 257 return v; 258 } 259 260 static InputFile *addFile(StringRef path, bool forceLoadArchive) { 261 Optional<MemoryBufferRef> buffer = readFile(path); 262 if (!buffer) 263 return nullptr; 264 MemoryBufferRef mbref = *buffer; 265 InputFile *newFile = nullptr; 266 267 auto magic = identify_magic(mbref.getBuffer()); 268 switch (magic) { 269 case file_magic::archive: { 270 std::unique_ptr<object::Archive> file = CHECK( 271 object::Archive::create(mbref), path + ": failed to parse archive"); 272 273 if (!file->isEmpty() && !file->hasSymbolTable()) 274 error(path + ": archive has no index; run ranlib to add one"); 275 276 if (config->allLoad || forceLoadArchive) { 277 if (Optional<MemoryBufferRef> buffer = readFile(path)) { 278 for (const ArchiveMember &member : getArchiveMembers(*buffer)) { 279 if (Optional<InputFile *> file = loadArchiveMember( 280 member.mbref, member.modTime, path, /*objCOnly=*/false)) { 281 inputFiles.insert(*file); 282 printArchiveMemberLoad( 283 (forceLoadArchive ? "-force_load" : "-all_load"), 284 inputFiles.back()); 285 } 286 } 287 } 288 } else if (config->forceLoadObjC) { 289 for (const object::Archive::Symbol &sym : file->symbols()) 290 if (sym.getName().startswith(objc::klass)) 291 symtab->addUndefined(sym.getName(), /*file=*/nullptr, 292 /*isWeakRef=*/false); 293 294 // TODO: no need to look for ObjC sections for a given archive member if 295 // we already found that it contains an ObjC symbol. We should also 296 // consider creating a LazyObjFile class in order to avoid double-loading 297 // these files here and below (as part of the ArchiveFile). 298 if (Optional<MemoryBufferRef> buffer = readFile(path)) { 299 for (const ArchiveMember &member : getArchiveMembers(*buffer)) { 300 if (Optional<InputFile *> file = loadArchiveMember( 301 member.mbref, member.modTime, path, /*objCOnly=*/true)) { 302 inputFiles.insert(*file); 303 printArchiveMemberLoad("-ObjC", inputFiles.back()); 304 } 305 } 306 } 307 } 308 309 newFile = make<ArchiveFile>(std::move(file)); 310 break; 311 } 312 case file_magic::macho_object: 313 newFile = make<ObjFile>(mbref, getModTime(path), ""); 314 break; 315 case file_magic::macho_dynamically_linked_shared_lib: 316 case file_magic::macho_dynamically_linked_shared_lib_stub: 317 case file_magic::tapi_file: 318 if (Optional<DylibFile *> dylibFile = loadDylib(mbref)) 319 newFile = *dylibFile; 320 break; 321 case file_magic::bitcode: 322 newFile = make<BitcodeFile>(mbref); 323 break; 324 default: 325 error(path + ": unhandled file type"); 326 } 327 if (newFile) { 328 // printArchiveMemberLoad() prints both .a and .o names, so no need to 329 // print the .a name here. 330 if (config->printEachFile && magic != file_magic::archive) 331 message(toString(newFile)); 332 inputFiles.insert(newFile); 333 } 334 return newFile; 335 } 336 337 static void addLibrary(StringRef name, bool isWeak) { 338 if (Optional<std::string> path = findLibrary(name)) { 339 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false)); 340 if (isWeak && dylibFile) 341 dylibFile->forceWeakImport = true; 342 return; 343 } 344 error("library not found for -l" + name); 345 } 346 347 static void addFramework(StringRef name, bool isWeak) { 348 if (Optional<std::string> path = findFramework(name)) { 349 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false)); 350 if (isWeak && dylibFile) 351 dylibFile->forceWeakImport = true; 352 return; 353 } 354 error("framework not found for -framework " + name); 355 } 356 357 // Parses LC_LINKER_OPTION contents, which can add additional command line flags. 358 void macho::parseLCLinkerOption(InputFile* f, unsigned argc, StringRef data) { 359 SmallVector<const char *, 4> argv; 360 size_t offset = 0; 361 for (unsigned i = 0; i < argc && offset < data.size(); ++i) { 362 argv.push_back(data.data() + offset); 363 offset += strlen(data.data() + offset) + 1; 364 } 365 if (argv.size() != argc || offset > data.size()) 366 fatal(toString(f) + ": invalid LC_LINKER_OPTION"); 367 368 MachOOptTable table; 369 unsigned missingIndex, missingCount; 370 opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount); 371 if (missingCount) 372 fatal(Twine(args.getArgString(missingIndex)) + ": missing argument"); 373 for (auto *arg : args.filtered(OPT_UNKNOWN)) 374 error("unknown argument: " + arg->getAsString(args)); 375 376 for (auto *arg : args) { 377 switch (arg->getOption().getID()) { 378 case OPT_l: 379 addLibrary(arg->getValue(), false); 380 break; 381 case OPT_framework: 382 addFramework(arg->getValue(), false); 383 break; 384 default: 385 error(arg->getSpelling() + " is not allowed in LC_LINKER_OPTION"); 386 } 387 } 388 } 389 390 static void addFileList(StringRef path) { 391 Optional<MemoryBufferRef> buffer = readFile(path); 392 if (!buffer) 393 return; 394 MemoryBufferRef mbref = *buffer; 395 for (StringRef path : args::getLines(mbref)) 396 addFile(path, false); 397 } 398 399 // An order file has one entry per line, in the following format: 400 // 401 // <cpu>:<object file>:<symbol name> 402 // 403 // <cpu> and <object file> are optional. If not specified, then that entry 404 // matches any symbol of that name. Parsing this format is not quite 405 // straightforward because the symbol name itself can contain colons, so when 406 // encountering a colon, we consider the preceding characters to decide if it 407 // can be a valid CPU type or file path. 408 // 409 // If a symbol is matched by multiple entries, then it takes the lowest-ordered 410 // entry (the one nearest to the front of the list.) 411 // 412 // The file can also have line comments that start with '#'. 413 static void parseOrderFile(StringRef path) { 414 Optional<MemoryBufferRef> buffer = readFile(path); 415 if (!buffer) { 416 error("Could not read order file at " + path); 417 return; 418 } 419 420 MemoryBufferRef mbref = *buffer; 421 size_t priority = std::numeric_limits<size_t>::max(); 422 for (StringRef line : args::getLines(mbref)) { 423 StringRef objectFile, symbol; 424 line = line.take_until([](char c) { return c == '#'; }); // ignore comments 425 line = line.ltrim(); 426 427 CPUType cpuType = StringSwitch<CPUType>(line) 428 .StartsWith("i386:", CPU_TYPE_I386) 429 .StartsWith("x86_64:", CPU_TYPE_X86_64) 430 .StartsWith("arm:", CPU_TYPE_ARM) 431 .StartsWith("arm64:", CPU_TYPE_ARM64) 432 .StartsWith("ppc:", CPU_TYPE_POWERPC) 433 .StartsWith("ppc64:", CPU_TYPE_POWERPC64) 434 .Default(CPU_TYPE_ANY); 435 // Drop the CPU type as well as the colon 436 if (cpuType != CPU_TYPE_ANY) 437 line = line.drop_until([](char c) { return c == ':'; }).drop_front(); 438 // TODO: Update when we extend support for other CPUs 439 if (cpuType != CPU_TYPE_ANY && cpuType != CPU_TYPE_X86_64) 440 continue; 441 442 constexpr std::array<StringRef, 2> fileEnds = {".o:", ".o):"}; 443 for (StringRef fileEnd : fileEnds) { 444 size_t pos = line.find(fileEnd); 445 if (pos != StringRef::npos) { 446 // Split the string around the colon 447 objectFile = line.take_front(pos + fileEnd.size() - 1); 448 line = line.drop_front(pos + fileEnd.size()); 449 break; 450 } 451 } 452 symbol = line.trim(); 453 454 if (!symbol.empty()) { 455 SymbolPriorityEntry &entry = config->priorities[symbol]; 456 if (!objectFile.empty()) 457 entry.objectFiles.insert(std::make_pair(objectFile, priority)); 458 else 459 entry.anyObjectFile = std::max(entry.anyObjectFile, priority); 460 } 461 462 --priority; 463 } 464 } 465 466 // We expect sub-library names of the form "libfoo", which will match a dylib 467 // with a path of .*/libfoo.{dylib, tbd}. 468 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries; 469 // I'm not sure what the use case for that is. 470 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) { 471 for (InputFile *file : inputFiles) { 472 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 473 StringRef filename = path::filename(dylibFile->getName()); 474 if (filename.consume_front(searchName) && 475 (filename.empty() || 476 find(extensions, filename) != extensions.end())) { 477 dylibFile->reexport = true; 478 return true; 479 } 480 } 481 } 482 return false; 483 } 484 485 // This function is called on startup. We need this for LTO since 486 // LTO calls LLVM functions to compile bitcode files to native code. 487 // Technically this can be delayed until we read bitcode files, but 488 // we don't bother to do lazily because the initialization is fast. 489 static void initLLVM() { 490 InitializeAllTargets(); 491 InitializeAllTargetMCs(); 492 InitializeAllAsmPrinters(); 493 InitializeAllAsmParsers(); 494 } 495 496 static void compileBitcodeFiles() { 497 auto lto = make<BitcodeCompiler>(); 498 for (InputFile *file : inputFiles) 499 if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file)) 500 lto->add(*bitcodeFile); 501 502 for (ObjFile *file : lto->compile()) 503 inputFiles.insert(file); 504 } 505 506 // Replaces common symbols with defined symbols residing in __common sections. 507 // This function must be called after all symbol names are resolved (i.e. after 508 // all InputFiles have been loaded.) As a result, later operations won't see 509 // any CommonSymbols. 510 static void replaceCommonSymbols() { 511 for (macho::Symbol *sym : symtab->getSymbols()) { 512 auto *common = dyn_cast<CommonSymbol>(sym); 513 if (common == nullptr) 514 continue; 515 516 auto *isec = make<InputSection>(); 517 isec->file = common->getFile(); 518 isec->name = section_names::common; 519 isec->segname = segment_names::data; 520 isec->align = common->align; 521 // Casting to size_t will truncate large values on 32-bit architectures, 522 // but it's not really worth supporting the linking of 64-bit programs on 523 // 32-bit archs. 524 isec->data = {nullptr, static_cast<size_t>(common->size)}; 525 isec->flags = S_ZEROFILL; 526 inputSections.push_back(isec); 527 528 replaceSymbol<Defined>(sym, sym->getName(), isec->file, isec, /*value=*/0, 529 /*isWeakDef=*/false, 530 /*isExternal=*/true, common->privateExtern); 531 } 532 } 533 534 static inline char toLowerDash(char x) { 535 if (x >= 'A' && x <= 'Z') 536 return x - 'A' + 'a'; 537 else if (x == ' ') 538 return '-'; 539 return x; 540 } 541 542 static std::string lowerDash(StringRef s) { 543 return std::string(map_iterator(s.begin(), toLowerDash), 544 map_iterator(s.end(), toLowerDash)); 545 } 546 547 static void handlePlatformVersion(const opt::Arg *arg) { 548 StringRef platformStr = arg->getValue(0); 549 StringRef minVersionStr = arg->getValue(1); 550 StringRef sdkVersionStr = arg->getValue(2); 551 552 // TODO(compnerd) see if we can generate this case list via XMACROS 553 config->platform.kind = 554 StringSwitch<PlatformKind>(lowerDash(platformStr)) 555 .Cases("macos", "1", PlatformKind::macOS) 556 .Cases("ios", "2", PlatformKind::iOS) 557 .Cases("tvos", "3", PlatformKind::tvOS) 558 .Cases("watchos", "4", PlatformKind::watchOS) 559 .Cases("bridgeos", "5", PlatformKind::bridgeOS) 560 .Cases("mac-catalyst", "6", PlatformKind::macCatalyst) 561 .Cases("ios-simulator", "7", PlatformKind::iOSSimulator) 562 .Cases("tvos-simulator", "8", PlatformKind::tvOSSimulator) 563 .Cases("watchos-simulator", "9", PlatformKind::watchOSSimulator) 564 .Cases("driverkit", "10", PlatformKind::driverKit) 565 .Default(PlatformKind::unknown); 566 if (config->platform.kind == PlatformKind::unknown) 567 error(Twine("malformed platform: ") + platformStr); 568 // TODO: check validity of version strings, which varies by platform 569 // NOTE: ld64 accepts version strings with 5 components 570 // llvm::VersionTuple accepts no more than 4 components 571 // Has Apple ever published version strings with 5 components? 572 if (config->platform.minimum.tryParse(minVersionStr)) 573 error(Twine("malformed minimum version: ") + minVersionStr); 574 if (config->platform.sdk.tryParse(sdkVersionStr)) 575 error(Twine("malformed sdk version: ") + sdkVersionStr); 576 } 577 578 static void handleUndefined(const opt::Arg *arg) { 579 StringRef treatmentStr = arg->getValue(0); 580 config->undefinedSymbolTreatment = 581 StringSwitch<UndefinedSymbolTreatment>(treatmentStr) 582 .Case("error", UndefinedSymbolTreatment::error) 583 .Case("warning", UndefinedSymbolTreatment::warning) 584 .Case("suppress", UndefinedSymbolTreatment::suppress) 585 .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup) 586 .Default(UndefinedSymbolTreatment::unknown); 587 if (config->undefinedSymbolTreatment == UndefinedSymbolTreatment::unknown) { 588 warn(Twine("unknown -undefined TREATMENT '") + treatmentStr + 589 "', defaulting to 'error'"); 590 config->undefinedSymbolTreatment = UndefinedSymbolTreatment::error; 591 } 592 } 593 594 static void warnIfDeprecatedOption(const opt::Option &opt) { 595 if (!opt.getGroup().isValid()) 596 return; 597 if (opt.getGroup().getID() == OPT_grp_deprecated) { 598 warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:"); 599 warn(opt.getHelpText()); 600 } 601 } 602 603 static void warnIfUnimplementedOption(const opt::Option &opt) { 604 if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden)) 605 return; 606 switch (opt.getGroup().getID()) { 607 case OPT_grp_deprecated: 608 // warn about deprecated options elsewhere 609 break; 610 case OPT_grp_undocumented: 611 warn("Option `" + opt.getPrefixedName() + 612 "' is undocumented. Should lld implement it?"); 613 break; 614 case OPT_grp_obsolete: 615 warn("Option `" + opt.getPrefixedName() + 616 "' is obsolete. Please modernize your usage."); 617 break; 618 case OPT_grp_ignored: 619 warn("Option `" + opt.getPrefixedName() + "' is ignored."); 620 break; 621 default: 622 warn("Option `" + opt.getPrefixedName() + 623 "' is not yet implemented. Stay tuned..."); 624 break; 625 } 626 } 627 628 static const char *getReproduceOption(opt::InputArgList &args) { 629 if (auto *arg = args.getLastArg(OPT_reproduce)) 630 return arg->getValue(); 631 return getenv("LLD_REPRODUCE"); 632 } 633 634 static bool isPie(opt::InputArgList &args) { 635 if (config->outputType != MH_EXECUTE || args.hasArg(OPT_no_pie)) 636 return false; 637 638 // TODO: add logic here as we support more archs. E.g. i386 should default 639 // to PIE from 10.7, arm64 should always be PIE, etc 640 assert(config->arch == AK_x86_64 || config->arch == AK_x86_64h); 641 642 PlatformKind kind = config->platform.kind; 643 if (kind == PlatformKind::macOS && 644 config->platform.minimum >= VersionTuple(10, 6)) 645 return true; 646 647 if (kind == PlatformKind::iOSSimulator || kind == PlatformKind::driverKit) 648 return true; 649 650 return args.hasArg(OPT_pie); 651 } 652 653 static void parseClangOption(StringRef opt, const Twine &msg) { 654 std::string err; 655 raw_string_ostream os(err); 656 657 const char *argv[] = {"lld", opt.data()}; 658 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 659 return; 660 os.flush(); 661 error(msg + ": " + StringRef(err).trim()); 662 } 663 664 static uint32_t parseDylibVersion(const opt::ArgList& args, unsigned id) { 665 const opt::Arg *arg = args.getLastArg(id); 666 if (!arg) 667 return 0; 668 669 if (config->outputType != MH_DYLIB) { 670 error(arg->getAsString(args) + ": only valid with -dylib"); 671 return 0; 672 } 673 674 PackedVersion version; 675 if (!version.parse32(arg->getValue())) { 676 error(arg->getAsString(args) + ": malformed version"); 677 return 0; 678 } 679 680 return version.rawValue(); 681 } 682 683 bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly, 684 raw_ostream &stdoutOS, raw_ostream &stderrOS) { 685 lld::stdoutOS = &stdoutOS; 686 lld::stderrOS = &stderrOS; 687 688 stderrOS.enable_colors(stderrOS.has_colors()); 689 // TODO: Set up error handler properly, e.g. the errorLimitExceededMsg 690 691 errorHandler().cleanupCallback = []() { freeArena(); }; 692 693 MachOOptTable parser; 694 opt::InputArgList args = parser.parse(argsArr.slice(1)); 695 696 if (args.hasArg(OPT_help_hidden)) { 697 parser.printHelp(argsArr[0], /*showHidden=*/true); 698 return true; 699 } 700 if (args.hasArg(OPT_help)) { 701 parser.printHelp(argsArr[0], /*showHidden=*/false); 702 return true; 703 } 704 if (args.hasArg(OPT_version)) { 705 message(getLLDVersion()); 706 return true; 707 } 708 709 if (const char *path = getReproduceOption(args)) { 710 // Note that --reproduce is a debug option so you can ignore it 711 // if you are trying to understand the whole picture of the code. 712 Expected<std::unique_ptr<TarWriter>> errOrWriter = 713 TarWriter::create(path, path::stem(path)); 714 if (errOrWriter) { 715 tar = std::move(*errOrWriter); 716 tar->append("response.txt", createResponseFile(args)); 717 tar->append("version.txt", getLLDVersion() + "\n"); 718 } else { 719 error("--reproduce: " + toString(errOrWriter.takeError())); 720 } 721 } 722 723 config = make<Configuration>(); 724 symtab = make<SymbolTable>(); 725 target = createTargetInfo(args); 726 727 config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"), 728 /*file=*/nullptr, 729 /*isWeakRef=*/false); 730 config->outputFile = args.getLastArgValue(OPT_o, "a.out"); 731 config->installName = 732 args.getLastArgValue(OPT_install_name, config->outputFile); 733 config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32); 734 config->headerPadMaxInstallNames = 735 args.hasArg(OPT_headerpad_max_install_names); 736 config->printEachFile = args.hasArg(OPT_t); 737 config->printWhyLoad = args.hasArg(OPT_why_load); 738 config->outputType = getOutputType(args); 739 config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto); 740 config->ltoNewPassManager = 741 args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager, 742 LLVM_ENABLE_NEW_PASS_MANAGER); 743 config->runtimePaths = args::getStrings(args, OPT_rpath); 744 config->allLoad = args.hasArg(OPT_all_load); 745 config->forceLoadObjC = args.hasArg(OPT_ObjC); 746 config->demangle = args.hasArg(OPT_demangle); 747 config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs); 748 749 if (const opt::Arg *arg = args.getLastArg(OPT_static, OPT_dynamic)) 750 config->staticLink = (arg->getOption().getID() == OPT_static); 751 752 config->systemLibraryRoots = getSystemLibraryRoots(args); 753 config->librarySearchPaths = 754 getLibrarySearchPaths(args, config->systemLibraryRoots); 755 config->frameworkSearchPaths = 756 getFrameworkSearchPaths(args, config->systemLibraryRoots); 757 if (const opt::Arg *arg = 758 args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first)) 759 config->searchDylibsFirst = 760 arg->getOption().getID() == OPT_search_dylibs_first; 761 762 config->dylibCompatibilityVersion = 763 parseDylibVersion(args, OPT_compatibility_version); 764 config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version); 765 766 config->saveTemps = args.hasArg(OPT_save_temps); 767 768 if (args.hasArg(OPT_v)) { 769 message(getLLDVersion()); 770 message(StringRef("Library search paths:") + 771 (config->librarySearchPaths.size() 772 ? "\n\t" + join(config->librarySearchPaths, "\n\t") 773 : "")); 774 message(StringRef("Framework search paths:") + 775 (config->frameworkSearchPaths.size() 776 ? "\n\t" + join(config->frameworkSearchPaths, "\n\t") 777 : "")); 778 freeArena(); 779 return !errorCount(); 780 } 781 782 initLLVM(); // must be run before any call to addFile() 783 784 for (const auto &arg : args) { 785 const auto &opt = arg->getOption(); 786 warnIfDeprecatedOption(opt); 787 warnIfUnimplementedOption(opt); 788 // TODO: are any of these better handled via filtered() or getLastArg()? 789 switch (opt.getID()) { 790 case OPT_INPUT: 791 addFile(arg->getValue(), false); 792 break; 793 case OPT_weak_library: 794 if (auto *dylibFile = 795 dyn_cast_or_null<DylibFile>(addFile(arg->getValue(), false))) 796 dylibFile->forceWeakImport = true; 797 break; 798 case OPT_filelist: 799 addFileList(arg->getValue()); 800 break; 801 case OPT_force_load: 802 addFile(arg->getValue(), true); 803 break; 804 case OPT_l: 805 case OPT_weak_l: 806 addLibrary(arg->getValue(), opt.getID() == OPT_weak_l); 807 break; 808 case OPT_framework: 809 case OPT_weak_framework: 810 addFramework(arg->getValue(), opt.getID() == OPT_weak_framework); 811 break; 812 case OPT_platform_version: 813 handlePlatformVersion(arg); 814 break; 815 case OPT_undefined: 816 handleUndefined(arg); 817 break; 818 default: 819 break; 820 } 821 } 822 823 config->isPic = config->outputType == MH_DYLIB || 824 config->outputType == MH_BUNDLE || isPie(args); 825 826 // Now that all dylibs have been loaded, search for those that should be 827 // re-exported. 828 for (opt::Arg *arg : args.filtered(OPT_sub_library, OPT_sub_umbrella)) { 829 config->hasReexports = true; 830 StringRef searchName = arg->getValue(); 831 std::vector<StringRef> extensions; 832 if (arg->getOption().getID() == OPT_sub_library) 833 extensions = {".dylib", ".tbd"}; 834 else 835 extensions = {".tbd"}; 836 if (!markReexport(searchName, extensions)) 837 error(arg->getSpelling() + " " + searchName + 838 " does not match a supplied dylib"); 839 } 840 841 // Parse LTO options. 842 if (auto *arg = args.getLastArg(OPT_mcpu)) 843 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), 844 arg->getSpelling()); 845 846 for (auto *arg : args.filtered(OPT_mllvm)) 847 parseClangOption(arg->getValue(), arg->getSpelling()); 848 849 compileBitcodeFiles(); 850 replaceCommonSymbols(); 851 852 StringRef orderFile = args.getLastArgValue(OPT_order_file); 853 if (!orderFile.empty()) 854 parseOrderFile(orderFile); 855 856 if (config->outputType == MH_EXECUTE && isa<Undefined>(config->entry)) { 857 error("undefined symbol: " + toString(*config->entry)); 858 return false; 859 } 860 861 createSyntheticSections(); 862 symtab->addDSOHandle(in.header); 863 864 for (opt::Arg *arg : args.filtered(OPT_sectcreate)) { 865 StringRef segName = arg->getValue(0); 866 StringRef sectName = arg->getValue(1); 867 StringRef fileName = arg->getValue(2); 868 Optional<MemoryBufferRef> buffer = readFile(fileName); 869 if (buffer) 870 inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName)); 871 } 872 873 // Initialize InputSections. 874 for (InputFile *file : inputFiles) { 875 for (SubsectionMap &map : file->subsections) { 876 for (auto &p : map) { 877 InputSection *isec = p.second; 878 inputSections.push_back(isec); 879 } 880 } 881 } 882 883 // Write to an output file. 884 writeResult(); 885 886 if (canExitEarly) 887 exitLld(errorCount() ? 1 : 0); 888 889 return !errorCount(); 890 } 891