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