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 "DriverUtils.h" 12 #include "InputFiles.h" 13 #include "LTO.h" 14 #include "ObjC.h" 15 #include "OutputSection.h" 16 #include "OutputSegment.h" 17 #include "SymbolTable.h" 18 #include "Symbols.h" 19 #include "SyntheticSections.h" 20 #include "Target.h" 21 #include "Writer.h" 22 23 #include "lld/Common/Args.h" 24 #include "lld/Common/Driver.h" 25 #include "lld/Common/ErrorHandler.h" 26 #include "lld/Common/LLVM.h" 27 #include "lld/Common/Memory.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/Option/Option.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/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 // Create prefix string literals used in Options.td 57 #define PREFIX(NAME, VALUE) const char *NAME[] = VALUE; 58 #include "Options.inc" 59 #undef PREFIX 60 61 // Create table mapping all options defined in Options.td 62 static const opt::OptTable::Info optInfo[] = { 63 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 64 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \ 65 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 66 #include "Options.inc" 67 #undef OPTION 68 }; 69 70 MachOOptTable::MachOOptTable() : OptTable(optInfo) {} 71 72 opt::InputArgList MachOOptTable::parse(ArrayRef<const char *> argv) { 73 // Make InputArgList from string vectors. 74 unsigned missingIndex; 75 unsigned missingCount; 76 SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size()); 77 78 opt::InputArgList args = ParseArgs(vec, missingIndex, missingCount); 79 80 if (missingCount) 81 error(Twine(args.getArgString(missingIndex)) + ": missing argument"); 82 83 for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) 84 error("unknown argument: " + arg->getSpelling()); 85 return args; 86 } 87 88 void MachOOptTable::printHelp(const char *argv0, bool showHidden) const { 89 PrintHelp(lld::outs(), (std::string(argv0) + " [options] file...").c_str(), 90 "LLVM Linker", showHidden); 91 lld::outs() << "\n"; 92 } 93 94 static HeaderFileType getOutputType(const opt::InputArgList &args) { 95 // TODO: -r, -dylinker, -preload... 96 opt::Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute); 97 if (outputArg == nullptr) 98 return MH_EXECUTE; 99 100 switch (outputArg->getOption().getID()) { 101 case OPT_bundle: 102 return MH_BUNDLE; 103 case OPT_dylib: 104 return MH_DYLIB; 105 case OPT_execute: 106 return MH_EXECUTE; 107 default: 108 llvm_unreachable("internal error"); 109 } 110 } 111 112 static Optional<std::string> 113 findAlongPathsWithExtensions(StringRef name, ArrayRef<StringRef> extensions) { 114 llvm::SmallString<261> base; 115 for (StringRef dir : config->librarySearchPaths) { 116 base = dir; 117 path::append(base, Twine("lib") + name); 118 for (StringRef ext : extensions) { 119 Twine location = base + ext; 120 if (fs::exists(location)) 121 return location.str(); 122 } 123 } 124 return {}; 125 } 126 127 static Optional<std::string> findLibrary(StringRef name) { 128 if (config->searchDylibsFirst) { 129 if (Optional<std::string> path = 130 findAlongPathsWithExtensions(name, {".tbd", ".dylib"})) 131 return path; 132 return findAlongPathsWithExtensions(name, {".a"}); 133 } 134 return findAlongPathsWithExtensions(name, {".tbd", ".dylib", ".a"}); 135 } 136 137 static Optional<std::string> findFramework(StringRef name) { 138 llvm::SmallString<260> symlink; 139 StringRef suffix; 140 std::tie(name, suffix) = name.split(","); 141 for (StringRef dir : config->frameworkSearchPaths) { 142 symlink = dir; 143 path::append(symlink, name + ".framework", name); 144 145 if (!suffix.empty()) { 146 // NOTE: we must resolve the symlink before trying the suffixes, because 147 // there are no symlinks for the suffixed paths. 148 llvm::SmallString<260> location; 149 if (!fs::real_path(symlink, location)) { 150 // only append suffix if realpath() succeeds 151 Twine suffixed = location + suffix; 152 if (fs::exists(suffixed)) 153 return suffixed.str(); 154 } 155 // Suffix lookup failed, fall through to the no-suffix case. 156 } 157 158 if (Optional<std::string> path = resolveDylibPath(symlink)) 159 return path; 160 } 161 return {}; 162 } 163 164 static TargetInfo *createTargetInfo(opt::InputArgList &args) { 165 StringRef arch = args.getLastArgValue(OPT_arch, "x86_64"); 166 config->arch = llvm::MachO::getArchitectureFromName( 167 args.getLastArgValue(OPT_arch, arch)); 168 switch (config->arch) { 169 case llvm::MachO::AK_x86_64: 170 case llvm::MachO::AK_x86_64h: 171 return createX86_64TargetInfo(); 172 default: 173 fatal("missing or unsupported -arch " + arch); 174 } 175 } 176 177 static bool warnIfNotDirectory(StringRef option, StringRef path) { 178 if (!fs::exists(path)) { 179 warn("directory not found for option -" + option + path); 180 return false; 181 } else if (!fs::is_directory(path)) { 182 warn("option -" + option + path + " references a non-directory path"); 183 return false; 184 } 185 return true; 186 } 187 188 static std::vector<StringRef> 189 getSearchPaths(unsigned optionCode, opt::InputArgList &args, 190 const std::vector<StringRef> &roots, 191 const SmallVector<StringRef, 2> &systemPaths) { 192 std::vector<StringRef> paths; 193 StringRef optionLetter{optionCode == OPT_F ? "F" : "L"}; 194 for (StringRef path : args::getStrings(args, optionCode)) { 195 // NOTE: only absolute paths are re-rooted to syslibroot(s) 196 bool found = false; 197 if (path::is_absolute(path, path::Style::posix)) { 198 for (StringRef root : roots) { 199 SmallString<261> buffer(root); 200 path::append(buffer, path); 201 // Do not warn about paths that are computed via the syslib roots 202 if (fs::is_directory(buffer)) { 203 paths.push_back(saver.save(buffer.str())); 204 found = true; 205 } 206 } 207 } 208 if (!found && warnIfNotDirectory(optionLetter, path)) 209 paths.push_back(path); 210 } 211 212 // `-Z` suppresses the standard "system" search paths. 213 if (args.hasArg(OPT_Z)) 214 return paths; 215 216 for (auto const &path : systemPaths) { 217 for (auto root : roots) { 218 SmallString<261> buffer(root); 219 path::append(buffer, path); 220 if (warnIfNotDirectory(optionLetter, buffer)) 221 paths.push_back(saver.save(buffer.str())); 222 } 223 } 224 return paths; 225 } 226 227 static std::vector<StringRef> getSystemLibraryRoots(opt::InputArgList &args) { 228 std::vector<StringRef> roots; 229 for (const Arg *arg : args.filtered(OPT_syslibroot)) 230 roots.push_back(arg->getValue()); 231 // NOTE: the final `-syslibroot` being `/` will ignore all roots 232 if (roots.size() && roots.back() == "/") 233 roots.clear(); 234 // NOTE: roots can never be empty - add an empty root to simplify the library 235 // and framework search path computation. 236 if (roots.empty()) 237 roots.emplace_back(""); 238 return roots; 239 } 240 241 static std::vector<StringRef> 242 getLibrarySearchPaths(opt::InputArgList &args, 243 const std::vector<StringRef> &roots) { 244 return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"}); 245 } 246 247 static std::vector<StringRef> 248 getFrameworkSearchPaths(opt::InputArgList &args, 249 const std::vector<StringRef> &roots) { 250 return getSearchPaths(OPT_F, args, roots, 251 {"/Library/Frameworks", "/System/Library/Frameworks"}); 252 } 253 254 // Returns slices of MB by parsing MB as an archive file. 255 // Each slice consists of a member file in the archive. 256 static std::vector<MemoryBufferRef> getArchiveMembers(MemoryBufferRef mb) { 257 std::unique_ptr<Archive> file = 258 CHECK(Archive::create(mb), 259 mb.getBufferIdentifier() + ": failed to parse archive"); 260 261 std::vector<MemoryBufferRef> v; 262 Error err = Error::success(); 263 for (const Archive::Child &c : file->children(err)) { 264 MemoryBufferRef mbref = 265 CHECK(c.getMemoryBufferRef(), 266 mb.getBufferIdentifier() + 267 ": could not get the buffer for a child of the archive"); 268 v.push_back(mbref); 269 } 270 if (err) 271 fatal(mb.getBufferIdentifier() + 272 ": Archive::children failed: " + toString(std::move(err))); 273 274 return v; 275 } 276 277 static InputFile *addFile(StringRef path) { 278 Optional<MemoryBufferRef> buffer = readFile(path); 279 if (!buffer) 280 return nullptr; 281 MemoryBufferRef mbref = *buffer; 282 InputFile *newFile = nullptr; 283 284 switch (identify_magic(mbref.getBuffer())) { 285 case file_magic::archive: { 286 std::unique_ptr<object::Archive> file = CHECK( 287 object::Archive::create(mbref), path + ": failed to parse archive"); 288 289 if (!file->isEmpty() && !file->hasSymbolTable()) 290 error(path + ": archive has no index; run ranlib to add one"); 291 292 if (config->allLoad) { 293 if (Optional<MemoryBufferRef> buffer = readFile(path)) 294 for (MemoryBufferRef member : getArchiveMembers(*buffer)) 295 inputFiles.push_back(make<ObjFile>(member)); 296 } else if (config->forceLoadObjC) { 297 for (const object::Archive::Symbol &sym : file->symbols()) 298 if (sym.getName().startswith(objc::klass)) 299 symtab->addUndefined(sym.getName()); 300 301 // TODO: no need to look for ObjC sections for a given archive member if 302 // we already found that it contains an ObjC symbol. We should also 303 // consider creating a LazyObjFile class in order to avoid double-loading 304 // these files here and below (as part of the ArchiveFile). 305 if (Optional<MemoryBufferRef> buffer = readFile(path)) 306 for (MemoryBufferRef member : getArchiveMembers(*buffer)) 307 if (hasObjCSection(member)) 308 inputFiles.push_back(make<ObjFile>(member)); 309 } 310 311 newFile = make<ArchiveFile>(std::move(file)); 312 break; 313 } 314 case file_magic::macho_object: 315 newFile = make<ObjFile>(mbref); 316 break; 317 case file_magic::macho_dynamically_linked_shared_lib: 318 case file_magic::macho_dynamically_linked_shared_lib_stub: 319 newFile = make<DylibFile>(mbref); 320 break; 321 case file_magic::tapi_file: { 322 if (Optional<DylibFile *> dylibFile = makeDylibFromTAPI(mbref)) 323 newFile = *dylibFile; 324 break; 325 } 326 case file_magic::bitcode: 327 newFile = make<BitcodeFile>(mbref); 328 break; 329 default: 330 error(path + ": unhandled file type"); 331 } 332 if (newFile) 333 inputFiles.push_back(newFile); 334 return newFile; 335 } 336 337 static void addFileList(StringRef path) { 338 Optional<MemoryBufferRef> buffer = readFile(path); 339 if (!buffer) 340 return; 341 MemoryBufferRef mbref = *buffer; 342 for (StringRef path : args::getLines(mbref)) 343 addFile(path); 344 } 345 346 static void forceLoadArchive(StringRef path) { 347 if (Optional<MemoryBufferRef> buffer = readFile(path)) 348 for (MemoryBufferRef member : getArchiveMembers(*buffer)) 349 inputFiles.push_back(make<ObjFile>(member)); 350 } 351 352 static std::array<StringRef, 6> archNames{"arm", "arm64", "i386", 353 "x86_64", "ppc", "ppc64"}; 354 static bool isArchString(StringRef s) { 355 static DenseSet<StringRef> archNamesSet(archNames.begin(), archNames.end()); 356 return archNamesSet.find(s) != archNamesSet.end(); 357 } 358 359 // An order file has one entry per line, in the following format: 360 // 361 // <arch>:<object file>:<symbol name> 362 // 363 // <arch> and <object file> are optional. If not specified, then that entry 364 // matches any symbol of that name. 365 // 366 // If a symbol is matched by multiple entries, then it takes the lowest-ordered 367 // entry (the one nearest to the front of the list.) 368 // 369 // The file can also have line comments that start with '#'. 370 static void parseOrderFile(StringRef path) { 371 Optional<MemoryBufferRef> buffer = readFile(path); 372 if (!buffer) { 373 error("Could not read order file at " + path); 374 return; 375 } 376 377 MemoryBufferRef mbref = *buffer; 378 size_t priority = std::numeric_limits<size_t>::max(); 379 for (StringRef rest : args::getLines(mbref)) { 380 StringRef arch, objectFile, symbol; 381 382 std::array<StringRef, 3> fields; 383 uint8_t fieldCount = 0; 384 while (rest != "" && fieldCount < 3) { 385 std::pair<StringRef, StringRef> p = getToken(rest, ": \t\n\v\f\r"); 386 StringRef tok = p.first; 387 rest = p.second; 388 389 // Check if we have a comment 390 if (tok == "" || tok[0] == '#') 391 break; 392 393 fields[fieldCount++] = tok; 394 } 395 396 switch (fieldCount) { 397 case 3: 398 arch = fields[0]; 399 objectFile = fields[1]; 400 symbol = fields[2]; 401 break; 402 case 2: 403 (isArchString(fields[0]) ? arch : objectFile) = fields[0]; 404 symbol = fields[1]; 405 break; 406 case 1: 407 symbol = fields[0]; 408 break; 409 case 0: 410 break; 411 default: 412 llvm_unreachable("too many fields in order file"); 413 } 414 415 if (!arch.empty()) { 416 if (!isArchString(arch)) { 417 error("invalid arch \"" + arch + "\" in order file: expected one of " + 418 llvm::join(archNames, ", ")); 419 continue; 420 } 421 422 // TODO: Update when we extend support for other archs 423 if (arch != "x86_64") 424 continue; 425 } 426 427 if (!objectFile.empty() && !objectFile.endswith(".o")) { 428 error("invalid object file name \"" + objectFile + 429 "\" in order file: should end with .o"); 430 continue; 431 } 432 433 if (!symbol.empty()) { 434 SymbolPriorityEntry &entry = config->priorities[symbol]; 435 if (!objectFile.empty()) 436 entry.objectFiles.insert(std::make_pair(objectFile, priority)); 437 else 438 entry.anyObjectFile = std::max(entry.anyObjectFile, priority); 439 } 440 441 --priority; 442 } 443 } 444 445 // We expect sub-library names of the form "libfoo", which will match a dylib 446 // with a path of .*/libfoo.{dylib, tbd}. 447 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries; 448 // I'm not sure what the use case for that is. 449 static bool markSubLibrary(StringRef searchName) { 450 for (InputFile *file : inputFiles) { 451 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 452 StringRef filename = path::filename(dylibFile->getName()); 453 if (filename.consume_front(searchName) && 454 (filename == ".dylib" || filename == ".tbd")) { 455 dylibFile->reexport = true; 456 return true; 457 } 458 } 459 } 460 return false; 461 } 462 463 // This function is called on startup. We need this for LTO since 464 // LTO calls LLVM functions to compile bitcode files to native code. 465 // Technically this can be delayed until we read bitcode files, but 466 // we don't bother to do lazily because the initialization is fast. 467 static void initLLVM() { 468 InitializeAllTargets(); 469 InitializeAllTargetMCs(); 470 InitializeAllAsmPrinters(); 471 InitializeAllAsmParsers(); 472 } 473 474 static void compileBitcodeFiles() { 475 auto lto = make<BitcodeCompiler>(); 476 for (InputFile *file : inputFiles) 477 if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file)) 478 lto->add(*bitcodeFile); 479 480 for (ObjFile *file : lto->compile()) 481 inputFiles.push_back(file); 482 } 483 484 // Replaces common symbols with defined symbols residing in __common sections. 485 // This function must be called after all symbol names are resolved (i.e. after 486 // all InputFiles have been loaded.) As a result, later operations won't see 487 // any CommonSymbols. 488 static void replaceCommonSymbols() { 489 for (macho::Symbol *sym : symtab->getSymbols()) { 490 auto *common = dyn_cast<CommonSymbol>(sym); 491 if (common == nullptr) 492 continue; 493 494 auto *isec = make<InputSection>(); 495 isec->file = common->file; 496 isec->name = section_names::common; 497 isec->segname = segment_names::data; 498 isec->align = common->align; 499 // Casting to size_t will truncate large values on 32-bit architectures, 500 // but it's not really worth supporting the linking of 64-bit programs on 501 // 32-bit archs. 502 isec->data = {nullptr, static_cast<size_t>(common->size)}; 503 isec->flags = S_ZEROFILL; 504 inputSections.push_back(isec); 505 506 replaceSymbol<Defined>(sym, sym->getName(), isec, /*value=*/0, 507 /*isWeakDef=*/false, 508 /*isExternal=*/true); 509 } 510 } 511 512 static inline char toLowerDash(char x) { 513 if (x >= 'A' && x <= 'Z') 514 return x - 'A' + 'a'; 515 else if (x == ' ') 516 return '-'; 517 return x; 518 } 519 520 static std::string lowerDash(StringRef s) { 521 return std::string(map_iterator(s.begin(), toLowerDash), 522 map_iterator(s.end(), toLowerDash)); 523 } 524 525 static void handlePlatformVersion(const opt::Arg *arg) { 526 StringRef platformStr = arg->getValue(0); 527 StringRef minVersionStr = arg->getValue(1); 528 StringRef sdkVersionStr = arg->getValue(2); 529 530 // TODO(compnerd) see if we can generate this case list via XMACROS 531 config->platform.kind = 532 llvm::StringSwitch<llvm::MachO::PlatformKind>(lowerDash(platformStr)) 533 .Cases("macos", "1", llvm::MachO::PlatformKind::macOS) 534 .Cases("ios", "2", llvm::MachO::PlatformKind::iOS) 535 .Cases("tvos", "3", llvm::MachO::PlatformKind::tvOS) 536 .Cases("watchos", "4", llvm::MachO::PlatformKind::watchOS) 537 .Cases("bridgeos", "5", llvm::MachO::PlatformKind::bridgeOS) 538 .Cases("mac-catalyst", "6", llvm::MachO::PlatformKind::macCatalyst) 539 .Cases("ios-simulator", "7", llvm::MachO::PlatformKind::iOSSimulator) 540 .Cases("tvos-simulator", "8", 541 llvm::MachO::PlatformKind::tvOSSimulator) 542 .Cases("watchos-simulator", "9", 543 llvm::MachO::PlatformKind::watchOSSimulator) 544 .Default(llvm::MachO::PlatformKind::unknown); 545 if (config->platform.kind == llvm::MachO::PlatformKind::unknown) 546 error(Twine("malformed platform: ") + platformStr); 547 // TODO: check validity of version strings, which varies by platform 548 // NOTE: ld64 accepts version strings with 5 components 549 // llvm::VersionTuple accepts no more than 4 components 550 // Has Apple ever published version strings with 5 components? 551 if (config->platform.minimum.tryParse(minVersionStr)) 552 error(Twine("malformed minimum version: ") + minVersionStr); 553 if (config->platform.sdk.tryParse(sdkVersionStr)) 554 error(Twine("malformed sdk version: ") + sdkVersionStr); 555 } 556 557 static void warnIfDeprecatedOption(const opt::Option &opt) { 558 if (!opt.getGroup().isValid()) 559 return; 560 if (opt.getGroup().getID() == OPT_grp_deprecated) { 561 warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:"); 562 warn(opt.getHelpText()); 563 } 564 } 565 566 static void warnIfUnimplementedOption(const opt::Option &opt) { 567 if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden)) 568 return; 569 switch (opt.getGroup().getID()) { 570 case OPT_grp_deprecated: 571 // warn about deprecated options elsewhere 572 break; 573 case OPT_grp_undocumented: 574 warn("Option `" + opt.getPrefixedName() + 575 "' is undocumented. Should lld implement it?"); 576 break; 577 case OPT_grp_obsolete: 578 warn("Option `" + opt.getPrefixedName() + 579 "' is obsolete. Please modernize your usage."); 580 break; 581 case OPT_grp_ignored: 582 warn("Option `" + opt.getPrefixedName() + "' is ignored."); 583 break; 584 default: 585 warn("Option `" + opt.getPrefixedName() + 586 "' is not yet implemented. Stay tuned..."); 587 break; 588 } 589 } 590 591 bool macho::link(llvm::ArrayRef<const char *> argsArr, bool canExitEarly, 592 raw_ostream &stdoutOS, raw_ostream &stderrOS) { 593 lld::stdoutOS = &stdoutOS; 594 lld::stderrOS = &stderrOS; 595 596 stderrOS.enable_colors(stderrOS.has_colors()); 597 // TODO: Set up error handler properly, e.g. the errorLimitExceededMsg 598 599 errorHandler().cleanupCallback = []() { freeArena(); }; 600 601 MachOOptTable parser; 602 opt::InputArgList args = parser.parse(argsArr.slice(1)); 603 604 if (args.hasArg(OPT_help_hidden)) { 605 parser.printHelp(argsArr[0], /*showHidden=*/true); 606 return true; 607 } else if (args.hasArg(OPT_help)) { 608 parser.printHelp(argsArr[0], /*showHidden=*/false); 609 return true; 610 } 611 612 config = make<Configuration>(); 613 symtab = make<SymbolTable>(); 614 target = createTargetInfo(args); 615 616 config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main")); 617 config->outputFile = args.getLastArgValue(OPT_o, "a.out"); 618 config->installName = 619 args.getLastArgValue(OPT_install_name, config->outputFile); 620 config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32); 621 config->headerPadMaxInstallNames = 622 args.hasArg(OPT_headerpad_max_install_names); 623 config->outputType = getOutputType(args); 624 config->runtimePaths = args::getStrings(args, OPT_rpath); 625 config->allLoad = args.hasArg(OPT_all_load); 626 config->forceLoadObjC = args.hasArg(OPT_ObjC); 627 628 if (const opt::Arg *arg = args.getLastArg(OPT_static, OPT_dynamic)) 629 config->staticLink = (arg->getOption().getID() == OPT_static); 630 631 config->systemLibraryRoots = getSystemLibraryRoots(args); 632 config->librarySearchPaths = 633 getLibrarySearchPaths(args, config->systemLibraryRoots); 634 config->frameworkSearchPaths = 635 getFrameworkSearchPaths(args, config->systemLibraryRoots); 636 if (const opt::Arg *arg = 637 args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first)) 638 config->searchDylibsFirst = 639 (arg && arg->getOption().getID() == OPT_search_dylibs_first); 640 641 config->saveTemps = args.hasArg(OPT_save_temps); 642 643 if (args.hasArg(OPT_v)) { 644 message(getLLDVersion()); 645 message(StringRef("Library search paths:") + 646 (config->librarySearchPaths.size() 647 ? "\n\t" + llvm::join(config->librarySearchPaths, "\n\t") 648 : "")); 649 message(StringRef("Framework search paths:") + 650 (config->frameworkSearchPaths.size() 651 ? "\n\t" + llvm::join(config->frameworkSearchPaths, "\n\t") 652 : "")); 653 freeArena(); 654 return !errorCount(); 655 } 656 657 for (const auto &arg : args) { 658 const auto &opt = arg->getOption(); 659 warnIfDeprecatedOption(opt); 660 warnIfUnimplementedOption(opt); 661 // TODO: are any of these better handled via filtered() or getLastArg()? 662 switch (opt.getID()) { 663 case OPT_INPUT: 664 addFile(arg->getValue()); 665 break; 666 case OPT_weak_library: { 667 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(arg->getValue())); 668 if (dylibFile) 669 dylibFile->forceWeakImport = true; 670 break; 671 } 672 case OPT_filelist: 673 addFileList(arg->getValue()); 674 break; 675 case OPT_force_load: 676 forceLoadArchive(arg->getValue()); 677 break; 678 case OPT_l: 679 case OPT_weak_l: { 680 StringRef name = arg->getValue(); 681 if (Optional<std::string> path = findLibrary(name)) { 682 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path)); 683 if (opt.getID() == OPT_weak_l && dylibFile) 684 dylibFile->forceWeakImport = true; 685 break; 686 } 687 error("library not found for -l" + name); 688 break; 689 } 690 case OPT_framework: 691 case OPT_weak_framework: { 692 StringRef name = arg->getValue(); 693 if (Optional<std::string> path = findFramework(name)) { 694 auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path)); 695 if (opt.getID() == OPT_weak_framework && dylibFile) 696 dylibFile->forceWeakImport = true; 697 break; 698 } 699 error("framework not found for -framework " + name); 700 break; 701 } 702 case OPT_platform_version: 703 handlePlatformVersion(arg); 704 break; 705 default: 706 break; 707 } 708 } 709 710 config->isPic = config->outputType == MH_DYLIB || 711 config->outputType == MH_BUNDLE || 712 (config->outputType == MH_EXECUTE && args.hasArg(OPT_pie)); 713 714 // Now that all dylibs have been loaded, search for those that should be 715 // re-exported. 716 for (opt::Arg *arg : args.filtered(OPT_sub_library)) { 717 config->hasReexports = true; 718 StringRef searchName = arg->getValue(); 719 if (!markSubLibrary(searchName)) 720 error("-sub_library " + searchName + " does not match a supplied dylib"); 721 } 722 723 initLLVM(); 724 compileBitcodeFiles(); 725 replaceCommonSymbols(); 726 727 StringRef orderFile = args.getLastArgValue(OPT_order_file); 728 if (!orderFile.empty()) 729 parseOrderFile(orderFile); 730 731 if (config->outputType == MH_EXECUTE && isa<Undefined>(config->entry)) { 732 error("undefined symbol: " + config->entry->getName()); 733 return false; 734 } 735 736 createSyntheticSections(); 737 symtab->addDSOHandle(in.header); 738 739 for (opt::Arg *arg : args.filtered(OPT_sectcreate)) { 740 StringRef segName = arg->getValue(0); 741 StringRef sectName = arg->getValue(1); 742 StringRef fileName = arg->getValue(2); 743 Optional<MemoryBufferRef> buffer = readFile(fileName); 744 if (buffer) 745 inputFiles.push_back(make<OpaqueFile>(*buffer, segName, sectName)); 746 } 747 748 // Initialize InputSections. 749 for (InputFile *file : inputFiles) { 750 for (SubsectionMap &map : file->subsections) { 751 for (auto &p : map) { 752 InputSection *isec = p.second; 753 inputSections.push_back(isec); 754 } 755 } 756 } 757 758 // Write to an output file. 759 writeResult(); 760 761 if (canExitEarly) 762 exitLld(errorCount() ? 1 : 0); 763 764 return !errorCount(); 765 } 766