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