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