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