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