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