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