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 "ICF.h" 12 #include "InputFiles.h" 13 #include "LTO.h" 14 #include "MarkLive.h" 15 #include "ObjC.h" 16 #include "OutputSection.h" 17 #include "OutputSegment.h" 18 #include "SectionPriorities.h" 19 #include "SymbolTable.h" 20 #include "Symbols.h" 21 #include "SyntheticSections.h" 22 #include "Target.h" 23 #include "UnwindInfoSection.h" 24 #include "Writer.h" 25 26 #include "lld/Common/Args.h" 27 #include "lld/Common/Driver.h" 28 #include "lld/Common/ErrorHandler.h" 29 #include "lld/Common/LLVM.h" 30 #include "lld/Common/Memory.h" 31 #include "lld/Common/Reproduce.h" 32 #include "lld/Common/Version.h" 33 #include "llvm/ADT/DenseSet.h" 34 #include "llvm/ADT/StringExtras.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/BinaryFormat/MachO.h" 37 #include "llvm/BinaryFormat/Magic.h" 38 #include "llvm/Config/llvm-config.h" 39 #include "llvm/LTO/LTO.h" 40 #include "llvm/Object/Archive.h" 41 #include "llvm/Option/ArgList.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/Host.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/Parallel.h" 47 #include "llvm/Support/Path.h" 48 #include "llvm/Support/TarWriter.h" 49 #include "llvm/Support/TargetSelect.h" 50 #include "llvm/Support/TimeProfiler.h" 51 #include "llvm/TextAPI/PackedVersion.h" 52 53 #include <algorithm> 54 55 using namespace llvm; 56 using namespace llvm::MachO; 57 using namespace llvm::object; 58 using namespace llvm::opt; 59 using namespace llvm::sys; 60 using namespace lld; 61 using namespace lld::macho; 62 63 std::unique_ptr<Configuration> macho::config; 64 std::unique_ptr<DependencyTracker> macho::depTracker; 65 66 static HeaderFileType getOutputType(const InputArgList &args) { 67 // TODO: -r, -dylinker, -preload... 68 Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute); 69 if (outputArg == nullptr) 70 return MH_EXECUTE; 71 72 switch (outputArg->getOption().getID()) { 73 case OPT_bundle: 74 return MH_BUNDLE; 75 case OPT_dylib: 76 return MH_DYLIB; 77 case OPT_execute: 78 return MH_EXECUTE; 79 default: 80 llvm_unreachable("internal error"); 81 } 82 } 83 84 static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries; 85 static Optional<StringRef> findLibrary(StringRef name) { 86 CachedHashStringRef key(name); 87 auto entry = resolvedLibraries.find(key); 88 if (entry != resolvedLibraries.end()) 89 return entry->second; 90 91 auto doFind = [&] { 92 if (config->searchDylibsFirst) { 93 if (Optional<StringRef> path = findPathCombination( 94 "lib" + name, config->librarySearchPaths, {".tbd", ".dylib"})) 95 return path; 96 return findPathCombination("lib" + name, config->librarySearchPaths, 97 {".a"}); 98 } 99 return findPathCombination("lib" + name, config->librarySearchPaths, 100 {".tbd", ".dylib", ".a"}); 101 }; 102 103 Optional<StringRef> path = doFind(); 104 if (path) 105 resolvedLibraries[key] = *path; 106 107 return path; 108 } 109 110 static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks; 111 static Optional<StringRef> findFramework(StringRef name) { 112 CachedHashStringRef key(name); 113 auto entry = resolvedFrameworks.find(key); 114 if (entry != resolvedFrameworks.end()) 115 return entry->second; 116 117 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 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 resolvedFrameworks[key] = saver().save(suffixed.str()); 133 } 134 // Suffix lookup failed, fall through to the no-suffix case. 135 } 136 137 if (Optional<StringRef> path = resolveDylibPath(symlink.str())) 138 return resolvedFrameworks[key] = *path; 139 } 140 return {}; 141 } 142 143 static bool warnIfNotDirectory(StringRef option, StringRef path) { 144 if (!fs::exists(path)) { 145 warn("directory not found for option -" + option + path); 146 return false; 147 } else if (!fs::is_directory(path)) { 148 warn("option -" + option + path + " references a non-directory path"); 149 return false; 150 } 151 return true; 152 } 153 154 static std::vector<StringRef> 155 getSearchPaths(unsigned optionCode, InputArgList &args, 156 const std::vector<StringRef> &roots, 157 const SmallVector<StringRef, 2> &systemPaths) { 158 std::vector<StringRef> paths; 159 StringRef optionLetter{optionCode == OPT_F ? "F" : "L"}; 160 for (StringRef path : args::getStrings(args, optionCode)) { 161 // NOTE: only absolute paths are re-rooted to syslibroot(s) 162 bool found = false; 163 if (path::is_absolute(path, path::Style::posix)) { 164 for (StringRef root : roots) { 165 SmallString<261> buffer(root); 166 path::append(buffer, path); 167 // Do not warn about paths that are computed via the syslib roots 168 if (fs::is_directory(buffer)) { 169 paths.push_back(saver().save(buffer.str())); 170 found = true; 171 } 172 } 173 } 174 if (!found && warnIfNotDirectory(optionLetter, path)) 175 paths.push_back(path); 176 } 177 178 // `-Z` suppresses the standard "system" search paths. 179 if (args.hasArg(OPT_Z)) 180 return paths; 181 182 for (const StringRef &path : systemPaths) { 183 for (const StringRef &root : roots) { 184 SmallString<261> buffer(root); 185 path::append(buffer, path); 186 if (fs::is_directory(buffer)) 187 paths.push_back(saver().save(buffer.str())); 188 } 189 } 190 return paths; 191 } 192 193 static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) { 194 std::vector<StringRef> roots; 195 for (const Arg *arg : args.filtered(OPT_syslibroot)) 196 roots.push_back(arg->getValue()); 197 // NOTE: the final `-syslibroot` being `/` will ignore all roots 198 if (!roots.empty() && roots.back() == "/") 199 roots.clear(); 200 // NOTE: roots can never be empty - add an empty root to simplify the library 201 // and framework search path computation. 202 if (roots.empty()) 203 roots.emplace_back(""); 204 return roots; 205 } 206 207 static std::vector<StringRef> 208 getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) { 209 return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"}); 210 } 211 212 static std::vector<StringRef> 213 getFrameworkSearchPaths(InputArgList &args, 214 const std::vector<StringRef> &roots) { 215 return getSearchPaths(OPT_F, args, roots, 216 {"/Library/Frameworks", "/System/Library/Frameworks"}); 217 } 218 219 static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) { 220 SmallString<128> ltoPolicy; 221 auto add = [<oPolicy](Twine val) { 222 if (!ltoPolicy.empty()) 223 ltoPolicy += ":"; 224 val.toVector(ltoPolicy); 225 }; 226 for (const Arg *arg : 227 args.filtered(OPT_thinlto_cache_policy, OPT_prune_interval_lto, 228 OPT_prune_after_lto, OPT_max_relative_cache_size_lto)) { 229 switch (arg->getOption().getID()) { 230 case OPT_thinlto_cache_policy: 231 add(arg->getValue()); 232 break; 233 case OPT_prune_interval_lto: 234 if (!strcmp("-1", arg->getValue())) 235 add("prune_interval=87600h"); // 10 years 236 else 237 add(Twine("prune_interval=") + arg->getValue() + "s"); 238 break; 239 case OPT_prune_after_lto: 240 add(Twine("prune_after=") + arg->getValue() + "s"); 241 break; 242 case OPT_max_relative_cache_size_lto: 243 add(Twine("cache_size=") + arg->getValue() + "%"); 244 break; 245 } 246 } 247 return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy"); 248 } 249 250 static DenseMap<StringRef, ArchiveFile *> loadedArchives; 251 252 static InputFile *addFile(StringRef path, ForceLoad forceLoadArchive, 253 bool isLazy = false, bool isExplicit = true, 254 bool isBundleLoader = false) { 255 Optional<MemoryBufferRef> buffer = readFile(path); 256 if (!buffer) 257 return nullptr; 258 MemoryBufferRef mbref = *buffer; 259 InputFile *newFile = nullptr; 260 261 file_magic magic = identify_magic(mbref.getBuffer()); 262 switch (magic) { 263 case file_magic::archive: { 264 // Avoid loading archives twice. If the archives are being force-loaded, 265 // loading them twice would create duplicate symbol errors. In the 266 // non-force-loading case, this is just a minor performance optimization. 267 // We don't take a reference to cachedFile here because the 268 // loadArchiveMember() call below may recursively call addFile() and 269 // invalidate this reference. 270 auto entry = loadedArchives.find(path); 271 if (entry != loadedArchives.end()) 272 return entry->second; 273 274 std::unique_ptr<object::Archive> archive = CHECK( 275 object::Archive::create(mbref), path + ": failed to parse archive"); 276 277 if (!archive->isEmpty() && !archive->hasSymbolTable()) 278 error(path + ": archive has no index; run ranlib to add one"); 279 280 auto *file = make<ArchiveFile>(std::move(archive)); 281 if ((forceLoadArchive == ForceLoad::Default && config->allLoad) || 282 forceLoadArchive == ForceLoad::Yes) { 283 if (Optional<MemoryBufferRef> buffer = readFile(path)) { 284 Error e = Error::success(); 285 for (const object::Archive::Child &c : file->getArchive().children(e)) { 286 StringRef reason = 287 forceLoadArchive == ForceLoad::Yes ? "-force_load" : "-all_load"; 288 if (Error e = file->fetch(c, reason)) 289 error(toString(file) + ": " + reason + 290 " failed to load archive member: " + toString(std::move(e))); 291 } 292 if (e) 293 error(toString(file) + 294 ": Archive::children failed: " + toString(std::move(e))); 295 } 296 } else if (forceLoadArchive == ForceLoad::Default && 297 config->forceLoadObjC) { 298 for (const object::Archive::Symbol &sym : file->getArchive().symbols()) 299 if (sym.getName().startswith(objc::klass)) 300 file->fetch(sym); 301 302 // TODO: no need to look for ObjC sections for a given archive member if 303 // we already found that it contains an ObjC symbol. 304 if (Optional<MemoryBufferRef> buffer = readFile(path)) { 305 Error e = Error::success(); 306 for (const object::Archive::Child &c : file->getArchive().children(e)) { 307 Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); 308 if (!mb || !hasObjCSection(*mb)) 309 continue; 310 if (Error e = file->fetch(c, "-ObjC")) 311 error(toString(file) + ": -ObjC failed to load archive member: " + 312 toString(std::move(e))); 313 } 314 if (e) 315 error(toString(file) + 316 ": Archive::children failed: " + toString(std::move(e))); 317 } 318 } 319 320 file->addLazySymbols(); 321 newFile = loadedArchives[path] = file; 322 break; 323 } 324 case file_magic::macho_object: 325 newFile = make<ObjFile>(mbref, getModTime(path), "", isLazy); 326 break; 327 case file_magic::macho_dynamically_linked_shared_lib: 328 case file_magic::macho_dynamically_linked_shared_lib_stub: 329 case file_magic::tapi_file: 330 if (DylibFile *dylibFile = 331 loadDylib(mbref, nullptr, /*isBundleLoader=*/false, isExplicit)) 332 newFile = dylibFile; 333 break; 334 case file_magic::bitcode: 335 newFile = make<BitcodeFile>(mbref, "", 0, isLazy); 336 break; 337 case file_magic::macho_executable: 338 case file_magic::macho_bundle: 339 // We only allow executable and bundle type here if it is used 340 // as a bundle loader. 341 if (!isBundleLoader) 342 error(path + ": unhandled file type"); 343 if (DylibFile *dylibFile = loadDylib(mbref, nullptr, isBundleLoader)) 344 newFile = dylibFile; 345 break; 346 default: 347 error(path + ": unhandled file type"); 348 } 349 if (newFile && !isa<DylibFile>(newFile)) { 350 if ((isa<ObjFile>(newFile) || isa<BitcodeFile>(newFile)) && newFile->lazy && 351 config->forceLoadObjC) { 352 for (Symbol *sym : newFile->symbols) 353 if (sym && sym->getName().startswith(objc::klass)) { 354 extract(*newFile, "-ObjC"); 355 break; 356 } 357 if (newFile->lazy && hasObjCSection(mbref)) 358 extract(*newFile, "-ObjC"); 359 } 360 361 // printArchiveMemberLoad() prints both .a and .o names, so no need to 362 // print the .a name here. Similarly skip lazy files. 363 if (config->printEachFile && magic != file_magic::archive && !isLazy) 364 message(toString(newFile)); 365 inputFiles.insert(newFile); 366 } 367 return newFile; 368 } 369 370 static void addLibrary(StringRef name, bool isNeeded, bool isWeak, 371 bool isReexport, bool isExplicit, 372 ForceLoad forceLoadArchive) { 373 if (Optional<StringRef> path = findLibrary(name)) { 374 if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 375 addFile(*path, forceLoadArchive, /*isLazy=*/false, isExplicit))) { 376 if (isNeeded) 377 dylibFile->forceNeeded = true; 378 if (isWeak) 379 dylibFile->forceWeakImport = true; 380 if (isReexport) { 381 config->hasReexports = true; 382 dylibFile->reexport = true; 383 } 384 } 385 return; 386 } 387 error("library not found for -l" + name); 388 } 389 390 static DenseSet<StringRef> loadedObjectFrameworks; 391 static void addFramework(StringRef name, bool isNeeded, bool isWeak, 392 bool isReexport, bool isExplicit, 393 ForceLoad forceLoadArchive) { 394 if (Optional<StringRef> path = findFramework(name)) { 395 if (loadedObjectFrameworks.contains(*path)) 396 return; 397 398 InputFile *file = 399 addFile(*path, forceLoadArchive, /*isLazy=*/false, isExplicit); 400 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(file)) { 401 if (isNeeded) 402 dylibFile->forceNeeded = true; 403 if (isWeak) 404 dylibFile->forceWeakImport = true; 405 if (isReexport) { 406 config->hasReexports = true; 407 dylibFile->reexport = true; 408 } 409 } else if (isa_and_nonnull<ObjFile>(file) || 410 isa_and_nonnull<BitcodeFile>(file)) { 411 // Cache frameworks containing object or bitcode files to avoid duplicate 412 // symbols. Frameworks containing static archives are cached separately 413 // in addFile() to share caching with libraries, and frameworks 414 // containing dylibs should allow overwriting of attributes such as 415 // forceNeeded by subsequent loads 416 loadedObjectFrameworks.insert(*path); 417 } 418 return; 419 } 420 error("framework not found for -framework " + name); 421 } 422 423 // Parses LC_LINKER_OPTION contents, which can add additional command line 424 // flags. This directly parses the flags instead of using the standard argument 425 // parser to improve performance. 426 void macho::parseLCLinkerOption(InputFile *f, unsigned argc, StringRef data) { 427 SmallVector<StringRef, 4> argv; 428 size_t offset = 0; 429 for (unsigned i = 0; i < argc && offset < data.size(); ++i) { 430 argv.push_back(data.data() + offset); 431 offset += strlen(data.data() + offset) + 1; 432 } 433 if (argv.size() != argc || offset > data.size()) 434 fatal(toString(f) + ": invalid LC_LINKER_OPTION"); 435 436 unsigned i = 0; 437 StringRef arg = argv[i]; 438 if (arg.consume_front("-l")) { 439 ForceLoad forceLoadArchive = 440 config->forceLoadSwift && arg.startswith("swift") ? ForceLoad::Yes 441 : ForceLoad::No; 442 addLibrary(arg, /*isNeeded=*/false, /*isWeak=*/false, 443 /*isReexport=*/false, /*isExplicit=*/false, forceLoadArchive); 444 } else if (arg == "-framework") { 445 StringRef name = argv[++i]; 446 addFramework(name, /*isNeeded=*/false, /*isWeak=*/false, 447 /*isReexport=*/false, /*isExplicit=*/false, ForceLoad::No); 448 } else { 449 error(arg + " is not allowed in LC_LINKER_OPTION"); 450 } 451 } 452 453 static void addFileList(StringRef path, bool isLazy) { 454 Optional<MemoryBufferRef> buffer = readFile(path); 455 if (!buffer) 456 return; 457 MemoryBufferRef mbref = *buffer; 458 for (StringRef path : args::getLines(mbref)) 459 addFile(rerootPath(path), ForceLoad::Default, isLazy); 460 } 461 462 // We expect sub-library names of the form "libfoo", which will match a dylib 463 // with a path of .*/libfoo.{dylib, tbd}. 464 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries; 465 // I'm not sure what the use case for that is. 466 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) { 467 for (InputFile *file : inputFiles) { 468 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 469 StringRef filename = path::filename(dylibFile->getName()); 470 if (filename.consume_front(searchName) && 471 (filename.empty() || 472 find(extensions, filename) != extensions.end())) { 473 dylibFile->reexport = true; 474 return true; 475 } 476 } 477 } 478 return false; 479 } 480 481 // This function is called on startup. We need this for LTO since 482 // LTO calls LLVM functions to compile bitcode files to native code. 483 // Technically this can be delayed until we read bitcode files, but 484 // we don't bother to do lazily because the initialization is fast. 485 static void initLLVM() { 486 InitializeAllTargets(); 487 InitializeAllTargetMCs(); 488 InitializeAllAsmPrinters(); 489 InitializeAllAsmParsers(); 490 } 491 492 static void compileBitcodeFiles() { 493 TimeTraceScope timeScope("LTO"); 494 auto *lto = make<BitcodeCompiler>(); 495 for (InputFile *file : inputFiles) 496 if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file)) 497 if (!file->lazy) 498 lto->add(*bitcodeFile); 499 500 for (ObjFile *file : lto->compile()) 501 inputFiles.insert(file); 502 } 503 504 // Replaces common symbols with defined symbols residing in __common sections. 505 // This function must be called after all symbol names are resolved (i.e. after 506 // all InputFiles have been loaded.) As a result, later operations won't see 507 // any CommonSymbols. 508 static void replaceCommonSymbols() { 509 TimeTraceScope timeScope("Replace common symbols"); 510 ConcatOutputSection *osec = nullptr; 511 for (Symbol *sym : symtab->getSymbols()) { 512 auto *common = dyn_cast<CommonSymbol>(sym); 513 if (common == nullptr) 514 continue; 515 516 // Casting to size_t will truncate large values on 32-bit architectures, 517 // but it's not really worth supporting the linking of 64-bit programs on 518 // 32-bit archs. 519 ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)}; 520 // FIXME avoid creating one Section per symbol? 521 auto *section = 522 make<Section>(common->getFile(), segment_names::data, 523 section_names::common, S_ZEROFILL, /*addr=*/0); 524 auto *isec = make<ConcatInputSection>(*section, data, common->align); 525 if (!osec) 526 osec = ConcatOutputSection::getOrCreateForInput(isec); 527 isec->parent = osec; 528 inputSections.push_back(isec); 529 530 // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip 531 // and pass them on here. 532 replaceSymbol<Defined>( 533 sym, sym->getName(), common->getFile(), isec, /*value=*/0, /*size=*/0, 534 /*isWeakDef=*/false, /*isExternal=*/true, common->privateExtern, 535 /*includeInSymtab=*/true, /*isThumb=*/false, 536 /*isReferencedDynamically=*/false, /*noDeadStrip=*/false); 537 } 538 } 539 540 static void initializeSectionRenameMap() { 541 if (config->dataConst) { 542 SmallVector<StringRef> v{section_names::got, 543 section_names::authGot, 544 section_names::authPtr, 545 section_names::nonLazySymbolPtr, 546 section_names::const_, 547 section_names::cfString, 548 section_names::moduleInitFunc, 549 section_names::moduleTermFunc, 550 section_names::objcClassList, 551 section_names::objcNonLazyClassList, 552 section_names::objcCatList, 553 section_names::objcNonLazyCatList, 554 section_names::objcProtoList, 555 section_names::objcImageInfo}; 556 for (StringRef s : v) 557 config->sectionRenameMap[{segment_names::data, s}] = { 558 segment_names::dataConst, s}; 559 } 560 config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = { 561 segment_names::text, section_names::text}; 562 config->sectionRenameMap[{segment_names::import, section_names::pointers}] = { 563 config->dataConst ? segment_names::dataConst : segment_names::data, 564 section_names::nonLazySymbolPtr}; 565 } 566 567 static inline char toLowerDash(char x) { 568 if (x >= 'A' && x <= 'Z') 569 return x - 'A' + 'a'; 570 else if (x == ' ') 571 return '-'; 572 return x; 573 } 574 575 static std::string lowerDash(StringRef s) { 576 return std::string(map_iterator(s.begin(), toLowerDash), 577 map_iterator(s.end(), toLowerDash)); 578 } 579 580 struct PlatformVersion { 581 PlatformType platform = PLATFORM_UNKNOWN; 582 llvm::VersionTuple minimum; 583 llvm::VersionTuple sdk; 584 }; 585 586 static PlatformVersion parsePlatformVersion(const Arg *arg) { 587 assert(arg->getOption().getID() == OPT_platform_version); 588 StringRef platformStr = arg->getValue(0); 589 StringRef minVersionStr = arg->getValue(1); 590 StringRef sdkVersionStr = arg->getValue(2); 591 592 PlatformVersion platformVersion; 593 594 // TODO(compnerd) see if we can generate this case list via XMACROS 595 platformVersion.platform = 596 StringSwitch<PlatformType>(lowerDash(platformStr)) 597 .Cases("macos", "1", PLATFORM_MACOS) 598 .Cases("ios", "2", PLATFORM_IOS) 599 .Cases("tvos", "3", PLATFORM_TVOS) 600 .Cases("watchos", "4", PLATFORM_WATCHOS) 601 .Cases("bridgeos", "5", PLATFORM_BRIDGEOS) 602 .Cases("mac-catalyst", "6", PLATFORM_MACCATALYST) 603 .Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR) 604 .Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR) 605 .Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR) 606 .Cases("driverkit", "10", PLATFORM_DRIVERKIT) 607 .Default(PLATFORM_UNKNOWN); 608 if (platformVersion.platform == PLATFORM_UNKNOWN) 609 error(Twine("malformed platform: ") + platformStr); 610 // TODO: check validity of version strings, which varies by platform 611 // NOTE: ld64 accepts version strings with 5 components 612 // llvm::VersionTuple accepts no more than 4 components 613 // Has Apple ever published version strings with 5 components? 614 if (platformVersion.minimum.tryParse(minVersionStr)) 615 error(Twine("malformed minimum version: ") + minVersionStr); 616 if (platformVersion.sdk.tryParse(sdkVersionStr)) 617 error(Twine("malformed sdk version: ") + sdkVersionStr); 618 return platformVersion; 619 } 620 621 // Has the side-effect of setting Config::platformInfo. 622 static PlatformType parsePlatformVersions(const ArgList &args) { 623 std::map<PlatformType, PlatformVersion> platformVersions; 624 const PlatformVersion *lastVersionInfo = nullptr; 625 for (const Arg *arg : args.filtered(OPT_platform_version)) { 626 PlatformVersion version = parsePlatformVersion(arg); 627 628 // For each platform, the last flag wins: 629 // `-platform_version macos 2 3 -platform_version macos 4 5` has the same 630 // effect as just passing `-platform_version macos 4 5`. 631 // FIXME: ld64 warns on multiple flags for one platform. Should we? 632 platformVersions[version.platform] = version; 633 lastVersionInfo = &platformVersions[version.platform]; 634 } 635 636 if (platformVersions.empty()) { 637 error("must specify -platform_version"); 638 return PLATFORM_UNKNOWN; 639 } 640 if (platformVersions.size() > 2) { 641 error("must specify -platform_version at most twice"); 642 return PLATFORM_UNKNOWN; 643 } 644 if (platformVersions.size() == 2) { 645 // FIXME: If you implement support for this, add a diagnostic if 646 // outputType is not dylib or bundle -- linkers shouldn't be able to 647 // write zippered executables. 648 warn("writing zippered outputs not yet implemented, " 649 "ignoring all but last -platform_version flag"); 650 } 651 config->platformInfo.minimum = lastVersionInfo->minimum; 652 config->platformInfo.sdk = lastVersionInfo->sdk; 653 return lastVersionInfo->platform; 654 } 655 656 // Has the side-effect of setting Config::target. 657 static TargetInfo *createTargetInfo(InputArgList &args) { 658 StringRef archName = args.getLastArgValue(OPT_arch); 659 if (archName.empty()) { 660 error("must specify -arch"); 661 return nullptr; 662 } 663 664 PlatformType platform = parsePlatformVersions(args); 665 config->platformInfo.target = 666 MachO::Target(getArchitectureFromName(archName), platform); 667 668 uint32_t cpuType; 669 uint32_t cpuSubtype; 670 std::tie(cpuType, cpuSubtype) = getCPUTypeFromArchitecture(config->arch()); 671 672 switch (cpuType) { 673 case CPU_TYPE_X86_64: 674 return createX86_64TargetInfo(); 675 case CPU_TYPE_ARM64: 676 return createARM64TargetInfo(); 677 case CPU_TYPE_ARM64_32: 678 return createARM64_32TargetInfo(); 679 case CPU_TYPE_ARM: 680 return createARMTargetInfo(cpuSubtype); 681 default: 682 error("missing or unsupported -arch " + archName); 683 return nullptr; 684 } 685 } 686 687 static UndefinedSymbolTreatment 688 getUndefinedSymbolTreatment(const ArgList &args) { 689 StringRef treatmentStr = args.getLastArgValue(OPT_undefined); 690 auto treatment = 691 StringSwitch<UndefinedSymbolTreatment>(treatmentStr) 692 .Cases("error", "", UndefinedSymbolTreatment::error) 693 .Case("warning", UndefinedSymbolTreatment::warning) 694 .Case("suppress", UndefinedSymbolTreatment::suppress) 695 .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup) 696 .Default(UndefinedSymbolTreatment::unknown); 697 if (treatment == UndefinedSymbolTreatment::unknown) { 698 warn(Twine("unknown -undefined TREATMENT '") + treatmentStr + 699 "', defaulting to 'error'"); 700 treatment = UndefinedSymbolTreatment::error; 701 } else if (config->namespaceKind == NamespaceKind::twolevel && 702 (treatment == UndefinedSymbolTreatment::warning || 703 treatment == UndefinedSymbolTreatment::suppress)) { 704 if (treatment == UndefinedSymbolTreatment::warning) 705 error("'-undefined warning' only valid with '-flat_namespace'"); 706 else 707 error("'-undefined suppress' only valid with '-flat_namespace'"); 708 treatment = UndefinedSymbolTreatment::error; 709 } 710 return treatment; 711 } 712 713 static ICFLevel getICFLevel(const ArgList &args) { 714 StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq); 715 auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr) 716 .Cases("none", "", ICFLevel::none) 717 .Case("safe", ICFLevel::safe) 718 .Case("all", ICFLevel::all) 719 .Default(ICFLevel::unknown); 720 if (icfLevel == ICFLevel::unknown) { 721 warn(Twine("unknown --icf=OPTION `") + icfLevelStr + 722 "', defaulting to `none'"); 723 icfLevel = ICFLevel::none; 724 } 725 return icfLevel; 726 } 727 728 static void warnIfDeprecatedOption(const Option &opt) { 729 if (!opt.getGroup().isValid()) 730 return; 731 if (opt.getGroup().getID() == OPT_grp_deprecated) { 732 warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:"); 733 warn(opt.getHelpText()); 734 } 735 } 736 737 static void warnIfUnimplementedOption(const Option &opt) { 738 if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden)) 739 return; 740 switch (opt.getGroup().getID()) { 741 case OPT_grp_deprecated: 742 // warn about deprecated options elsewhere 743 break; 744 case OPT_grp_undocumented: 745 warn("Option `" + opt.getPrefixedName() + 746 "' is undocumented. Should lld implement it?"); 747 break; 748 case OPT_grp_obsolete: 749 warn("Option `" + opt.getPrefixedName() + 750 "' is obsolete. Please modernize your usage."); 751 break; 752 case OPT_grp_ignored: 753 warn("Option `" + opt.getPrefixedName() + "' is ignored."); 754 break; 755 case OPT_grp_ignored_silently: 756 break; 757 default: 758 warn("Option `" + opt.getPrefixedName() + 759 "' is not yet implemented. Stay tuned..."); 760 break; 761 } 762 } 763 764 static const char *getReproduceOption(InputArgList &args) { 765 if (const Arg *arg = args.getLastArg(OPT_reproduce)) 766 return arg->getValue(); 767 return getenv("LLD_REPRODUCE"); 768 } 769 770 static void parseClangOption(StringRef opt, const Twine &msg) { 771 std::string err; 772 raw_string_ostream os(err); 773 774 const char *argv[] = {"lld", opt.data()}; 775 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 776 return; 777 os.flush(); 778 error(msg + ": " + StringRef(err).trim()); 779 } 780 781 static uint32_t parseDylibVersion(const ArgList &args, unsigned id) { 782 const Arg *arg = args.getLastArg(id); 783 if (!arg) 784 return 0; 785 786 if (config->outputType != MH_DYLIB) { 787 error(arg->getAsString(args) + ": only valid with -dylib"); 788 return 0; 789 } 790 791 PackedVersion version; 792 if (!version.parse32(arg->getValue())) { 793 error(arg->getAsString(args) + ": malformed version"); 794 return 0; 795 } 796 797 return version.rawValue(); 798 } 799 800 static uint32_t parseProtection(StringRef protStr) { 801 uint32_t prot = 0; 802 for (char c : protStr) { 803 switch (c) { 804 case 'r': 805 prot |= VM_PROT_READ; 806 break; 807 case 'w': 808 prot |= VM_PROT_WRITE; 809 break; 810 case 'x': 811 prot |= VM_PROT_EXECUTE; 812 break; 813 case '-': 814 break; 815 default: 816 error("unknown -segprot letter '" + Twine(c) + "' in " + protStr); 817 return 0; 818 } 819 } 820 return prot; 821 } 822 823 static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) { 824 std::vector<SectionAlign> sectAligns; 825 for (const Arg *arg : args.filtered(OPT_sectalign)) { 826 StringRef segName = arg->getValue(0); 827 StringRef sectName = arg->getValue(1); 828 StringRef alignStr = arg->getValue(2); 829 if (alignStr.startswith("0x") || alignStr.startswith("0X")) 830 alignStr = alignStr.drop_front(2); 831 uint32_t align; 832 if (alignStr.getAsInteger(16, align)) { 833 error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) + 834 "' as number"); 835 continue; 836 } 837 if (!isPowerOf2_32(align)) { 838 error("-sectalign: '" + StringRef(arg->getValue(2)) + 839 "' (in base 16) not a power of two"); 840 continue; 841 } 842 sectAligns.push_back({segName, sectName, align}); 843 } 844 return sectAligns; 845 } 846 847 PlatformType macho::removeSimulator(PlatformType platform) { 848 switch (platform) { 849 case PLATFORM_IOSSIMULATOR: 850 return PLATFORM_IOS; 851 case PLATFORM_TVOSSIMULATOR: 852 return PLATFORM_TVOS; 853 case PLATFORM_WATCHOSSIMULATOR: 854 return PLATFORM_WATCHOS; 855 default: 856 return platform; 857 } 858 } 859 860 static bool dataConstDefault(const InputArgList &args) { 861 static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = { 862 {PLATFORM_MACOS, VersionTuple(10, 15)}, 863 {PLATFORM_IOS, VersionTuple(13, 0)}, 864 {PLATFORM_TVOS, VersionTuple(13, 0)}, 865 {PLATFORM_WATCHOS, VersionTuple(6, 0)}, 866 {PLATFORM_BRIDGEOS, VersionTuple(4, 0)}}; 867 PlatformType platform = removeSimulator(config->platformInfo.target.Platform); 868 auto it = llvm::find_if(minVersion, 869 [&](const auto &p) { return p.first == platform; }); 870 if (it != minVersion.end()) 871 if (config->platformInfo.minimum < it->second) 872 return false; 873 874 switch (config->outputType) { 875 case MH_EXECUTE: 876 return !args.hasArg(OPT_no_pie); 877 case MH_BUNDLE: 878 // FIXME: return false when -final_name ... 879 // has prefix "/System/Library/UserEventPlugins/" 880 // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd" 881 return true; 882 case MH_DYLIB: 883 return true; 884 case MH_OBJECT: 885 return false; 886 default: 887 llvm_unreachable( 888 "unsupported output type for determining data-const default"); 889 } 890 return false; 891 } 892 893 void SymbolPatterns::clear() { 894 literals.clear(); 895 globs.clear(); 896 } 897 898 void SymbolPatterns::insert(StringRef symbolName) { 899 if (symbolName.find_first_of("*?[]") == StringRef::npos) 900 literals.insert(CachedHashStringRef(symbolName)); 901 else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName)) 902 globs.emplace_back(*pattern); 903 else 904 error("invalid symbol-name pattern: " + symbolName); 905 } 906 907 bool SymbolPatterns::matchLiteral(StringRef symbolName) const { 908 return literals.contains(CachedHashStringRef(symbolName)); 909 } 910 911 bool SymbolPatterns::matchGlob(StringRef symbolName) const { 912 for (const GlobPattern &glob : globs) 913 if (glob.match(symbolName)) 914 return true; 915 return false; 916 } 917 918 bool SymbolPatterns::match(StringRef symbolName) const { 919 return matchLiteral(symbolName) || matchGlob(symbolName); 920 } 921 922 static void handleSymbolPatterns(InputArgList &args, 923 SymbolPatterns &symbolPatterns, 924 unsigned singleOptionCode, 925 unsigned listFileOptionCode) { 926 for (const Arg *arg : args.filtered(singleOptionCode)) 927 symbolPatterns.insert(arg->getValue()); 928 for (const Arg *arg : args.filtered(listFileOptionCode)) { 929 StringRef path = arg->getValue(); 930 Optional<MemoryBufferRef> buffer = readFile(path); 931 if (!buffer) { 932 error("Could not read symbol file: " + path); 933 continue; 934 } 935 MemoryBufferRef mbref = *buffer; 936 for (StringRef line : args::getLines(mbref)) { 937 line = line.take_until([](char c) { return c == '#'; }).trim(); 938 if (!line.empty()) 939 symbolPatterns.insert(line); 940 } 941 } 942 } 943 944 static void createFiles(const InputArgList &args) { 945 TimeTraceScope timeScope("Load input files"); 946 // This loop should be reserved for options whose exact ordering matters. 947 // Other options should be handled via filtered() and/or getLastArg(). 948 bool isLazy = false; 949 for (const Arg *arg : args) { 950 const Option &opt = arg->getOption(); 951 warnIfDeprecatedOption(opt); 952 warnIfUnimplementedOption(opt); 953 954 switch (opt.getID()) { 955 case OPT_INPUT: 956 addFile(rerootPath(arg->getValue()), ForceLoad::Default, isLazy); 957 break; 958 case OPT_needed_library: 959 if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 960 addFile(rerootPath(arg->getValue()), ForceLoad::Default))) 961 dylibFile->forceNeeded = true; 962 break; 963 case OPT_reexport_library: 964 if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 965 addFile(rerootPath(arg->getValue()), ForceLoad::Default))) { 966 config->hasReexports = true; 967 dylibFile->reexport = true; 968 } 969 break; 970 case OPT_weak_library: 971 if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 972 addFile(rerootPath(arg->getValue()), ForceLoad::Default))) 973 dylibFile->forceWeakImport = true; 974 break; 975 case OPT_filelist: 976 addFileList(arg->getValue(), isLazy); 977 break; 978 case OPT_force_load: 979 addFile(rerootPath(arg->getValue()), ForceLoad::Yes); 980 break; 981 case OPT_l: 982 case OPT_needed_l: 983 case OPT_reexport_l: 984 case OPT_weak_l: 985 addLibrary(arg->getValue(), opt.getID() == OPT_needed_l, 986 opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l, 987 /*isExplicit=*/true, ForceLoad::Default); 988 break; 989 case OPT_framework: 990 case OPT_needed_framework: 991 case OPT_reexport_framework: 992 case OPT_weak_framework: 993 addFramework(arg->getValue(), opt.getID() == OPT_needed_framework, 994 opt.getID() == OPT_weak_framework, 995 opt.getID() == OPT_reexport_framework, /*isExplicit=*/true, 996 ForceLoad::Default); 997 break; 998 case OPT_start_lib: 999 if (isLazy) 1000 error("nested --start-lib"); 1001 isLazy = true; 1002 break; 1003 case OPT_end_lib: 1004 if (!isLazy) 1005 error("stray --end-lib"); 1006 isLazy = false; 1007 break; 1008 default: 1009 break; 1010 } 1011 } 1012 } 1013 1014 static void gatherInputSections() { 1015 TimeTraceScope timeScope("Gathering input sections"); 1016 int inputOrder = 0; 1017 for (const InputFile *file : inputFiles) { 1018 for (const Section *section : file->sections) { 1019 if (section->name == section_names::compactUnwind) 1020 // Compact unwind entries require special handling elsewhere. 1021 continue; 1022 ConcatOutputSection *osec = nullptr; 1023 for (const Subsection &subsection : section->subsections) { 1024 if (auto *isec = dyn_cast<ConcatInputSection>(subsection.isec)) { 1025 if (isec->isCoalescedWeak()) 1026 continue; 1027 isec->outSecOff = inputOrder++; 1028 if (!osec) 1029 osec = ConcatOutputSection::getOrCreateForInput(isec); 1030 isec->parent = osec; 1031 inputSections.push_back(isec); 1032 } else if (auto *isec = 1033 dyn_cast<CStringInputSection>(subsection.isec)) { 1034 if (in.cStringSection->inputOrder == UnspecifiedInputOrder) 1035 in.cStringSection->inputOrder = inputOrder++; 1036 in.cStringSection->addInput(isec); 1037 } else if (auto *isec = 1038 dyn_cast<WordLiteralInputSection>(subsection.isec)) { 1039 if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder) 1040 in.wordLiteralSection->inputOrder = inputOrder++; 1041 in.wordLiteralSection->addInput(isec); 1042 } else { 1043 llvm_unreachable("unexpected input section kind"); 1044 } 1045 } 1046 } 1047 } 1048 assert(inputOrder <= UnspecifiedInputOrder); 1049 } 1050 1051 static void foldIdenticalLiterals() { 1052 // We always create a cStringSection, regardless of whether dedupLiterals is 1053 // true. If it isn't, we simply create a non-deduplicating CStringSection. 1054 // Either way, we must unconditionally finalize it here. 1055 in.cStringSection->finalizeContents(); 1056 if (in.wordLiteralSection) 1057 in.wordLiteralSection->finalizeContents(); 1058 } 1059 1060 static void referenceStubBinder() { 1061 bool needsStubHelper = config->outputType == MH_DYLIB || 1062 config->outputType == MH_EXECUTE || 1063 config->outputType == MH_BUNDLE; 1064 if (!needsStubHelper || !symtab->find("dyld_stub_binder")) 1065 return; 1066 1067 // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here 1068 // adds a opportunistic reference to dyld_stub_binder if it happens to exist. 1069 // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This 1070 // isn't needed for correctness, but the presence of that symbol suppresses 1071 // "no symbols" diagnostics from `nm`. 1072 // StubHelperSection::setup() adds a reference and errors out if 1073 // dyld_stub_binder doesn't exist in case it is actually needed. 1074 symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false); 1075 } 1076 1077 bool macho::link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS, 1078 llvm::raw_ostream &stderrOS, bool exitEarly, 1079 bool disableOutput) { 1080 // This driver-specific context will be freed later by lldMain(). 1081 auto *ctx = new CommonLinkerContext; 1082 1083 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 1084 ctx->e.cleanupCallback = []() { 1085 resolvedFrameworks.clear(); 1086 resolvedLibraries.clear(); 1087 cachedReads.clear(); 1088 concatOutputSections.clear(); 1089 inputFiles.clear(); 1090 inputSections.clear(); 1091 loadedArchives.clear(); 1092 loadedObjectFrameworks.clear(); 1093 syntheticSections.clear(); 1094 thunkMap.clear(); 1095 1096 firstTLVDataSection = nullptr; 1097 tar = nullptr; 1098 memset(&in, 0, sizeof(in)); 1099 1100 resetLoadedDylibs(); 1101 resetOutputSegments(); 1102 resetWriter(); 1103 InputFile::resetIdCount(); 1104 }; 1105 1106 ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]); 1107 1108 MachOOptTable parser; 1109 InputArgList args = parser.parse(argsArr.slice(1)); 1110 1111 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now " 1112 "(use --error-limit=0 to see all errors)"; 1113 ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20); 1114 ctx->e.verbose = args.hasArg(OPT_verbose); 1115 1116 if (args.hasArg(OPT_help_hidden)) { 1117 parser.printHelp(argsArr[0], /*showHidden=*/true); 1118 return true; 1119 } 1120 if (args.hasArg(OPT_help)) { 1121 parser.printHelp(argsArr[0], /*showHidden=*/false); 1122 return true; 1123 } 1124 if (args.hasArg(OPT_version)) { 1125 message(getLLDVersion()); 1126 return true; 1127 } 1128 1129 config = std::make_unique<Configuration>(); 1130 symtab = std::make_unique<SymbolTable>(); 1131 target = createTargetInfo(args); 1132 depTracker = std::make_unique<DependencyTracker>( 1133 args.getLastArgValue(OPT_dependency_info)); 1134 if (errorCount()) 1135 return false; 1136 1137 if (args.hasArg(OPT_pagezero_size)) { 1138 uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0); 1139 1140 // ld64 does something really weird. It attempts to realign the value to the 1141 // page size, but assumes the the page size is 4K. This doesn't work with 1142 // most of Apple's ARM64 devices, which use a page size of 16K. This means 1143 // that it will first 4K align it by rounding down, then round up to 16K. 1144 // This probably only happened because no one using this arg with anything 1145 // other then 0, so no one checked if it did what is what it says it does. 1146 1147 // So we are not copying this weird behavior and doing the it in a logical 1148 // way, by always rounding down to page size. 1149 if (!isAligned(Align(target->getPageSize()), pagezeroSize)) { 1150 pagezeroSize -= pagezeroSize % target->getPageSize(); 1151 warn("__PAGEZERO size is not page aligned, rounding down to 0x" + 1152 Twine::utohexstr(pagezeroSize)); 1153 } 1154 1155 target->pageZeroSize = pagezeroSize; 1156 } 1157 1158 config->osoPrefix = args.getLastArgValue(OPT_oso_prefix); 1159 if (!config->osoPrefix.empty()) { 1160 // Expand special characters, such as ".", "..", or "~", if present. 1161 // Note: LD64 only expands "." and not other special characters. 1162 // That seems silly to imitate so we will not try to follow it, but rather 1163 // just use real_path() to do it. 1164 1165 // The max path length is 4096, in theory. However that seems quite long 1166 // and seems unlikely that any one would want to strip everything from the 1167 // path. Hence we've picked a reasonably large number here. 1168 SmallString<1024> expanded; 1169 if (!fs::real_path(config->osoPrefix, expanded, 1170 /*expand_tilde=*/true)) { 1171 // Note: LD64 expands "." to be `<current_dir>/` 1172 // (ie., it has a slash suffix) whereas real_path() doesn't. 1173 // So we have to append '/' to be consistent. 1174 StringRef sep = sys::path::get_separator(); 1175 // real_path removes trailing slashes as part of the normalization, but 1176 // these are meaningful for our text based stripping 1177 if (config->osoPrefix.equals(".") || config->osoPrefix.endswith(sep)) 1178 expanded += sep; 1179 config->osoPrefix = saver().save(expanded.str()); 1180 } 1181 } 1182 1183 // Must be set before any InputSections and Symbols are created. 1184 config->deadStrip = args.hasArg(OPT_dead_strip); 1185 1186 config->systemLibraryRoots = getSystemLibraryRoots(args); 1187 if (const char *path = getReproduceOption(args)) { 1188 // Note that --reproduce is a debug option so you can ignore it 1189 // if you are trying to understand the whole picture of the code. 1190 Expected<std::unique_ptr<TarWriter>> errOrWriter = 1191 TarWriter::create(path, path::stem(path)); 1192 if (errOrWriter) { 1193 tar = std::move(*errOrWriter); 1194 tar->append("response.txt", createResponseFile(args)); 1195 tar->append("version.txt", getLLDVersion() + "\n"); 1196 } else { 1197 error("--reproduce: " + toString(errOrWriter.takeError())); 1198 } 1199 } 1200 1201 if (auto *arg = args.getLastArg(OPT_threads_eq)) { 1202 StringRef v(arg->getValue()); 1203 unsigned threads = 0; 1204 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1205 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1206 arg->getValue() + "'"); 1207 parallel::strategy = hardware_concurrency(threads); 1208 config->thinLTOJobs = v; 1209 } 1210 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq)) 1211 config->thinLTOJobs = arg->getValue(); 1212 if (!get_threadpool_strategy(config->thinLTOJobs)) 1213 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 1214 1215 for (const Arg *arg : args.filtered(OPT_u)) { 1216 config->explicitUndefineds.push_back(symtab->addUndefined( 1217 arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false)); 1218 } 1219 1220 for (const Arg *arg : args.filtered(OPT_U)) 1221 config->explicitDynamicLookups.insert(arg->getValue()); 1222 1223 config->mapFile = args.getLastArgValue(OPT_map); 1224 config->optimize = args::getInteger(args, OPT_O, 1); 1225 config->outputFile = args.getLastArgValue(OPT_o, "a.out"); 1226 config->finalOutput = 1227 args.getLastArgValue(OPT_final_output, config->outputFile); 1228 config->astPaths = args.getAllArgValues(OPT_add_ast_path); 1229 config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32); 1230 config->headerPadMaxInstallNames = 1231 args.hasArg(OPT_headerpad_max_install_names); 1232 config->printDylibSearch = 1233 args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING"); 1234 config->printEachFile = args.hasArg(OPT_t); 1235 config->printWhyLoad = args.hasArg(OPT_why_load); 1236 config->omitDebugInfo = args.hasArg(OPT_S); 1237 config->outputType = getOutputType(args); 1238 config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal); 1239 if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) { 1240 if (config->outputType != MH_BUNDLE) 1241 error("-bundle_loader can only be used with MachO bundle output"); 1242 addFile(arg->getValue(), ForceLoad::Default, /*isLazy=*/false, 1243 /*isExplicit=*/false, 1244 /*isBundleLoader=*/true); 1245 } 1246 if (const Arg *arg = args.getLastArg(OPT_umbrella)) { 1247 if (config->outputType != MH_DYLIB) 1248 warn("-umbrella used, but not creating dylib"); 1249 config->umbrella = arg->getValue(); 1250 } 1251 config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto); 1252 config->ltoo = args::getInteger(args, OPT_lto_O, 2); 1253 if (config->ltoo > 3) 1254 error("--lto-O: invalid optimization level: " + Twine(config->ltoo)); 1255 config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto); 1256 config->thinLTOCachePolicy = getLTOCachePolicy(args); 1257 config->runtimePaths = args::getStrings(args, OPT_rpath); 1258 config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false); 1259 config->archMultiple = args.hasArg(OPT_arch_multiple); 1260 config->applicationExtension = args.hasFlag( 1261 OPT_application_extension, OPT_no_application_extension, false); 1262 config->exportDynamic = args.hasArg(OPT_export_dynamic); 1263 config->forceLoadObjC = args.hasArg(OPT_ObjC); 1264 config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs); 1265 config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs); 1266 config->demangle = args.hasArg(OPT_demangle); 1267 config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs); 1268 config->emitFunctionStarts = 1269 args.hasFlag(OPT_function_starts, OPT_no_function_starts, true); 1270 config->emitBitcodeBundle = args.hasArg(OPT_bitcode_bundle); 1271 config->emitDataInCodeInfo = 1272 args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true); 1273 config->icfLevel = getICFLevel(args); 1274 config->dedupLiterals = 1275 args.hasFlag(OPT_deduplicate_literals, OPT_icf_eq, false) || 1276 config->icfLevel != ICFLevel::none; 1277 config->warnDylibInstallName = args.hasFlag( 1278 OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false); 1279 config->callGraphProfileSort = args.hasFlag( 1280 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 1281 config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order); 1282 1283 // FIXME: Add a commandline flag for this too. 1284 config->zeroModTime = getenv("ZERO_AR_DATE"); 1285 1286 std::array<PlatformType, 3> encryptablePlatforms{ 1287 PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS}; 1288 config->emitEncryptionInfo = 1289 args.hasFlag(OPT_encryptable, OPT_no_encryption, 1290 is_contained(encryptablePlatforms, config->platform())); 1291 1292 #ifndef LLVM_HAVE_LIBXAR 1293 if (config->emitBitcodeBundle) 1294 error("-bitcode_bundle unsupported because LLD wasn't built with libxar"); 1295 #endif 1296 1297 if (const Arg *arg = args.getLastArg(OPT_install_name)) { 1298 if (config->warnDylibInstallName && config->outputType != MH_DYLIB) 1299 warn( 1300 arg->getAsString(args) + 1301 ": ignored, only has effect with -dylib [--warn-dylib-install-name]"); 1302 else 1303 config->installName = arg->getValue(); 1304 } else if (config->outputType == MH_DYLIB) { 1305 config->installName = config->finalOutput; 1306 } 1307 1308 if (args.hasArg(OPT_mark_dead_strippable_dylib)) { 1309 if (config->outputType != MH_DYLIB) 1310 warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib"); 1311 else 1312 config->markDeadStrippableDylib = true; 1313 } 1314 1315 if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic)) 1316 config->staticLink = (arg->getOption().getID() == OPT_static); 1317 1318 if (const Arg *arg = 1319 args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) 1320 config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace 1321 ? NamespaceKind::twolevel 1322 : NamespaceKind::flat; 1323 1324 config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args); 1325 1326 if (config->outputType == MH_EXECUTE) 1327 config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"), 1328 /*file=*/nullptr, 1329 /*isWeakRef=*/false); 1330 1331 config->librarySearchPaths = 1332 getLibrarySearchPaths(args, config->systemLibraryRoots); 1333 config->frameworkSearchPaths = 1334 getFrameworkSearchPaths(args, config->systemLibraryRoots); 1335 if (const Arg *arg = 1336 args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first)) 1337 config->searchDylibsFirst = 1338 arg->getOption().getID() == OPT_search_dylibs_first; 1339 1340 config->dylibCompatibilityVersion = 1341 parseDylibVersion(args, OPT_compatibility_version); 1342 config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version); 1343 1344 config->dataConst = 1345 args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args)); 1346 // Populate config->sectionRenameMap with builtin default renames. 1347 // Options -rename_section and -rename_segment are able to override. 1348 initializeSectionRenameMap(); 1349 // Reject every special character except '.' and '$' 1350 // TODO(gkm): verify that this is the proper set of invalid chars 1351 StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~"); 1352 auto validName = [invalidNameChars](StringRef s) { 1353 if (s.find_first_of(invalidNameChars) != StringRef::npos) 1354 error("invalid name for segment or section: " + s); 1355 return s; 1356 }; 1357 for (const Arg *arg : args.filtered(OPT_rename_section)) { 1358 config->sectionRenameMap[{validName(arg->getValue(0)), 1359 validName(arg->getValue(1))}] = { 1360 validName(arg->getValue(2)), validName(arg->getValue(3))}; 1361 } 1362 for (const Arg *arg : args.filtered(OPT_rename_segment)) { 1363 config->segmentRenameMap[validName(arg->getValue(0))] = 1364 validName(arg->getValue(1)); 1365 } 1366 1367 config->sectionAlignments = parseSectAlign(args); 1368 1369 for (const Arg *arg : args.filtered(OPT_segprot)) { 1370 StringRef segName = arg->getValue(0); 1371 uint32_t maxProt = parseProtection(arg->getValue(1)); 1372 uint32_t initProt = parseProtection(arg->getValue(2)); 1373 if (maxProt != initProt && config->arch() != AK_i386) 1374 error("invalid argument '" + arg->getAsString(args) + 1375 "': max and init must be the same for non-i386 archs"); 1376 if (segName == segment_names::linkEdit) 1377 error("-segprot cannot be used to change __LINKEDIT's protections"); 1378 config->segmentProtections.push_back({segName, maxProt, initProt}); 1379 } 1380 1381 handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol, 1382 OPT_exported_symbols_list); 1383 handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol, 1384 OPT_unexported_symbols_list); 1385 if (!config->exportedSymbols.empty() && !config->unexportedSymbols.empty()) { 1386 error("cannot use both -exported_symbol* and -unexported_symbol* options\n" 1387 ">>> ignoring unexports"); 1388 config->unexportedSymbols.clear(); 1389 } 1390 // Explicitly-exported literal symbols must be defined, but might 1391 // languish in an archive if unreferenced elsewhere. Light a fire 1392 // under those lazy symbols! 1393 for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals) 1394 symtab->addUndefined(cachedName.val(), /*file=*/nullptr, 1395 /*isWeakRef=*/false); 1396 1397 for (const Arg *arg : args.filtered(OPT_why_live)) 1398 config->whyLive.insert(arg->getValue()); 1399 if (!config->whyLive.empty() && !config->deadStrip) 1400 warn("-why_live has no effect without -dead_strip, ignoring"); 1401 1402 config->saveTemps = args.hasArg(OPT_save_temps); 1403 1404 config->adhocCodesign = args.hasFlag( 1405 OPT_adhoc_codesign, OPT_no_adhoc_codesign, 1406 (config->arch() == AK_arm64 || config->arch() == AK_arm64e) && 1407 config->platform() == PLATFORM_MACOS); 1408 1409 if (args.hasArg(OPT_v)) { 1410 message(getLLDVersion(), lld::errs()); 1411 message(StringRef("Library search paths:") + 1412 (config->librarySearchPaths.empty() 1413 ? "" 1414 : "\n\t" + join(config->librarySearchPaths, "\n\t")), 1415 lld::errs()); 1416 message(StringRef("Framework search paths:") + 1417 (config->frameworkSearchPaths.empty() 1418 ? "" 1419 : "\n\t" + join(config->frameworkSearchPaths, "\n\t")), 1420 lld::errs()); 1421 } 1422 1423 config->progName = argsArr[0]; 1424 1425 config->timeTraceEnabled = args.hasArg( 1426 OPT_time_trace, OPT_time_trace_granularity_eq, OPT_time_trace_file_eq); 1427 config->timeTraceGranularity = 1428 args::getInteger(args, OPT_time_trace_granularity_eq, 500); 1429 1430 // Initialize time trace profiler. 1431 if (config->timeTraceEnabled) 1432 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 1433 1434 { 1435 TimeTraceScope timeScope("ExecuteLinker"); 1436 1437 initLLVM(); // must be run before any call to addFile() 1438 createFiles(args); 1439 1440 config->isPic = config->outputType == MH_DYLIB || 1441 config->outputType == MH_BUNDLE || 1442 (config->outputType == MH_EXECUTE && 1443 args.hasFlag(OPT_pie, OPT_no_pie, true)); 1444 1445 // Now that all dylibs have been loaded, search for those that should be 1446 // re-exported. 1447 { 1448 auto reexportHandler = [](const Arg *arg, 1449 const std::vector<StringRef> &extensions) { 1450 config->hasReexports = true; 1451 StringRef searchName = arg->getValue(); 1452 if (!markReexport(searchName, extensions)) 1453 error(arg->getSpelling() + " " + searchName + 1454 " does not match a supplied dylib"); 1455 }; 1456 std::vector<StringRef> extensions = {".tbd"}; 1457 for (const Arg *arg : args.filtered(OPT_sub_umbrella)) 1458 reexportHandler(arg, extensions); 1459 1460 extensions.push_back(".dylib"); 1461 for (const Arg *arg : args.filtered(OPT_sub_library)) 1462 reexportHandler(arg, extensions); 1463 } 1464 1465 cl::ResetAllOptionOccurrences(); 1466 1467 // Parse LTO options. 1468 if (const Arg *arg = args.getLastArg(OPT_mcpu)) 1469 parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())), 1470 arg->getSpelling()); 1471 1472 for (const Arg *arg : args.filtered(OPT_mllvm)) 1473 parseClangOption(arg->getValue(), arg->getSpelling()); 1474 1475 compileBitcodeFiles(); 1476 replaceCommonSymbols(); 1477 1478 StringRef orderFile = args.getLastArgValue(OPT_order_file); 1479 if (!orderFile.empty()) 1480 priorityBuilder.parseOrderFile(orderFile); 1481 1482 referenceStubBinder(); 1483 1484 // FIXME: should terminate the link early based on errors encountered so 1485 // far? 1486 1487 createSyntheticSections(); 1488 createSyntheticSymbols(); 1489 1490 if (!config->exportedSymbols.empty()) { 1491 parallelForEach(symtab->getSymbols(), [](Symbol *sym) { 1492 if (auto *defined = dyn_cast<Defined>(sym)) { 1493 StringRef symbolName = defined->getName(); 1494 if (config->exportedSymbols.match(symbolName)) { 1495 if (defined->privateExtern) { 1496 if (defined->weakDefCanBeHidden) { 1497 // weak_def_can_be_hidden symbols behave similarly to 1498 // private_extern symbols in most cases, except for when 1499 // it is explicitly exported. 1500 // The former can be exported but the latter cannot. 1501 defined->privateExtern = false; 1502 } else { 1503 warn("cannot export hidden symbol " + symbolName + 1504 "\n>>> defined in " + toString(defined->getFile())); 1505 } 1506 } 1507 } else { 1508 defined->privateExtern = true; 1509 } 1510 } 1511 }); 1512 } else if (!config->unexportedSymbols.empty()) { 1513 parallelForEach(symtab->getSymbols(), [](Symbol *sym) { 1514 if (auto *defined = dyn_cast<Defined>(sym)) 1515 if (config->unexportedSymbols.match(defined->getName())) 1516 defined->privateExtern = true; 1517 }); 1518 } 1519 1520 for (const Arg *arg : args.filtered(OPT_sectcreate)) { 1521 StringRef segName = arg->getValue(0); 1522 StringRef sectName = arg->getValue(1); 1523 StringRef fileName = arg->getValue(2); 1524 Optional<MemoryBufferRef> buffer = readFile(fileName); 1525 if (buffer) 1526 inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName)); 1527 } 1528 1529 for (const Arg *arg : args.filtered(OPT_add_empty_section)) { 1530 StringRef segName = arg->getValue(0); 1531 StringRef sectName = arg->getValue(1); 1532 inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName)); 1533 } 1534 1535 gatherInputSections(); 1536 if (config->callGraphProfileSort) 1537 priorityBuilder.extractCallGraphProfile(); 1538 1539 if (config->deadStrip) 1540 markLive(); 1541 1542 // ICF assumes that all literals have been folded already, so we must run 1543 // foldIdenticalLiterals before foldIdenticalSections. 1544 foldIdenticalLiterals(); 1545 if (config->icfLevel != ICFLevel::none) { 1546 if (config->icfLevel == ICFLevel::safe) 1547 markAddrSigSymbols(); 1548 foldIdenticalSections(); 1549 } 1550 1551 // Write to an output file. 1552 if (target->wordSize == 8) 1553 writeResult<LP64>(); 1554 else 1555 writeResult<ILP32>(); 1556 1557 depTracker->write(getLLDVersion(), inputFiles, config->outputFile); 1558 } 1559 1560 if (config->timeTraceEnabled) { 1561 checkError(timeTraceProfilerWrite( 1562 args.getLastArgValue(OPT_time_trace_file_eq).str(), 1563 config->outputFile)); 1564 1565 timeTraceProfilerCleanup(); 1566 } 1567 return errorCount() == 0; 1568 } 1569