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