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 inputFiles.insert(make<ObjFile>(member.mbref, member.modTime, path)); 280 printArchiveMemberLoad( 281 (forceLoadArchive ? "-force_load" : "-all_load"), 282 inputFiles.back()); 283 } 284 } 285 } else if (config->forceLoadObjC) { 286 for (const object::Archive::Symbol &sym : file->symbols()) 287 if (sym.getName().startswith(objc::klass)) 288 symtab->addUndefined(sym.getName(), /*isWeakRef=*/false); 289 290 // TODO: no need to look for ObjC sections for a given archive member if 291 // we already found that it contains an ObjC symbol. We should also 292 // consider creating a LazyObjFile class in order to avoid double-loading 293 // these files here and below (as part of the ArchiveFile). 294 if (Optional<MemoryBufferRef> buffer = readFile(path)) { 295 for (const ArchiveMember &member : getArchiveMembers(*buffer)) { 296 if (hasObjCSection(member.mbref)) { 297 inputFiles.insert( 298 make<ObjFile>(member.mbref, member.modTime, path)); 299 printArchiveMemberLoad("-ObjC", inputFiles.back()); 300 } 301 } 302 } 303 } 304 305 newFile = make<ArchiveFile>(std::move(file)); 306 break; 307 } 308 case file_magic::macho_object: 309 newFile = make<ObjFile>(mbref, getModTime(path), ""); 310 break; 311 case file_magic::macho_dynamically_linked_shared_lib: 312 case file_magic::macho_dynamically_linked_shared_lib_stub: 313 case file_magic::tapi_file: { 314 if (Optional<DylibFile *> dylibFile = loadDylib(mbref)) 315 newFile = *dylibFile; 316 break; 317 } 318 case file_magic::bitcode: 319 newFile = make<BitcodeFile>(mbref); 320 break; 321 default: 322 error(path + ": unhandled file type"); 323 } 324 if (newFile) { 325 // printArchiveMemberLoad() prints both .a and .o names, so no need to 326 // print the .a name here. 327 if (config->printEachFile && magic != file_magic::archive) 328 message(toString(newFile)); 329 inputFiles.insert(newFile); 330 } 331 return newFile; 332 } 333 334 static void addLibrary(StringRef name, bool isWeak) { 335 if (Optional<std::string> path = findLibrary(name)) { 336 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false)); 337 if (isWeak && dylibFile) 338 dylibFile->forceWeakImport = true; 339 return; 340 } 341 error("library not found for -l" + name); 342 } 343 344 static void addFramework(StringRef name, bool isWeak) { 345 if (Optional<std::string> path = findFramework(name)) { 346 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false)); 347 if (isWeak && dylibFile) 348 dylibFile->forceWeakImport = true; 349 return; 350 } 351 error("framework not found for -framework " + name); 352 } 353 354 // Parses LC_LINKER_OPTION contents, which can add additional command line flags. 355 void macho::parseLCLinkerOption(InputFile* f, unsigned argc, StringRef data) { 356 SmallVector<const char *, 4> argv; 357 size_t offset = 0; 358 for (unsigned i = 0; i < argc && offset < data.size(); ++i) { 359 argv.push_back(data.data() + offset); 360 offset += strlen(data.data() + offset) + 1; 361 } 362 if (argv.size() != argc || offset > data.size()) 363 fatal(toString(f) + ": invalid LC_LINKER_OPTION"); 364 365 MachOOptTable table; 366 unsigned missingIndex, missingCount; 367 opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount); 368 if (missingCount) 369 fatal(Twine(args.getArgString(missingIndex)) + ": missing argument"); 370 for (auto *arg : args.filtered(OPT_UNKNOWN)) 371 error("unknown argument: " + arg->getAsString(args)); 372 373 for (auto *arg : args) { 374 switch (arg->getOption().getID()) { 375 case OPT_l: 376 addLibrary(arg->getValue(), false); 377 break; 378 case OPT_framework: 379 addFramework(arg->getValue(), false); 380 break; 381 default: 382 error(arg->getSpelling() + " is not allowed in LC_LINKER_OPTION"); 383 } 384 } 385 } 386 387 static void addFileList(StringRef path) { 388 Optional<MemoryBufferRef> buffer = readFile(path); 389 if (!buffer) 390 return; 391 MemoryBufferRef mbref = *buffer; 392 for (StringRef path : args::getLines(mbref)) 393 addFile(path, false); 394 } 395 396 // An order file has one entry per line, in the following format: 397 // 398 // <cpu>:<object file>:<symbol name> 399 // 400 // <cpu> and <object file> are optional. If not specified, then that entry 401 // matches any symbol of that name. Parsing this format is not quite 402 // straightforward because the symbol name itself can contain colons, so when 403 // encountering a colon, we consider the preceding characters to decide if it 404 // can be a valid CPU type or file path. 405 // 406 // If a symbol is matched by multiple entries, then it takes the lowest-ordered 407 // entry (the one nearest to the front of the list.) 408 // 409 // The file can also have line comments that start with '#'. 410 static void parseOrderFile(StringRef path) { 411 Optional<MemoryBufferRef> buffer = readFile(path); 412 if (!buffer) { 413 error("Could not read order file at " + path); 414 return; 415 } 416 417 MemoryBufferRef mbref = *buffer; 418 size_t priority = std::numeric_limits<size_t>::max(); 419 for (StringRef line : args::getLines(mbref)) { 420 StringRef objectFile, symbol; 421 line = line.take_until([](char c) { return c == '#'; }); // ignore comments 422 line = line.ltrim(); 423 424 CPUType cpuType = StringSwitch<CPUType>(line) 425 .StartsWith("i386:", CPU_TYPE_I386) 426 .StartsWith("x86_64:", CPU_TYPE_X86_64) 427 .StartsWith("arm:", CPU_TYPE_ARM) 428 .StartsWith("arm64:", CPU_TYPE_ARM64) 429 .StartsWith("ppc:", CPU_TYPE_POWERPC) 430 .StartsWith("ppc64:", CPU_TYPE_POWERPC64) 431 .Default(CPU_TYPE_ANY); 432 // Drop the CPU type as well as the colon 433 if (cpuType != CPU_TYPE_ANY) 434 line = line.drop_until([](char c) { return c == ':'; }).drop_front(); 435 // TODO: Update when we extend support for other CPUs 436 if (cpuType != CPU_TYPE_ANY && cpuType != CPU_TYPE_X86_64) 437 continue; 438 439 constexpr std::array<StringRef, 2> fileEnds = {".o:", ".o):"}; 440 for (StringRef fileEnd : fileEnds) { 441 size_t pos = line.find(fileEnd); 442 if (pos != StringRef::npos) { 443 // Split the string around the colon 444 objectFile = line.take_front(pos + fileEnd.size() - 1); 445 line = line.drop_front(pos + fileEnd.size()); 446 break; 447 } 448 } 449 symbol = line.trim(); 450 451 if (!symbol.empty()) { 452 SymbolPriorityEntry &entry = config->priorities[symbol]; 453 if (!objectFile.empty()) 454 entry.objectFiles.insert(std::make_pair(objectFile, priority)); 455 else 456 entry.anyObjectFile = std::max(entry.anyObjectFile, priority); 457 } 458 459 --priority; 460 } 461 } 462 463 // We expect sub-library names of the form "libfoo", which will match a dylib 464 // with a path of .*/libfoo.{dylib, tbd}. 465 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries; 466 // I'm not sure what the use case for that is. 467 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) { 468 for (InputFile *file : inputFiles) { 469 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 470 StringRef filename = path::filename(dylibFile->getName()); 471 if (filename.consume_front(searchName) && 472 (filename.empty() || 473 find(extensions, filename) != extensions.end())) { 474 dylibFile->reexport = true; 475 return true; 476 } 477 } 478 } 479 return false; 480 } 481 482 // This function is called on startup. We need this for LTO since 483 // LTO calls LLVM functions to compile bitcode files to native code. 484 // Technically this can be delayed until we read bitcode files, but 485 // we don't bother to do lazily because the initialization is fast. 486 static void initLLVM() { 487 InitializeAllTargets(); 488 InitializeAllTargetMCs(); 489 InitializeAllAsmPrinters(); 490 InitializeAllAsmParsers(); 491 } 492 493 static void compileBitcodeFiles() { 494 auto lto = make<BitcodeCompiler>(); 495 for (InputFile *file : inputFiles) 496 if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file)) 497 lto->add(*bitcodeFile); 498 499 for (ObjFile *file : lto->compile()) 500 inputFiles.insert(file); 501 } 502 503 // Replaces common symbols with defined symbols residing in __common sections. 504 // This function must be called after all symbol names are resolved (i.e. after 505 // all InputFiles have been loaded.) As a result, later operations won't see 506 // any CommonSymbols. 507 static void replaceCommonSymbols() { 508 for (macho::Symbol *sym : symtab->getSymbols()) { 509 auto *common = dyn_cast<CommonSymbol>(sym); 510 if (common == nullptr) 511 continue; 512 513 auto *isec = make<InputSection>(); 514 isec->file = common->file; 515 isec->name = section_names::common; 516 isec->segname = segment_names::data; 517 isec->align = common->align; 518 // Casting to size_t will truncate large values on 32-bit architectures, 519 // but it's not really worth supporting the linking of 64-bit programs on 520 // 32-bit archs. 521 isec->data = {nullptr, static_cast<size_t>(common->size)}; 522 isec->flags = S_ZEROFILL; 523 inputSections.push_back(isec); 524 525 replaceSymbol<Defined>(sym, sym->getName(), isec, /*value=*/0, 526 /*isWeakDef=*/false, 527 /*isExternal=*/true, common->privateExtern); 528 } 529 } 530 531 static inline char toLowerDash(char x) { 532 if (x >= 'A' && x <= 'Z') 533 return x - 'A' + 'a'; 534 else if (x == ' ') 535 return '-'; 536 return x; 537 } 538 539 static std::string lowerDash(StringRef s) { 540 return std::string(map_iterator(s.begin(), toLowerDash), 541 map_iterator(s.end(), toLowerDash)); 542 } 543 544 static void handlePlatformVersion(const opt::Arg *arg) { 545 StringRef platformStr = arg->getValue(0); 546 StringRef minVersionStr = arg->getValue(1); 547 StringRef sdkVersionStr = arg->getValue(2); 548 549 // TODO(compnerd) see if we can generate this case list via XMACROS 550 config->platform.kind = 551 StringSwitch<PlatformKind>(lowerDash(platformStr)) 552 .Cases("macos", "1", PlatformKind::macOS) 553 .Cases("ios", "2", PlatformKind::iOS) 554 .Cases("tvos", "3", PlatformKind::tvOS) 555 .Cases("watchos", "4", PlatformKind::watchOS) 556 .Cases("bridgeos", "5", PlatformKind::bridgeOS) 557 .Cases("mac-catalyst", "6", PlatformKind::macCatalyst) 558 .Cases("ios-simulator", "7", PlatformKind::iOSSimulator) 559 .Cases("tvos-simulator", "8", PlatformKind::tvOSSimulator) 560 .Cases("watchos-simulator", "9", PlatformKind::watchOSSimulator) 561 .Cases("driverkit", "10", PlatformKind::driverKit) 562 .Default(PlatformKind::unknown); 563 if (config->platform.kind == PlatformKind::unknown) 564 error(Twine("malformed platform: ") + platformStr); 565 // TODO: check validity of version strings, which varies by platform 566 // NOTE: ld64 accepts version strings with 5 components 567 // llvm::VersionTuple accepts no more than 4 components 568 // Has Apple ever published version strings with 5 components? 569 if (config->platform.minimum.tryParse(minVersionStr)) 570 error(Twine("malformed minimum version: ") + minVersionStr); 571 if (config->platform.sdk.tryParse(sdkVersionStr)) 572 error(Twine("malformed sdk version: ") + sdkVersionStr); 573 } 574 575 static void handleUndefined(const opt::Arg *arg) { 576 StringRef treatmentStr = arg->getValue(0); 577 config->undefinedSymbolTreatment = 578 StringSwitch<UndefinedSymbolTreatment>(treatmentStr) 579 .Case("error", UndefinedSymbolTreatment::error) 580 .Case("warning", UndefinedSymbolTreatment::warning) 581 .Case("suppress", UndefinedSymbolTreatment::suppress) 582 .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup) 583 .Default(UndefinedSymbolTreatment::unknown); 584 if (config->undefinedSymbolTreatment == UndefinedSymbolTreatment::unknown) { 585 warn(Twine("unknown -undefined TREATMENT '") + treatmentStr + 586 "', defaulting to 'error'"); 587 config->undefinedSymbolTreatment = UndefinedSymbolTreatment::error; 588 } 589 } 590 591 static void warnIfDeprecatedOption(const opt::Option &opt) { 592 if (!opt.getGroup().isValid()) 593 return; 594 if (opt.getGroup().getID() == OPT_grp_deprecated) { 595 warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:"); 596 warn(opt.getHelpText()); 597 } 598 } 599 600 static void warnIfUnimplementedOption(const opt::Option &opt) { 601 if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden)) 602 return; 603 switch (opt.getGroup().getID()) { 604 case OPT_grp_deprecated: 605 // warn about deprecated options elsewhere 606 break; 607 case OPT_grp_undocumented: 608 warn("Option `" + opt.getPrefixedName() + 609 "' is undocumented. Should lld implement it?"); 610 break; 611 case OPT_grp_obsolete: 612 warn("Option `" + opt.getPrefixedName() + 613 "' is obsolete. Please modernize your usage."); 614 break; 615 case OPT_grp_ignored: 616 warn("Option `" + opt.getPrefixedName() + "' is ignored."); 617 break; 618 default: 619 warn("Option `" + opt.getPrefixedName() + 620 "' is not yet implemented. Stay tuned..."); 621 break; 622 } 623 } 624 625 static const char *getReproduceOption(opt::InputArgList &args) { 626 if (auto *arg = args.getLastArg(OPT_reproduce)) 627 return arg->getValue(); 628 return getenv("LLD_REPRODUCE"); 629 } 630 631 static bool isPie(opt::InputArgList &args) { 632 if (config->outputType != MH_EXECUTE || args.hasArg(OPT_no_pie)) 633 return false; 634 635 // TODO: add logic here as we support more archs. E.g. i386 should default 636 // to PIE from 10.7, arm64 should always be PIE, etc 637 assert(config->arch == AK_x86_64 || config->arch == AK_x86_64h); 638 639 PlatformKind kind = config->platform.kind; 640 if (kind == PlatformKind::macOS && 641 config->platform.minimum >= VersionTuple(10, 6)) 642 return true; 643 644 if (kind == PlatformKind::iOSSimulator || kind == PlatformKind::driverKit) 645 return true; 646 647 return args.hasArg(OPT_pie); 648 } 649 650 static void parseClangOption(StringRef opt, const Twine &msg) { 651 std::string err; 652 raw_string_ostream os(err); 653 654 const char *argv[] = {"lld", opt.data()}; 655 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 656 return; 657 os.flush(); 658 error(msg + ": " + StringRef(err).trim()); 659 } 660 661 static uint32_t parseDylibVersion(const opt::ArgList& args, unsigned id) { 662 const opt::Arg *arg = args.getLastArg(id); 663 if (!arg) 664 return 0; 665 666 if (config->outputType != MH_DYLIB) { 667 error(arg->getAsString(args) + ": only valid with -dylib"); 668 return 0; 669 } 670 671 PackedVersion version; 672 if (!version.parse32(arg->getValue())) { 673 error(arg->getAsString(args) + ": malformed version"); 674 return 0; 675 } 676 677 return version.rawValue(); 678 } 679 680 bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly, 681 raw_ostream &stdoutOS, raw_ostream &stderrOS) { 682 lld::stdoutOS = &stdoutOS; 683 lld::stderrOS = &stderrOS; 684 685 stderrOS.enable_colors(stderrOS.has_colors()); 686 // TODO: Set up error handler properly, e.g. the errorLimitExceededMsg 687 688 errorHandler().cleanupCallback = []() { freeArena(); }; 689 690 MachOOptTable parser; 691 opt::InputArgList args = parser.parse(argsArr.slice(1)); 692 693 if (args.hasArg(OPT_help_hidden)) { 694 parser.printHelp(argsArr[0], /*showHidden=*/true); 695 return true; 696 } 697 if (args.hasArg(OPT_help)) { 698 parser.printHelp(argsArr[0], /*showHidden=*/false); 699 return true; 700 } 701 if (args.hasArg(OPT_version)) { 702 message(getLLDVersion()); 703 return true; 704 } 705 706 if (const char *path = getReproduceOption(args)) { 707 // Note that --reproduce is a debug option so you can ignore it 708 // if you are trying to understand the whole picture of the code. 709 Expected<std::unique_ptr<TarWriter>> errOrWriter = 710 TarWriter::create(path, path::stem(path)); 711 if (errOrWriter) { 712 tar = std::move(*errOrWriter); 713 tar->append("response.txt", createResponseFile(args)); 714 tar->append("version.txt", getLLDVersion() + "\n"); 715 } else { 716 error("--reproduce: " + toString(errOrWriter.takeError())); 717 } 718 } 719 720 config = make<Configuration>(); 721 symtab = make<SymbolTable>(); 722 target = createTargetInfo(args); 723 724 config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"), 725 /*isWeakRef=*/false); 726 config->outputFile = args.getLastArgValue(OPT_o, "a.out"); 727 config->installName = 728 args.getLastArgValue(OPT_install_name, config->outputFile); 729 config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32); 730 config->headerPadMaxInstallNames = 731 args.hasArg(OPT_headerpad_max_install_names); 732 config->printEachFile = args.hasArg(OPT_t); 733 config->printWhyLoad = args.hasArg(OPT_why_load); 734 config->outputType = getOutputType(args); 735 config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto); 736 config->ltoNewPassManager = 737 args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager, 738 LLVM_ENABLE_NEW_PASS_MANAGER); 739 config->runtimePaths = args::getStrings(args, OPT_rpath); 740 config->allLoad = args.hasArg(OPT_all_load); 741 config->forceLoadObjC = args.hasArg(OPT_ObjC); 742 config->demangle = args.hasArg(OPT_demangle); 743 config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs); 744 745 if (const opt::Arg *arg = args.getLastArg(OPT_static, OPT_dynamic)) 746 config->staticLink = (arg->getOption().getID() == OPT_static); 747 748 config->systemLibraryRoots = getSystemLibraryRoots(args); 749 config->librarySearchPaths = 750 getLibrarySearchPaths(args, config->systemLibraryRoots); 751 config->frameworkSearchPaths = 752 getFrameworkSearchPaths(args, config->systemLibraryRoots); 753 if (const opt::Arg *arg = 754 args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first)) 755 config->searchDylibsFirst = 756 arg->getOption().getID() == OPT_search_dylibs_first; 757 758 config->dylibCompatibilityVersion = 759 parseDylibVersion(args, OPT_compatibility_version); 760 config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version); 761 762 config->saveTemps = args.hasArg(OPT_save_temps); 763 764 if (args.hasArg(OPT_v)) { 765 message(getLLDVersion()); 766 message(StringRef("Library search paths:") + 767 (config->librarySearchPaths.size() 768 ? "\n\t" + join(config->librarySearchPaths, "\n\t") 769 : "")); 770 message(StringRef("Framework search paths:") + 771 (config->frameworkSearchPaths.size() 772 ? "\n\t" + join(config->frameworkSearchPaths, "\n\t") 773 : "")); 774 freeArena(); 775 return !errorCount(); 776 } 777 778 initLLVM(); // must be run before any call to addFile() 779 780 for (const auto &arg : args) { 781 const auto &opt = arg->getOption(); 782 warnIfDeprecatedOption(opt); 783 warnIfUnimplementedOption(opt); 784 // TODO: are any of these better handled via filtered() or getLastArg()? 785 switch (opt.getID()) { 786 case OPT_INPUT: 787 addFile(arg->getValue(), false); 788 break; 789 case OPT_weak_library: { 790 auto *dylibFile = 791 dyn_cast_or_null<DylibFile>(addFile(arg->getValue(), false)); 792 if (dylibFile) 793 dylibFile->forceWeakImport = true; 794 break; 795 } 796 case OPT_filelist: 797 addFileList(arg->getValue()); 798 break; 799 case OPT_force_load: 800 addFile(arg->getValue(), true); 801 break; 802 case OPT_l: 803 case OPT_weak_l: 804 addLibrary(arg->getValue(), opt.getID() == OPT_weak_l); 805 break; 806 case OPT_framework: 807 case OPT_weak_framework: 808 addFramework(arg->getValue(), opt.getID() == OPT_weak_framework); 809 break; 810 case OPT_platform_version: 811 handlePlatformVersion(arg); 812 break; 813 case OPT_undefined: 814 handleUndefined(arg); 815 break; 816 default: 817 break; 818 } 819 } 820 821 config->isPic = config->outputType == MH_DYLIB || 822 config->outputType == MH_BUNDLE || isPie(args); 823 824 // Now that all dylibs have been loaded, search for those that should be 825 // re-exported. 826 for (opt::Arg *arg : args.filtered(OPT_sub_library, OPT_sub_umbrella)) { 827 config->hasReexports = true; 828 StringRef searchName = arg->getValue(); 829 std::vector<StringRef> extensions; 830 if (arg->getOption().getID() == OPT_sub_library) 831 extensions = {".dylib", ".tbd"}; 832 else 833 extensions = {".tbd"}; 834 if (!markReexport(searchName, extensions)) 835 error(arg->getSpelling() + " " + searchName + 836 " does not match a supplied dylib"); 837 } 838 839 // Parse LTO options. 840 if (auto *arg = args.getLastArg(OPT_mcpu)) 841 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), 842 arg->getSpelling()); 843 844 for (auto *arg : args.filtered(OPT_mllvm)) 845 parseClangOption(arg->getValue(), arg->getSpelling()); 846 847 compileBitcodeFiles(); 848 replaceCommonSymbols(); 849 850 StringRef orderFile = args.getLastArgValue(OPT_order_file); 851 if (!orderFile.empty()) 852 parseOrderFile(orderFile); 853 854 if (config->outputType == MH_EXECUTE && isa<Undefined>(config->entry)) { 855 error("undefined symbol: " + toString(*config->entry)); 856 return false; 857 } 858 859 createSyntheticSections(); 860 symtab->addDSOHandle(in.header); 861 862 for (opt::Arg *arg : args.filtered(OPT_sectcreate)) { 863 StringRef segName = arg->getValue(0); 864 StringRef sectName = arg->getValue(1); 865 StringRef fileName = arg->getValue(2); 866 Optional<MemoryBufferRef> buffer = readFile(fileName); 867 if (buffer) 868 inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName)); 869 } 870 871 // Initialize InputSections. 872 for (InputFile *file : inputFiles) { 873 for (SubsectionMap &map : file->subsections) { 874 for (auto &p : map) { 875 InputSection *isec = p.second; 876 inputSections.push_back(isec); 877 } 878 } 879 } 880 881 // Write to an output file. 882 writeResult(); 883 884 if (canExitEarly) 885 exitLld(errorCount() ? 1 : 0); 886 887 return !errorCount(); 888 } 889