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