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