| 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 "COFFLinkerContext.h" |
| 11 | #include "Config.h" |
| 12 | #include "DebugTypes.h" |
| 13 | #include "ICF.h" |
| 14 | #include "InputFiles.h" |
| 15 | #include "MarkLive.h" |
| 16 | #include "MinGW.h" |
| 17 | #include "SymbolTable.h" |
| 18 | #include "Symbols.h" |
| 19 | #include "Writer.h" |
| 20 | #include "lld/Common/Args.h" |
| 21 | #include "lld/Common/CommonLinkerContext.h" |
| 22 | #include "lld/Common/Filesystem.h" |
| 23 | #include "lld/Common/Timer.h" |
| 24 | #include "lld/Common/Version.h" |
| 25 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
| 26 | #include "llvm/ADT/StringSwitch.h" |
| 27 | #include "llvm/BinaryFormat/Magic.h" |
| 28 | #include "llvm/Config/llvm-config.h" |
| 29 | #include "llvm/LTO/LTO.h" |
| 30 | #include "llvm/Object/COFFImportFile.h" |
| 31 | #include "llvm/Option/Arg.h" |
| 32 | #include "llvm/Option/ArgList.h" |
| 33 | #include "llvm/Option/Option.h" |
| 34 | #include "llvm/Support/BinaryStreamReader.h" |
| 35 | #include "llvm/Support/CommandLine.h" |
| 36 | #include "llvm/Support/Debug.h" |
| 37 | #include "llvm/Support/LEB128.h" |
| 38 | #include "llvm/Support/MathExtras.h" |
| 39 | #include "llvm/Support/Parallel.h" |
| 40 | #include "llvm/Support/Path.h" |
| 41 | #include "llvm/Support/Process.h" |
| 42 | #include "llvm/Support/TarWriter.h" |
| 43 | #include "llvm/Support/TargetSelect.h" |
| 44 | #include "llvm/Support/TimeProfiler.h" |
| 45 | #include "llvm/Support/VirtualFileSystem.h" |
| 46 | #include "llvm/Support/raw_ostream.h" |
| 47 | #include "llvm/TargetParser/Triple.h" |
| 48 | #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" |
| 49 | #include <algorithm> |
| 50 | #include <future> |
| 51 | #include <memory> |
| 52 | #include <optional> |
| 53 | #include <tuple> |
| 54 | |
| 55 | using namespace lld; |
| 56 | using namespace lld::coff; |
| 57 | using namespace llvm; |
| 58 | using namespace llvm::object; |
| 59 | using namespace llvm::COFF; |
| 60 | using namespace llvm::sys; |
| 61 | |
| 62 | COFFSyncStream::COFFSyncStream(COFFLinkerContext &ctx, DiagLevel level) |
| 63 | : SyncStream(ctx.e, level), ctx(ctx) {} |
| 64 | |
| 65 | COFFSyncStream coff::Log(COFFLinkerContext &ctx) { |
| 66 | return {ctx, DiagLevel::Log}; |
| 67 | } |
| 68 | COFFSyncStream coff::Msg(COFFLinkerContext &ctx) { |
| 69 | return {ctx, DiagLevel::Msg}; |
| 70 | } |
| 71 | COFFSyncStream coff::Warn(COFFLinkerContext &ctx) { |
| 72 | return {ctx, DiagLevel::Warn}; |
| 73 | } |
| 74 | COFFSyncStream coff::Err(COFFLinkerContext &ctx) { |
| 75 | return {ctx, DiagLevel::Err}; |
| 76 | } |
| 77 | COFFSyncStream coff::Fatal(COFFLinkerContext &ctx) { |
| 78 | return {ctx, DiagLevel::Fatal}; |
| 79 | } |
| 80 | uint64_t coff::errCount(COFFLinkerContext &ctx) { return ctx.e.errorCount; } |
| 81 | |
| 82 | namespace lld::coff { |
| 83 | |
| 84 | bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, |
| 85 | llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) { |
| 86 | // This driver-specific context will be freed later by unsafeLldMain(). |
| 87 | auto *ctx = new COFFLinkerContext; |
| 88 | |
| 89 | ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); |
| 90 | ctx->e.logName = args::getFilenameWithoutExe(path: args[0]); |
| 91 | ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now" |
| 92 | " (use /errorlimit:0 to see all errors)" ; |
| 93 | |
| 94 | ctx->driver.linkerMain(args); |
| 95 | |
| 96 | return errCount(ctx&: *ctx) == 0; |
| 97 | } |
| 98 | |
| 99 | // Parse options of the form "old;new". |
| 100 | static std::pair<StringRef, StringRef> |
| 101 | getOldNewOptions(COFFLinkerContext &ctx, opt::InputArgList &args, unsigned id) { |
| 102 | auto *arg = args.getLastArg(Ids: id); |
| 103 | if (!arg) |
| 104 | return {"" , "" }; |
| 105 | |
| 106 | StringRef s = arg->getValue(); |
| 107 | std::pair<StringRef, StringRef> ret = s.split(Separator: ';'); |
| 108 | if (ret.second.empty()) |
| 109 | Err(ctx) << arg->getSpelling() << " expects 'old;new' format, but got " |
| 110 | << s; |
| 111 | return ret; |
| 112 | } |
| 113 | |
| 114 | // Parse options of the form "old;new[;extra]". |
| 115 | static std::tuple<StringRef, StringRef, StringRef> |
| 116 | (COFFLinkerContext &ctx, opt::InputArgList &args, |
| 117 | unsigned id) { |
| 118 | auto [oldDir, second] = getOldNewOptions(ctx, args, id); |
| 119 | auto [newDir, extraDir] = second.split(Separator: ';'); |
| 120 | return {oldDir, newDir, extraDir}; |
| 121 | } |
| 122 | |
| 123 | // Drop directory components and replace extension with |
| 124 | // ".exe", ".dll" or ".sys". |
| 125 | static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) { |
| 126 | StringRef ext = ".exe" ; |
| 127 | if (isDll) |
| 128 | ext = ".dll" ; |
| 129 | else if (isDriver) |
| 130 | ext = ".sys" ; |
| 131 | |
| 132 | return (sys::path::stem(path) + ext).str(); |
| 133 | } |
| 134 | |
| 135 | // Returns true if S matches /crtend.?\.o$/. |
| 136 | static bool isCrtend(StringRef s) { |
| 137 | if (!s.consume_back(Suffix: ".o" )) |
| 138 | return false; |
| 139 | if (s.ends_with(Suffix: "crtend" )) |
| 140 | return true; |
| 141 | return !s.empty() && s.drop_back().ends_with(Suffix: "crtend" ); |
| 142 | } |
| 143 | |
| 144 | // ErrorOr is not default constructible, so it cannot be used as the type |
| 145 | // parameter of a future. |
| 146 | // FIXME: We could open the file in createFutureForFile and avoid needing to |
| 147 | // return an error here, but for the moment that would cost us a file descriptor |
| 148 | // (a limited resource on Windows) for the duration that the future is pending. |
| 149 | using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; |
| 150 | |
| 151 | // Create a std::future that opens and maps a file using the best strategy for |
| 152 | // the host platform. |
| 153 | static std::future<MBErrPair> createFutureForFile(std::string path) { |
| 154 | #if _WIN64 |
| 155 | // On Windows, file I/O is relatively slow so it is best to do this |
| 156 | // asynchronously. But 32-bit has issues with potentially launching tons |
| 157 | // of threads |
| 158 | auto strategy = std::launch::async; |
| 159 | #else |
| 160 | auto strategy = std::launch::deferred; |
| 161 | #endif |
| 162 | return std::async(policy: strategy, fn: [=]() { |
| 163 | auto mbOrErr = MemoryBuffer::getFile(Filename: path, /*IsText=*/false, |
| 164 | /*RequiresNullTerminator=*/false); |
| 165 | if (!mbOrErr) |
| 166 | return MBErrPair{nullptr, mbOrErr.getError()}; |
| 167 | return MBErrPair{std::move(*mbOrErr), std::error_code()}; |
| 168 | }); |
| 169 | } |
| 170 | |
| 171 | llvm::Triple::ArchType LinkerDriver::getArch() { |
| 172 | return getMachineArchType(machine: ctx.config.machine); |
| 173 | } |
| 174 | |
| 175 | std::vector<Chunk *> LinkerDriver::getChunks() const { |
| 176 | std::vector<Chunk *> res; |
| 177 | for (ObjFile *file : ctx.objFileInstances) { |
| 178 | ArrayRef<Chunk *> v = file->getChunks(); |
| 179 | res.insert(position: res.end(), first: v.begin(), last: v.end()); |
| 180 | } |
| 181 | return res; |
| 182 | } |
| 183 | |
| 184 | static bool compatibleMachineType(COFFLinkerContext &ctx, MachineTypes mt) { |
| 185 | if (mt == IMAGE_FILE_MACHINE_UNKNOWN) |
| 186 | return true; |
| 187 | switch (ctx.config.machine) { |
| 188 | case ARM64: |
| 189 | return mt == ARM64 || mt == ARM64X; |
| 190 | case ARM64EC: |
| 191 | case ARM64X: |
| 192 | return isAnyArm64(Machine: mt) || mt == AMD64; |
| 193 | case IMAGE_FILE_MACHINE_UNKNOWN: |
| 194 | return true; |
| 195 | default: |
| 196 | return ctx.config.machine == mt; |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | void LinkerDriver::addFile(InputFile *file) { |
| 201 | Log(ctx) << "Reading " << toString(file); |
| 202 | if (file->lazy) { |
| 203 | if (auto *f = dyn_cast<BitcodeFile>(Val: file)) |
| 204 | f->parseLazy(); |
| 205 | else |
| 206 | cast<ObjFile>(Val: file)->parseLazy(); |
| 207 | } else { |
| 208 | file->parse(); |
| 209 | if (auto *f = dyn_cast<ObjFile>(Val: file)) { |
| 210 | ctx.objFileInstances.push_back(x: f); |
| 211 | } else if (auto *f = dyn_cast<BitcodeFile>(Val: file)) { |
| 212 | if (ltoCompilationDone) { |
| 213 | Err(ctx) << "LTO object file " << toString(file) |
| 214 | << " linked in after " |
| 215 | "doing LTO compilation." ; |
| 216 | } |
| 217 | f->symtab.bitcodeFileInstances.push_back(x: f); |
| 218 | } else if (auto *f = dyn_cast<ImportFile>(Val: file)) { |
| 219 | ctx.importFileInstances.push_back(x: f); |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | MachineTypes mt = file->getMachineType(); |
| 224 | // The ARM64EC target must be explicitly specified and cannot be inferred. |
| 225 | if (mt == ARM64EC && |
| 226 | (ctx.config.machine == IMAGE_FILE_MACHINE_UNKNOWN || |
| 227 | (ctx.config.machineInferred && |
| 228 | (ctx.config.machine == ARM64 || ctx.config.machine == AMD64)))) { |
| 229 | Err(ctx) << toString(file) |
| 230 | << ": machine type arm64ec is ambiguous and cannot be " |
| 231 | "inferred, use /machine:arm64ec or /machine:arm64x" ; |
| 232 | return; |
| 233 | } |
| 234 | if (!compatibleMachineType(ctx, mt)) { |
| 235 | Err(ctx) << toString(file) << ": machine type " << machineToStr(MT: mt) |
| 236 | << " conflicts with " << machineToStr(MT: ctx.config.machine); |
| 237 | return; |
| 238 | } |
| 239 | if (ctx.config.machine == IMAGE_FILE_MACHINE_UNKNOWN && |
| 240 | mt != IMAGE_FILE_MACHINE_UNKNOWN) { |
| 241 | ctx.config.machineInferred = true; |
| 242 | setMachine(mt); |
| 243 | } |
| 244 | |
| 245 | parseDirectives(file); |
| 246 | } |
| 247 | |
| 248 | MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) { |
| 249 | MemoryBufferRef mbref = *mb; |
| 250 | make<std::unique_ptr<MemoryBuffer>>(args: std::move(mb)); // take ownership |
| 251 | |
| 252 | if (ctx.driver.tar) |
| 253 | ctx.driver.tar->append(Path: relativeToRoot(path: mbref.getBufferIdentifier()), |
| 254 | Data: mbref.getBuffer()); |
| 255 | return mbref; |
| 256 | } |
| 257 | |
| 258 | void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb, |
| 259 | bool wholeArchive, bool lazy) { |
| 260 | StringRef filename = mb->getBufferIdentifier(); |
| 261 | |
| 262 | MemoryBufferRef mbref = takeBuffer(mb: std::move(mb)); |
| 263 | |
| 264 | // File type is detected by contents, not by file extension. |
| 265 | switch (identify_magic(magic: mbref.getBuffer())) { |
| 266 | case file_magic::windows_resource: |
| 267 | resources.push_back(x: mbref); |
| 268 | break; |
| 269 | case file_magic::archive: |
| 270 | if (wholeArchive) { |
| 271 | std::unique_ptr<Archive> file = |
| 272 | CHECK(Archive::create(mbref), filename + ": failed to parse archive" ); |
| 273 | Archive *archive = file.get(); |
| 274 | make<std::unique_ptr<Archive>>(args: std::move(file)); // take ownership |
| 275 | |
| 276 | int memberIndex = 0; |
| 277 | for (MemoryBufferRef m : getArchiveMembers(ctx, file: archive)) |
| 278 | addArchiveBuffer(mbref: m, symName: "<whole-archive>" , parentName: filename, offsetInArchive: memberIndex++); |
| 279 | return; |
| 280 | } |
| 281 | addFile(file: make<ArchiveFile>(args&: ctx, args&: mbref)); |
| 282 | break; |
| 283 | case file_magic::bitcode: |
| 284 | addFile(file: BitcodeFile::create(ctx, mb: mbref, archiveName: "" , offsetInArchive: 0, lazy)); |
| 285 | break; |
| 286 | case file_magic::coff_object: |
| 287 | case file_magic::coff_import_library: |
| 288 | addFile(file: ObjFile::create(ctx, mb: mbref, lazy)); |
| 289 | break; |
| 290 | case file_magic::pdb: |
| 291 | addFile(file: make<PDBInputFile>(args&: ctx, args&: mbref)); |
| 292 | break; |
| 293 | case file_magic::coff_cl_gl_object: |
| 294 | Err(ctx) << filename |
| 295 | << ": is not a native COFF file. Recompile without /GL" ; |
| 296 | break; |
| 297 | case file_magic::pecoff_executable: |
| 298 | if (ctx.config.mingw) { |
| 299 | addFile(file: make<DLLFile>(args&: ctx.symtab, args&: mbref)); |
| 300 | break; |
| 301 | } |
| 302 | if (filename.ends_with_insensitive(Suffix: ".dll" )) { |
| 303 | Err(ctx) << filename |
| 304 | << ": bad file type. Did you specify a DLL instead of an " |
| 305 | "import library?" ; |
| 306 | break; |
| 307 | } |
| 308 | [[fallthrough]]; |
| 309 | default: |
| 310 | Err(ctx) << mbref.getBufferIdentifier() << ": unknown file type" ; |
| 311 | break; |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { |
| 316 | auto future = std::make_shared<std::future<MBErrPair>>( |
| 317 | args: createFutureForFile(path: std::string(path))); |
| 318 | std::string pathStr = std::string(path); |
| 319 | enqueueTask(task: [=]() { |
| 320 | llvm::TimeTraceScope timeScope("File: " , path); |
| 321 | auto [mb, ec] = future->get(); |
| 322 | if (ec) { |
| 323 | // Retry reading the file (synchronously) now that we may have added |
| 324 | // winsysroot search paths from SymbolTable::addFile(). |
| 325 | // Retrying synchronously is important for keeping the order of inputs |
| 326 | // consistent. |
| 327 | // This makes it so that if the user passes something in the winsysroot |
| 328 | // before something we can find with an architecture, we won't find the |
| 329 | // winsysroot file. |
| 330 | if (std::optional<StringRef> retryPath = findFileIfNew(filename: pathStr)) { |
| 331 | auto retryMb = MemoryBuffer::getFile(Filename: *retryPath, /*IsText=*/false, |
| 332 | /*RequiresNullTerminator=*/false); |
| 333 | ec = retryMb.getError(); |
| 334 | if (!ec) |
| 335 | mb = std::move(*retryMb); |
| 336 | } else { |
| 337 | // We've already handled this file. |
| 338 | return; |
| 339 | } |
| 340 | } |
| 341 | if (ec) { |
| 342 | std::string msg = "could not open '" + pathStr + "': " + ec.message(); |
| 343 | // Check if the filename is a typo for an option flag. OptTable thinks |
| 344 | // that all args that are not known options and that start with / are |
| 345 | // filenames, but e.g. `/nodefaultlibs` is more likely a typo for |
| 346 | // the option `/nodefaultlib` than a reference to a file in the root |
| 347 | // directory. |
| 348 | std::string nearest; |
| 349 | if (ctx.optTable.findNearest(Option: pathStr, NearestString&: nearest) > 1) |
| 350 | Err(ctx) << msg; |
| 351 | else |
| 352 | Err(ctx) << msg << "; did you mean '" << nearest << "'" ; |
| 353 | } else |
| 354 | ctx.driver.addBuffer(mb: std::move(mb), wholeArchive, lazy); |
| 355 | }); |
| 356 | } |
| 357 | |
| 358 | void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, |
| 359 | StringRef parentName, |
| 360 | uint64_t offsetInArchive) { |
| 361 | file_magic magic = identify_magic(magic: mb.getBuffer()); |
| 362 | if (magic == file_magic::coff_import_library) { |
| 363 | InputFile *imp = make<ImportFile>(args&: ctx, args&: mb); |
| 364 | imp->parentName = parentName; |
| 365 | addFile(file: imp); |
| 366 | return; |
| 367 | } |
| 368 | |
| 369 | InputFile *obj; |
| 370 | if (magic == file_magic::coff_object) { |
| 371 | obj = ObjFile::create(ctx, mb); |
| 372 | } else if (magic == file_magic::bitcode) { |
| 373 | obj = BitcodeFile::create(ctx, mb, archiveName: parentName, offsetInArchive, |
| 374 | /*lazy=*/false); |
| 375 | } else if (magic == file_magic::coff_cl_gl_object) { |
| 376 | Err(ctx) << mb.getBufferIdentifier() |
| 377 | << ": is not a native COFF file. Recompile without /GL?" ; |
| 378 | return; |
| 379 | } else { |
| 380 | Err(ctx) << "unknown file type: " << mb.getBufferIdentifier(); |
| 381 | return; |
| 382 | } |
| 383 | |
| 384 | obj->parentName = parentName; |
| 385 | addFile(file: obj); |
| 386 | Log(ctx) << "Loaded " << obj << " for " << symName; |
| 387 | } |
| 388 | |
| 389 | void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, |
| 390 | const Archive::Symbol &sym, |
| 391 | StringRef parentName) { |
| 392 | |
| 393 | auto reportBufferError = [=](Error &&e, StringRef childName) { |
| 394 | Fatal(ctx) << "could not get the buffer for the member defining symbol " |
| 395 | << &sym << ": " << parentName << "(" << childName |
| 396 | << "): " << std::move(e); |
| 397 | }; |
| 398 | |
| 399 | if (!c.getParent()->isThin()) { |
| 400 | uint64_t offsetInArchive = c.getChildOffset(); |
| 401 | Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); |
| 402 | if (!mbOrErr) |
| 403 | reportBufferError(mbOrErr.takeError(), check(e: c.getFullName())); |
| 404 | MemoryBufferRef mb = mbOrErr.get(); |
| 405 | enqueueTask(task: [=]() { |
| 406 | llvm::TimeTraceScope timeScope("Archive: " , mb.getBufferIdentifier()); |
| 407 | ctx.driver.addArchiveBuffer(mb, symName: toCOFFString(ctx, b: sym), parentName, |
| 408 | offsetInArchive); |
| 409 | }); |
| 410 | return; |
| 411 | } |
| 412 | |
| 413 | std::string childName = |
| 414 | CHECK(c.getFullName(), |
| 415 | "could not get the filename for the member defining symbol " + |
| 416 | toCOFFString(ctx, sym)); |
| 417 | auto future = |
| 418 | std::make_shared<std::future<MBErrPair>>(args: createFutureForFile(path: childName)); |
| 419 | enqueueTask(task: [=]() { |
| 420 | auto mbOrErr = future->get(); |
| 421 | if (mbOrErr.second) |
| 422 | reportBufferError(errorCodeToError(EC: mbOrErr.second), childName); |
| 423 | llvm::TimeTraceScope timeScope("Archive: " , |
| 424 | mbOrErr.first->getBufferIdentifier()); |
| 425 | // Pass empty string as archive name so that the original filename is |
| 426 | // used as the buffer identifier. |
| 427 | ctx.driver.addArchiveBuffer(mb: takeBuffer(mb: std::move(mbOrErr.first)), |
| 428 | symName: toCOFFString(ctx, b: sym), parentName: "" , |
| 429 | /*OffsetInArchive=*/offsetInArchive: 0); |
| 430 | }); |
| 431 | } |
| 432 | |
| 433 | bool LinkerDriver::isDecorated(StringRef sym) { |
| 434 | return sym.starts_with(Prefix: "@" ) || sym.contains(Other: "@@" ) || sym.starts_with(Prefix: "?" ) || |
| 435 | (!ctx.config.mingw && sym.contains(C: '@')); |
| 436 | } |
| 437 | |
| 438 | // Parses .drectve section contents and returns a list of files |
| 439 | // specified by /defaultlib. |
| 440 | void LinkerDriver::parseDirectives(InputFile *file) { |
| 441 | StringRef s = file->getDirectives(); |
| 442 | if (s.empty()) |
| 443 | return; |
| 444 | |
| 445 | Log(ctx) << "Directives: " << file << ": " << s; |
| 446 | |
| 447 | ArgParser parser(ctx); |
| 448 | // .drectve is always tokenized using Windows shell rules. |
| 449 | // /EXPORT: option can appear too many times, processing in fastpath. |
| 450 | ParsedDirectives directives = parser.parseDirectives(s); |
| 451 | |
| 452 | for (StringRef e : directives.exports) { |
| 453 | // If a common header file contains dllexported function |
| 454 | // declarations, many object files may end up with having the |
| 455 | // same /EXPORT options. In order to save cost of parsing them, |
| 456 | // we dedup them first. |
| 457 | if (!file->symtab.directivesExports.insert(V: e).second) |
| 458 | continue; |
| 459 | |
| 460 | Export exp = parseExport(arg: e); |
| 461 | if (ctx.config.machine == I386 && ctx.config.mingw) { |
| 462 | if (!isDecorated(sym: exp.name)) |
| 463 | exp.name = saver().save(S: "_" + exp.name); |
| 464 | if (!exp.extName.empty() && !isDecorated(sym: exp.extName)) |
| 465 | exp.extName = saver().save(S: "_" + exp.extName); |
| 466 | } |
| 467 | exp.source = ExportSource::Directives; |
| 468 | file->symtab.exports.push_back(x: exp); |
| 469 | } |
| 470 | |
| 471 | // Handle /include: in bulk. |
| 472 | for (StringRef inc : directives.includes) |
| 473 | file->symtab.addGCRoot(sym: inc); |
| 474 | |
| 475 | // Handle /exclude-symbols: in bulk. |
| 476 | for (StringRef e : directives.excludes) { |
| 477 | SmallVector<StringRef, 2> vec; |
| 478 | e.split(A&: vec, Separator: ','); |
| 479 | for (StringRef sym : vec) |
| 480 | excludedSymbols.insert(V: file->symtab.mangle(sym)); |
| 481 | } |
| 482 | |
| 483 | // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160 |
| 484 | for (auto *arg : directives.args) { |
| 485 | switch (arg->getOption().getID()) { |
| 486 | case OPT_aligncomm: |
| 487 | file->symtab.parseAligncomm(arg->getValue()); |
| 488 | break; |
| 489 | case OPT_alternatename: |
| 490 | file->symtab.parseAlternateName(arg->getValue()); |
| 491 | break; |
| 492 | case OPT_arm64xsameaddress: |
| 493 | if (!file->symtab.isEC()) |
| 494 | Warn(ctx) << arg->getSpelling() |
| 495 | << " is not allowed in non-ARM64EC files (" << toString(file) |
| 496 | << ")" ; |
| 497 | break; |
| 498 | case OPT_defaultlib: |
| 499 | if (std::optional<StringRef> path = findLibIfNew(filename: arg->getValue())) |
| 500 | enqueuePath(path: *path, wholeArchive: false, lazy: false); |
| 501 | break; |
| 502 | case OPT_entry: |
| 503 | if (!arg->getValue()[0]) |
| 504 | Fatal(ctx) << "missing entry point symbol name" ; |
| 505 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
| 506 | symtab.entry = symtab.addGCRoot(sym: symtab.mangle(sym: arg->getValue()), aliasEC: true); |
| 507 | }); |
| 508 | break; |
| 509 | case OPT_failifmismatch: |
| 510 | checkFailIfMismatch(arg: arg->getValue(), source: file); |
| 511 | break; |
| 512 | case OPT_incl: |
| 513 | file->symtab.addGCRoot(sym: arg->getValue()); |
| 514 | break; |
| 515 | case OPT_manifestdependency: |
| 516 | ctx.config.manifestDependencies.insert(X: arg->getValue()); |
| 517 | break; |
| 518 | case OPT_merge: |
| 519 | parseMerge(arg->getValue()); |
| 520 | break; |
| 521 | case OPT_nodefaultlib: |
| 522 | ctx.config.noDefaultLibs.insert(x: findLib(filename: arg->getValue()).lower()); |
| 523 | break; |
| 524 | case OPT_release: |
| 525 | ctx.config.writeCheckSum = true; |
| 526 | break; |
| 527 | case OPT_section: |
| 528 | parseSection(arg->getValue()); |
| 529 | break; |
| 530 | case OPT_stack: |
| 531 | parseNumbers(arg: arg->getValue(), addr: &ctx.config.stackReserve, |
| 532 | size: &ctx.config.stackCommit); |
| 533 | break; |
| 534 | case OPT_subsystem: { |
| 535 | bool gotVersion = false; |
| 536 | parseSubsystem(arg: arg->getValue(), sys: &ctx.config.subsystem, |
| 537 | major: &ctx.config.majorSubsystemVersion, |
| 538 | minor: &ctx.config.minorSubsystemVersion, gotVersion: &gotVersion); |
| 539 | if (gotVersion) { |
| 540 | ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion; |
| 541 | ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion; |
| 542 | } |
| 543 | break; |
| 544 | } |
| 545 | // Only add flags here that link.exe accepts in |
| 546 | // `#pragma comment(linker, "/flag")`-generated sections. |
| 547 | case OPT_editandcontinue: |
| 548 | case OPT_guardsym: |
| 549 | case OPT_throwingnew: |
| 550 | case OPT_inferasanlibs: |
| 551 | case OPT_inferasanlibs_no: |
| 552 | break; |
| 553 | default: |
| 554 | Err(ctx) << arg->getSpelling() << " is not allowed in .drectve (" |
| 555 | << toString(file) << ")" ; |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | // Find file from search paths. You can omit ".obj", this function takes |
| 561 | // care of that. Note that the returned path is not guaranteed to exist. |
| 562 | StringRef LinkerDriver::findFile(StringRef filename) { |
| 563 | auto getFilename = [this](StringRef filename) -> StringRef { |
| 564 | if (ctx.config.vfs) |
| 565 | if (auto statOrErr = ctx.config.vfs->status(Path: filename)) |
| 566 | return saver().save(S: statOrErr->getName()); |
| 567 | return filename; |
| 568 | }; |
| 569 | |
| 570 | if (sys::path::is_absolute(path: filename)) |
| 571 | return getFilename(filename); |
| 572 | bool hasExt = filename.contains(C: '.'); |
| 573 | for (StringRef dir : searchPaths) { |
| 574 | SmallString<128> path = dir; |
| 575 | sys::path::append(path, a: filename); |
| 576 | path = SmallString<128>{getFilename(path.str())}; |
| 577 | if (sys::fs::exists(Path: path.str())) |
| 578 | return saver().save(S: path.str()); |
| 579 | if (!hasExt) { |
| 580 | path.append(RHS: ".obj" ); |
| 581 | path = SmallString<128>{getFilename(path.str())}; |
| 582 | if (sys::fs::exists(Path: path.str())) |
| 583 | return saver().save(S: path.str()); |
| 584 | } |
| 585 | } |
| 586 | return filename; |
| 587 | } |
| 588 | |
| 589 | static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) { |
| 590 | sys::fs::UniqueID ret; |
| 591 | if (sys::fs::getUniqueID(Path: path, Result&: ret)) |
| 592 | return std::nullopt; |
| 593 | return ret; |
| 594 | } |
| 595 | |
| 596 | // Resolves a file path. This never returns the same path |
| 597 | // (in that case, it returns std::nullopt). |
| 598 | std::optional<StringRef> LinkerDriver::findFileIfNew(StringRef filename) { |
| 599 | StringRef path = findFile(filename); |
| 600 | |
| 601 | if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) { |
| 602 | bool seen = !visitedFiles.insert(x: *id).second; |
| 603 | if (seen) |
| 604 | return std::nullopt; |
| 605 | } |
| 606 | |
| 607 | if (path.ends_with_insensitive(Suffix: ".lib" )) |
| 608 | visitedLibs.insert(x: std::string(sys::path::filename(path).lower())); |
| 609 | return path; |
| 610 | } |
| 611 | |
| 612 | // MinGW specific. If an embedded directive specified to link to |
| 613 | // foo.lib, but it isn't found, try libfoo.a instead. |
| 614 | StringRef LinkerDriver::findLibMinGW(StringRef filename) { |
| 615 | if (filename.contains(C: '/') || filename.contains(C: '\\')) |
| 616 | return filename; |
| 617 | |
| 618 | SmallString<128> s = filename; |
| 619 | sys::path::replace_extension(path&: s, extension: ".a" ); |
| 620 | StringRef libName = saver().save(S: "lib" + s.str()); |
| 621 | return findFile(filename: libName); |
| 622 | } |
| 623 | |
| 624 | // Find library file from search path. |
| 625 | StringRef LinkerDriver::findLib(StringRef filename) { |
| 626 | // Add ".lib" to Filename if that has no file extension. |
| 627 | bool hasExt = filename.contains(C: '.'); |
| 628 | if (!hasExt) |
| 629 | filename = saver().save(S: filename + ".lib" ); |
| 630 | StringRef ret = findFile(filename); |
| 631 | // For MinGW, if the find above didn't turn up anything, try |
| 632 | // looking for a MinGW formatted library name. |
| 633 | if (ctx.config.mingw && ret == filename) |
| 634 | return findLibMinGW(filename); |
| 635 | return ret; |
| 636 | } |
| 637 | |
| 638 | // Resolves a library path. /nodefaultlib options are taken into |
| 639 | // consideration. This never returns the same path (in that case, |
| 640 | // it returns std::nullopt). |
| 641 | std::optional<StringRef> LinkerDriver::findLibIfNew(StringRef filename) { |
| 642 | if (ctx.config.noDefaultLibAll) |
| 643 | return std::nullopt; |
| 644 | if (!visitedLibs.insert(x: filename.lower()).second) |
| 645 | return std::nullopt; |
| 646 | |
| 647 | StringRef path = findLib(filename); |
| 648 | if (ctx.config.noDefaultLibs.count(x: path.lower())) |
| 649 | return std::nullopt; |
| 650 | |
| 651 | if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) |
| 652 | if (!visitedFiles.insert(x: *id).second) |
| 653 | return std::nullopt; |
| 654 | return path; |
| 655 | } |
| 656 | |
| 657 | void LinkerDriver::setMachine(MachineTypes machine) { |
| 658 | assert(ctx.config.machine == IMAGE_FILE_MACHINE_UNKNOWN); |
| 659 | assert(machine != IMAGE_FILE_MACHINE_UNKNOWN); |
| 660 | |
| 661 | ctx.config.machine = machine; |
| 662 | |
| 663 | if (!isArm64EC(Machine: machine)) { |
| 664 | ctx.symtab.machine = machine; |
| 665 | } else { |
| 666 | // Set up a hybrid symbol table on ARM64EC/ARM64X. This is primarily useful |
| 667 | // on ARM64X, where both the native and EC symbol tables are meaningful. |
| 668 | // However, since ARM64EC can include native object files, we also need to |
| 669 | // support a hybrid symbol table there. |
| 670 | ctx.symtab.machine = ARM64EC; |
| 671 | ctx.hybridSymtab.emplace(args&: ctx, args: ARM64); |
| 672 | } |
| 673 | |
| 674 | addWinSysRootLibSearchPaths(); |
| 675 | } |
| 676 | |
| 677 | void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) { |
| 678 | IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem(); |
| 679 | |
| 680 | // Check the command line first, that's the user explicitly telling us what to |
| 681 | // use. Check the environment next, in case we're being invoked from a VS |
| 682 | // command prompt. Failing that, just try to find the newest Visual Studio |
| 683 | // version we can and use its default VC toolchain. |
| 684 | std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot; |
| 685 | if (auto *A = Args.getLastArg(Ids: OPT_vctoolsdir)) |
| 686 | VCToolsDir = A->getValue(); |
| 687 | if (auto *A = Args.getLastArg(Ids: OPT_vctoolsversion)) |
| 688 | VCToolsVersion = A->getValue(); |
| 689 | if (auto *A = Args.getLastArg(Ids: OPT_winsysroot)) |
| 690 | WinSysRoot = A->getValue(); |
| 691 | if (!findVCToolChainViaCommandLine(VFS&: *VFS, VCToolsDir, VCToolsVersion, |
| 692 | WinSysRoot, Path&: vcToolChainPath, VSLayout&: vsLayout) && |
| 693 | (Args.hasArg(Ids: OPT_lldignoreenv) || |
| 694 | !findVCToolChainViaEnvironment(VFS&: *VFS, Path&: vcToolChainPath, VSLayout&: vsLayout)) && |
| 695 | !findVCToolChainViaSetupConfig(VFS&: *VFS, VCToolsVersion: {}, Path&: vcToolChainPath, VSLayout&: vsLayout) && |
| 696 | !findVCToolChainViaRegistry(Path&: vcToolChainPath, VSLayout&: vsLayout)) |
| 697 | return; |
| 698 | |
| 699 | // If the VC environment hasn't been configured (perhaps because the user did |
| 700 | // not run vcvarsall), try to build a consistent link environment. If the |
| 701 | // environment variable is set however, assume the user knows what they're |
| 702 | // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env |
| 703 | // vars. |
| 704 | if (const auto *A = Args.getLastArg(Ids: OPT_diasdkdir, Ids: OPT_winsysroot)) { |
| 705 | diaPath = A->getValue(); |
| 706 | if (A->getOption().getID() == OPT_winsysroot) |
| 707 | path::append(path&: diaPath, a: "DIA SDK" ); |
| 708 | } |
| 709 | useWinSysRootLibPath = !Process::GetEnv(name: "LIB" ) || |
| 710 | Args.hasArg(Ids: OPT_lldignoreenv, Ids: OPT_vctoolsdir, |
| 711 | Ids: OPT_vctoolsversion, Ids: OPT_winsysroot); |
| 712 | if (!Process::GetEnv(name: "LIB" ) || |
| 713 | Args.hasArg(Ids: OPT_lldignoreenv, Ids: OPT_winsdkdir, Ids: OPT_winsdkversion, |
| 714 | Ids: OPT_winsysroot)) { |
| 715 | std::optional<StringRef> WinSdkDir, WinSdkVersion; |
| 716 | if (auto *A = Args.getLastArg(Ids: OPT_winsdkdir)) |
| 717 | WinSdkDir = A->getValue(); |
| 718 | if (auto *A = Args.getLastArg(Ids: OPT_winsdkversion)) |
| 719 | WinSdkVersion = A->getValue(); |
| 720 | |
| 721 | if (useUniversalCRT(VSLayout: vsLayout, VCToolChainPath: vcToolChainPath, TargetArch: getArch(), VFS&: *VFS)) { |
| 722 | std::string UniversalCRTSdkPath; |
| 723 | std::string UCRTVersion; |
| 724 | if (getUniversalCRTSdkDir(VFS&: *VFS, WinSdkDir, WinSdkVersion, WinSysRoot, |
| 725 | Path&: UniversalCRTSdkPath, UCRTVersion)) { |
| 726 | universalCRTLibPath = UniversalCRTSdkPath; |
| 727 | path::append(path&: universalCRTLibPath, a: "Lib" , b: UCRTVersion, c: "ucrt" ); |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | std::string sdkPath; |
| 732 | std::string windowsSDKIncludeVersion; |
| 733 | std::string windowsSDKLibVersion; |
| 734 | if (getWindowsSDKDir(VFS&: *VFS, WinSdkDir, WinSdkVersion, WinSysRoot, Path&: sdkPath, |
| 735 | Major&: sdkMajor, WindowsSDKIncludeVersion&: windowsSDKIncludeVersion, |
| 736 | WindowsSDKLibVersion&: windowsSDKLibVersion)) { |
| 737 | windowsSdkLibPath = sdkPath; |
| 738 | path::append(path&: windowsSdkLibPath, a: "Lib" ); |
| 739 | if (sdkMajor >= 8) |
| 740 | path::append(path&: windowsSdkLibPath, a: windowsSDKLibVersion, b: "um" ); |
| 741 | } |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) { |
| 746 | std::string lldBinary = sys::fs::getMainExecutable(argv0: argv0.c_str(), MainExecAddr: nullptr); |
| 747 | SmallString<128> binDir(lldBinary); |
| 748 | sys::path::remove_filename(path&: binDir); // remove lld-link.exe |
| 749 | StringRef rootDir = sys::path::parent_path(path: binDir); // remove 'bin' |
| 750 | |
| 751 | SmallString<128> libDir(rootDir); |
| 752 | sys::path::append(path&: libDir, a: "lib" ); |
| 753 | |
| 754 | // Add the resource dir library path |
| 755 | SmallString<128> runtimeLibDir(rootDir); |
| 756 | sys::path::append(path&: runtimeLibDir, a: "lib" , b: "clang" , |
| 757 | c: std::to_string(LLVM_VERSION_MAJOR), d: "lib" ); |
| 758 | // Resource dir + osname, which is hardcoded to windows since we are in the |
| 759 | // COFF driver. |
| 760 | SmallString<128> runtimeLibDirWithOS(runtimeLibDir); |
| 761 | sys::path::append(path&: runtimeLibDirWithOS, a: "windows" ); |
| 762 | |
| 763 | searchPaths.push_back(x: saver().save(S: runtimeLibDirWithOS.str())); |
| 764 | searchPaths.push_back(x: saver().save(S: runtimeLibDir.str())); |
| 765 | searchPaths.push_back(x: saver().save(S: libDir.str())); |
| 766 | } |
| 767 | |
| 768 | void LinkerDriver::addWinSysRootLibSearchPaths() { |
| 769 | if (!diaPath.empty()) { |
| 770 | // The DIA SDK always uses the legacy vc arch, even in new MSVC versions. |
| 771 | path::append(path&: diaPath, a: "lib" , b: archToLegacyVCArch(Arch: getArch())); |
| 772 | searchPaths.push_back(x: saver().save(S: diaPath.str())); |
| 773 | } |
| 774 | if (useWinSysRootLibPath) { |
| 775 | searchPaths.push_back(x: saver().save(S: getSubDirectoryPath( |
| 776 | Type: SubDirectoryType::Lib, VSLayout: vsLayout, VCToolChainPath: vcToolChainPath, TargetArch: getArch()))); |
| 777 | searchPaths.push_back(x: saver().save( |
| 778 | S: getSubDirectoryPath(Type: SubDirectoryType::Lib, VSLayout: vsLayout, VCToolChainPath: vcToolChainPath, |
| 779 | TargetArch: getArch(), SubdirParent: "atlmfc" ))); |
| 780 | } |
| 781 | if (!universalCRTLibPath.empty()) { |
| 782 | StringRef ArchName = archToWindowsSDKArch(Arch: getArch()); |
| 783 | if (!ArchName.empty()) { |
| 784 | path::append(path&: universalCRTLibPath, a: ArchName); |
| 785 | searchPaths.push_back(x: saver().save(S: universalCRTLibPath.str())); |
| 786 | } |
| 787 | } |
| 788 | if (!windowsSdkLibPath.empty()) { |
| 789 | std::string path; |
| 790 | if (appendArchToWindowsSDKLibPath(SDKMajor: sdkMajor, LibPath: windowsSdkLibPath, Arch: getArch(), |
| 791 | path)) |
| 792 | searchPaths.push_back(x: saver().save(S: path)); |
| 793 | } |
| 794 | |
| 795 | // Libraries specified by `/nodefaultlib:` may not be found in incomplete |
| 796 | // search paths before lld infers a machine type from input files. |
| 797 | std::set<std::string> noDefaultLibs; |
| 798 | for (const std::string &path : ctx.config.noDefaultLibs) |
| 799 | noDefaultLibs.insert(x: findLib(filename: path).lower()); |
| 800 | ctx.config.noDefaultLibs = noDefaultLibs; |
| 801 | } |
| 802 | |
| 803 | // Parses LIB environment which contains a list of search paths. |
| 804 | void LinkerDriver::addLibSearchPaths() { |
| 805 | std::optional<std::string> envOpt = Process::GetEnv(name: "LIB" ); |
| 806 | if (!envOpt) |
| 807 | return; |
| 808 | StringRef env = saver().save(S: *envOpt); |
| 809 | while (!env.empty()) { |
| 810 | StringRef path; |
| 811 | std::tie(args&: path, args&: env) = env.split(Separator: ';'); |
| 812 | searchPaths.push_back(x: path); |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | uint64_t LinkerDriver::getDefaultImageBase() { |
| 817 | if (ctx.config.is64()) |
| 818 | return ctx.config.dll ? 0x180000000 : 0x140000000; |
| 819 | return ctx.config.dll ? 0x10000000 : 0x400000; |
| 820 | } |
| 821 | |
| 822 | static std::string rewritePath(StringRef s) { |
| 823 | if (fs::exists(Path: s)) |
| 824 | return relativeToRoot(path: s); |
| 825 | return std::string(s); |
| 826 | } |
| 827 | |
| 828 | // Reconstructs command line arguments so that so that you can re-run |
| 829 | // the same command with the same inputs. This is for --reproduce. |
| 830 | static std::string createResponseFile(const opt::InputArgList &args, |
| 831 | ArrayRef<StringRef> searchPaths) { |
| 832 | SmallString<0> data; |
| 833 | raw_svector_ostream os(data); |
| 834 | |
| 835 | for (auto *arg : args) { |
| 836 | switch (arg->getOption().getID()) { |
| 837 | case OPT_linkrepro: |
| 838 | case OPT_reproduce: |
| 839 | case OPT_libpath: |
| 840 | case OPT_winsysroot: |
| 841 | break; |
| 842 | case OPT_INPUT: |
| 843 | os << quote(s: rewritePath(s: arg->getValue())) << "\n" ; |
| 844 | break; |
| 845 | case OPT_wholearchive_file: |
| 846 | os << arg->getSpelling() << quote(s: rewritePath(s: arg->getValue())) << "\n" ; |
| 847 | break; |
| 848 | case OPT_call_graph_ordering_file: |
| 849 | case OPT_deffile: |
| 850 | case OPT_manifestinput: |
| 851 | case OPT_natvis: |
| 852 | os << arg->getSpelling() << quote(s: rewritePath(s: arg->getValue())) << '\n'; |
| 853 | break; |
| 854 | case OPT_order: { |
| 855 | StringRef orderFile = arg->getValue(); |
| 856 | orderFile.consume_front(Prefix: "@" ); |
| 857 | os << arg->getSpelling() << '@' << quote(s: rewritePath(s: orderFile)) << '\n'; |
| 858 | break; |
| 859 | } |
| 860 | case OPT_pdbstream: { |
| 861 | const std::pair<StringRef, StringRef> nameFile = |
| 862 | StringRef(arg->getValue()).split(Separator: "=" ); |
| 863 | os << arg->getSpelling() << nameFile.first << '=' |
| 864 | << quote(s: rewritePath(s: nameFile.second)) << '\n'; |
| 865 | break; |
| 866 | } |
| 867 | case OPT_implib: |
| 868 | case OPT_manifestfile: |
| 869 | case OPT_pdb: |
| 870 | case OPT_pdbstripped: |
| 871 | case OPT_out: |
| 872 | os << arg->getSpelling() << sys::path::filename(path: arg->getValue()) << "\n" ; |
| 873 | break; |
| 874 | default: |
| 875 | os << toString(arg: *arg) << "\n" ; |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | for (StringRef path : searchPaths) { |
| 880 | std::string relPath = relativeToRoot(path); |
| 881 | os << "/libpath:" << quote(s: relPath) << "\n" ; |
| 882 | } |
| 883 | |
| 884 | return std::string(data); |
| 885 | } |
| 886 | |
| 887 | static unsigned parseDebugTypes(COFFLinkerContext &ctx, |
| 888 | const opt::InputArgList &args) { |
| 889 | unsigned debugTypes = static_cast<unsigned>(DebugType::None); |
| 890 | |
| 891 | if (auto *a = args.getLastArg(Ids: OPT_debugtype)) { |
| 892 | SmallVector<StringRef, 3> types; |
| 893 | StringRef(a->getValue()) |
| 894 | .split(A&: types, Separator: ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); |
| 895 | |
| 896 | for (StringRef type : types) { |
| 897 | unsigned v = StringSwitch<unsigned>(type.lower()) |
| 898 | .Case(S: "cv" , Value: static_cast<unsigned>(DebugType::CV)) |
| 899 | .Case(S: "pdata" , Value: static_cast<unsigned>(DebugType::PData)) |
| 900 | .Case(S: "fixup" , Value: static_cast<unsigned>(DebugType::Fixup)) |
| 901 | .Default(Value: 0); |
| 902 | if (v == 0) { |
| 903 | Warn(ctx) << "/debugtype: unknown option '" << type << "'" ; |
| 904 | continue; |
| 905 | } |
| 906 | debugTypes |= v; |
| 907 | } |
| 908 | return debugTypes; |
| 909 | } |
| 910 | |
| 911 | // Default debug types |
| 912 | debugTypes = static_cast<unsigned>(DebugType::CV); |
| 913 | if (args.hasArg(Ids: OPT_driver)) |
| 914 | debugTypes |= static_cast<unsigned>(DebugType::PData); |
| 915 | if (args.hasArg(Ids: OPT_profile)) |
| 916 | debugTypes |= static_cast<unsigned>(DebugType::Fixup); |
| 917 | |
| 918 | return debugTypes; |
| 919 | } |
| 920 | |
| 921 | std::string LinkerDriver::getMapFile(const opt::InputArgList &args, |
| 922 | opt::OptSpecifier os, |
| 923 | opt::OptSpecifier osFile) { |
| 924 | auto *arg = args.getLastArg(Ids: os, Ids: osFile); |
| 925 | if (!arg) |
| 926 | return "" ; |
| 927 | if (arg->getOption().getID() == osFile.getID()) |
| 928 | return arg->getValue(); |
| 929 | |
| 930 | assert(arg->getOption().getID() == os.getID()); |
| 931 | StringRef outFile = ctx.config.outputFile; |
| 932 | return (outFile.substr(Start: 0, N: outFile.rfind(C: '.')) + ".map" ).str(); |
| 933 | } |
| 934 | |
| 935 | std::string LinkerDriver::getImplibPath() { |
| 936 | if (!ctx.config.implib.empty()) |
| 937 | return std::string(ctx.config.implib); |
| 938 | SmallString<128> out = StringRef(ctx.config.outputFile); |
| 939 | sys::path::replace_extension(path&: out, extension: ".lib" ); |
| 940 | return std::string(out); |
| 941 | } |
| 942 | |
| 943 | // The import name is calculated as follows: |
| 944 | // |
| 945 | // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY |
| 946 | // -----+----------------+---------------------+------------------ |
| 947 | // LINK | {value} | {value}.{.dll/.exe} | {output name} |
| 948 | // LIB | {value} | {value}.dll | {output name}.dll |
| 949 | // |
| 950 | std::string LinkerDriver::getImportName(bool asLib) { |
| 951 | SmallString<128> out; |
| 952 | |
| 953 | if (ctx.config.importName.empty()) { |
| 954 | out.assign(RHS: sys::path::filename(path: ctx.config.outputFile)); |
| 955 | if (asLib) |
| 956 | sys::path::replace_extension(path&: out, extension: ".dll" ); |
| 957 | } else { |
| 958 | out.assign(RHS: ctx.config.importName); |
| 959 | if (!sys::path::has_extension(path: out)) |
| 960 | sys::path::replace_extension(path&: out, |
| 961 | extension: (ctx.config.dll || asLib) ? ".dll" : ".exe" ); |
| 962 | } |
| 963 | |
| 964 | return std::string(out); |
| 965 | } |
| 966 | |
| 967 | void LinkerDriver::createImportLibrary(bool asLib) { |
| 968 | llvm::TimeTraceScope timeScope("Create import library" ); |
| 969 | std::vector<COFFShortExport> exports, nativeExports; |
| 970 | |
| 971 | auto getExports = [](SymbolTable &symtab, |
| 972 | std::vector<COFFShortExport> &exports) { |
| 973 | for (Export &e1 : symtab.exports) { |
| 974 | COFFShortExport e2; |
| 975 | e2.Name = std::string(e1.name); |
| 976 | e2.SymbolName = std::string(e1.symbolName); |
| 977 | e2.ExtName = std::string(e1.extName); |
| 978 | e2.ExportAs = std::string(e1.exportAs); |
| 979 | e2.ImportName = std::string(e1.importName); |
| 980 | e2.Ordinal = e1.ordinal; |
| 981 | e2.Noname = e1.noname; |
| 982 | e2.Data = e1.data; |
| 983 | e2.Private = e1.isPrivate; |
| 984 | e2.Constant = e1.constant; |
| 985 | exports.push_back(x: e2); |
| 986 | } |
| 987 | }; |
| 988 | |
| 989 | getExports(ctx.symtab, exports); |
| 990 | if (ctx.config.machine == ARM64X) |
| 991 | getExports(*ctx.hybridSymtab, nativeExports); |
| 992 | |
| 993 | std::string libName = getImportName(asLib); |
| 994 | std::string path = getImplibPath(); |
| 995 | |
| 996 | if (!ctx.config.incremental) { |
| 997 | checkError(e: writeImportLibrary(ImportName: libName, Path: path, Exports: exports, Machine: ctx.config.machine, |
| 998 | MinGW: ctx.config.mingw, NativeExports: nativeExports)); |
| 999 | return; |
| 1000 | } |
| 1001 | |
| 1002 | // If the import library already exists, replace it only if the contents |
| 1003 | // have changed. |
| 1004 | ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( |
| 1005 | Filename: path, /*IsText=*/false, /*RequiresNullTerminator=*/false); |
| 1006 | if (!oldBuf) { |
| 1007 | checkError(e: writeImportLibrary(ImportName: libName, Path: path, Exports: exports, Machine: ctx.config.machine, |
| 1008 | MinGW: ctx.config.mingw, NativeExports: nativeExports)); |
| 1009 | return; |
| 1010 | } |
| 1011 | |
| 1012 | SmallString<128> tmpName; |
| 1013 | if (std::error_code ec = |
| 1014 | sys::fs::createUniqueFile(Model: path + ".tmp-%%%%%%%%.lib" , ResultPath&: tmpName)) |
| 1015 | Fatal(ctx) << "cannot create temporary file for import library " << path |
| 1016 | << ": " << ec.message(); |
| 1017 | |
| 1018 | if (Error e = |
| 1019 | writeImportLibrary(ImportName: libName, Path: tmpName, Exports: exports, Machine: ctx.config.machine, |
| 1020 | MinGW: ctx.config.mingw, NativeExports: nativeExports)) { |
| 1021 | checkError(e: std::move(e)); |
| 1022 | return; |
| 1023 | } |
| 1024 | |
| 1025 | std::unique_ptr<MemoryBuffer> newBuf = check(e: MemoryBuffer::getFile( |
| 1026 | Filename: tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); |
| 1027 | if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { |
| 1028 | oldBuf->reset(); |
| 1029 | checkError(e: errorCodeToError(EC: sys::fs::rename(from: tmpName, to: path))); |
| 1030 | } else { |
| 1031 | sys::fs::remove(path: tmpName); |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | void LinkerDriver::enqueueTask(std::function<void()> task) { |
| 1036 | taskQueue.push_back(x: std::move(task)); |
| 1037 | } |
| 1038 | |
| 1039 | bool LinkerDriver::run() { |
| 1040 | llvm::TimeTraceScope timeScope("Read input files" ); |
| 1041 | ScopedTimer t(ctx.inputFileTimer); |
| 1042 | |
| 1043 | bool didWork = !taskQueue.empty(); |
| 1044 | while (!taskQueue.empty()) { |
| 1045 | taskQueue.front()(); |
| 1046 | taskQueue.pop_front(); |
| 1047 | } |
| 1048 | return didWork; |
| 1049 | } |
| 1050 | |
| 1051 | // Parse an /order file. If an option is given, the linker places |
| 1052 | // COMDAT sections in the same order as their names appear in the |
| 1053 | // given file. |
| 1054 | void LinkerDriver::parseOrderFile(StringRef arg) { |
| 1055 | // For some reason, the MSVC linker requires a filename to be |
| 1056 | // preceded by "@". |
| 1057 | if (!arg.starts_with(Prefix: "@" )) { |
| 1058 | Err(ctx) << "malformed /order option: '@' missing" ; |
| 1059 | return; |
| 1060 | } |
| 1061 | |
| 1062 | // Get a list of all comdat sections for error checking. |
| 1063 | DenseSet<StringRef> set; |
| 1064 | for (Chunk *c : ctx.driver.getChunks()) |
| 1065 | if (auto *sec = dyn_cast<SectionChunk>(Val: c)) |
| 1066 | if (sec->sym) |
| 1067 | set.insert(V: sec->sym->getName()); |
| 1068 | |
| 1069 | // Open a file. |
| 1070 | StringRef path = arg.substr(Start: 1); |
| 1071 | std::unique_ptr<MemoryBuffer> mb = |
| 1072 | CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, |
| 1073 | /*RequiresNullTerminator=*/false, |
| 1074 | /*IsVolatile=*/true), |
| 1075 | "could not open " + path); |
| 1076 | |
| 1077 | // Parse a file. An order file contains one symbol per line. |
| 1078 | // All symbols that were not present in a given order file are |
| 1079 | // considered to have the lowest priority 0 and are placed at |
| 1080 | // end of an output section. |
| 1081 | for (StringRef arg : args::getLines(mb: mb->getMemBufferRef())) { |
| 1082 | std::string s(arg); |
| 1083 | if (ctx.config.machine == I386 && !isDecorated(sym: s)) |
| 1084 | s = "_" + s; |
| 1085 | |
| 1086 | if (set.count(V: s) == 0) { |
| 1087 | if (ctx.config.warnMissingOrderSymbol) |
| 1088 | Warn(ctx) << "/order:" << arg << ": missing symbol: " << s |
| 1089 | << " [LNK4037]" ; |
| 1090 | } else |
| 1091 | ctx.config.order[s] = INT_MIN + ctx.config.order.size(); |
| 1092 | } |
| 1093 | |
| 1094 | // Include in /reproduce: output if applicable. |
| 1095 | ctx.driver.takeBuffer(mb: std::move(mb)); |
| 1096 | } |
| 1097 | |
| 1098 | void LinkerDriver::parseCallGraphFile(StringRef path) { |
| 1099 | std::unique_ptr<MemoryBuffer> mb = |
| 1100 | CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, |
| 1101 | /*RequiresNullTerminator=*/false, |
| 1102 | /*IsVolatile=*/true), |
| 1103 | "could not open " + path); |
| 1104 | |
| 1105 | // Build a map from symbol name to section. |
| 1106 | DenseMap<StringRef, Symbol *> map; |
| 1107 | for (ObjFile *file : ctx.objFileInstances) |
| 1108 | for (Symbol *sym : file->getSymbols()) |
| 1109 | if (sym) |
| 1110 | map[sym->getName()] = sym; |
| 1111 | |
| 1112 | auto findSection = [&](StringRef name) -> SectionChunk * { |
| 1113 | Symbol *sym = map.lookup(Val: name); |
| 1114 | if (!sym) { |
| 1115 | if (ctx.config.warnMissingOrderSymbol) |
| 1116 | Warn(ctx) << path << ": no such symbol: " << name; |
| 1117 | return nullptr; |
| 1118 | } |
| 1119 | |
| 1120 | if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(Val: sym)) |
| 1121 | return dyn_cast_or_null<SectionChunk>(Val: dr->getChunk()); |
| 1122 | return nullptr; |
| 1123 | }; |
| 1124 | |
| 1125 | for (StringRef line : args::getLines(mb: *mb)) { |
| 1126 | SmallVector<StringRef, 3> fields; |
| 1127 | line.split(A&: fields, Separator: ' '); |
| 1128 | uint64_t count; |
| 1129 | |
| 1130 | if (fields.size() != 3 || !to_integer(S: fields[2], Num&: count)) { |
| 1131 | Err(ctx) << path << ": parse error" ; |
| 1132 | return; |
| 1133 | } |
| 1134 | |
| 1135 | if (SectionChunk *from = findSection(fields[0])) |
| 1136 | if (SectionChunk *to = findSection(fields[1])) |
| 1137 | ctx.config.callGraphProfile[{from, to}] += count; |
| 1138 | } |
| 1139 | |
| 1140 | // Include in /reproduce: output if applicable. |
| 1141 | ctx.driver.takeBuffer(mb: std::move(mb)); |
| 1142 | } |
| 1143 | |
| 1144 | static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { |
| 1145 | for (ObjFile *obj : ctx.objFileInstances) { |
| 1146 | if (obj->callgraphSec) { |
| 1147 | ArrayRef<uint8_t> contents; |
| 1148 | cantFail( |
| 1149 | Err: obj->getCOFFObj()->getSectionContents(Sec: obj->callgraphSec, Res&: contents)); |
| 1150 | BinaryStreamReader reader(contents, llvm::endianness::little); |
| 1151 | while (!reader.empty()) { |
| 1152 | uint32_t fromIndex, toIndex; |
| 1153 | uint64_t count; |
| 1154 | if (Error err = reader.readInteger(Dest&: fromIndex)) |
| 1155 | Fatal(ctx) << toString(file: obj) << ": Expected 32-bit integer" ; |
| 1156 | if (Error err = reader.readInteger(Dest&: toIndex)) |
| 1157 | Fatal(ctx) << toString(file: obj) << ": Expected 32-bit integer" ; |
| 1158 | if (Error err = reader.readInteger(Dest&: count)) |
| 1159 | Fatal(ctx) << toString(file: obj) << ": Expected 64-bit integer" ; |
| 1160 | auto *fromSym = dyn_cast_or_null<Defined>(Val: obj->getSymbol(symbolIndex: fromIndex)); |
| 1161 | auto *toSym = dyn_cast_or_null<Defined>(Val: obj->getSymbol(symbolIndex: toIndex)); |
| 1162 | if (!fromSym || !toSym) |
| 1163 | continue; |
| 1164 | auto *from = dyn_cast_or_null<SectionChunk>(Val: fromSym->getChunk()); |
| 1165 | auto *to = dyn_cast_or_null<SectionChunk>(Val: toSym->getChunk()); |
| 1166 | if (from && to) |
| 1167 | ctx.config.callGraphProfile[{from, to}] += count; |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | } |
| 1172 | |
| 1173 | static void markAddrsig(Symbol *s) { |
| 1174 | if (auto *d = dyn_cast_or_null<Defined>(Val: s)) |
| 1175 | if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(Val: d->getChunk())) |
| 1176 | c->keepUnique = true; |
| 1177 | } |
| 1178 | |
| 1179 | static void findKeepUniqueSections(COFFLinkerContext &ctx) { |
| 1180 | llvm::TimeTraceScope timeScope("Find keep unique sections" ); |
| 1181 | |
| 1182 | // Exported symbols could be address-significant in other executables or DSOs, |
| 1183 | // so we conservatively mark them as address-significant. |
| 1184 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
| 1185 | for (Export &r : symtab.exports) |
| 1186 | markAddrsig(s: r.sym); |
| 1187 | }); |
| 1188 | |
| 1189 | // Visit the address-significance table in each object file and mark each |
| 1190 | // referenced symbol as address-significant. |
| 1191 | for (ObjFile *obj : ctx.objFileInstances) { |
| 1192 | ArrayRef<Symbol *> syms = obj->getSymbols(); |
| 1193 | if (obj->addrsigSec) { |
| 1194 | ArrayRef<uint8_t> contents; |
| 1195 | cantFail( |
| 1196 | Err: obj->getCOFFObj()->getSectionContents(Sec: obj->addrsigSec, Res&: contents)); |
| 1197 | const uint8_t *cur = contents.begin(); |
| 1198 | while (cur != contents.end()) { |
| 1199 | unsigned size; |
| 1200 | const char *err = nullptr; |
| 1201 | uint64_t symIndex = decodeULEB128(p: cur, n: &size, end: contents.end(), error: &err); |
| 1202 | if (err) |
| 1203 | Fatal(ctx) << toString(file: obj) |
| 1204 | << ": could not decode addrsig section: " << err; |
| 1205 | if (symIndex >= syms.size()) |
| 1206 | Fatal(ctx) << toString(file: obj) |
| 1207 | << ": invalid symbol index in addrsig section" ; |
| 1208 | markAddrsig(s: syms[symIndex]); |
| 1209 | cur += size; |
| 1210 | } |
| 1211 | } else { |
| 1212 | // If an object file does not have an address-significance table, |
| 1213 | // conservatively mark all of its symbols as address-significant. |
| 1214 | for (Symbol *s : syms) |
| 1215 | markAddrsig(s); |
| 1216 | } |
| 1217 | } |
| 1218 | } |
| 1219 | |
| 1220 | // link.exe replaces each %foo% in altPath with the contents of environment |
| 1221 | // variable foo, and adds the two magic env vars _PDB (expands to the basename |
| 1222 | // of pdb's output path) and _EXT (expands to the extension of the output |
| 1223 | // binary). |
| 1224 | // lld only supports %_PDB% and %_EXT% and warns on references to all other env |
| 1225 | // vars. |
| 1226 | void LinkerDriver::parsePDBAltPath() { |
| 1227 | SmallString<128> buf; |
| 1228 | StringRef pdbBasename = |
| 1229 | sys::path::filename(path: ctx.config.pdbPath, style: sys::path::Style::windows); |
| 1230 | StringRef binaryExtension = |
| 1231 | sys::path::extension(path: ctx.config.outputFile, style: sys::path::Style::windows); |
| 1232 | if (!binaryExtension.empty()) |
| 1233 | binaryExtension = binaryExtension.substr(Start: 1); // %_EXT% does not include '.'. |
| 1234 | |
| 1235 | // Invariant: |
| 1236 | // +--------- cursor ('a...' might be the empty string). |
| 1237 | // | +----- firstMark |
| 1238 | // | | +- secondMark |
| 1239 | // v v v |
| 1240 | // a...%...%... |
| 1241 | size_t cursor = 0; |
| 1242 | while (cursor < ctx.config.pdbAltPath.size()) { |
| 1243 | size_t firstMark, secondMark; |
| 1244 | if ((firstMark = ctx.config.pdbAltPath.find(C: '%', From: cursor)) == |
| 1245 | StringRef::npos || |
| 1246 | (secondMark = ctx.config.pdbAltPath.find(C: '%', From: firstMark + 1)) == |
| 1247 | StringRef::npos) { |
| 1248 | // Didn't find another full fragment, treat rest of string as literal. |
| 1249 | buf.append(RHS: ctx.config.pdbAltPath.substr(Start: cursor)); |
| 1250 | break; |
| 1251 | } |
| 1252 | |
| 1253 | // Found a full fragment. Append text in front of first %, and interpret |
| 1254 | // text between first and second % as variable name. |
| 1255 | buf.append(RHS: ctx.config.pdbAltPath.substr(Start: cursor, N: firstMark - cursor)); |
| 1256 | StringRef var = |
| 1257 | ctx.config.pdbAltPath.substr(Start: firstMark, N: secondMark - firstMark + 1); |
| 1258 | if (var.equals_insensitive(RHS: "%_pdb%" )) |
| 1259 | buf.append(RHS: pdbBasename); |
| 1260 | else if (var.equals_insensitive(RHS: "%_ext%" )) |
| 1261 | buf.append(RHS: binaryExtension); |
| 1262 | else { |
| 1263 | Warn(ctx) << "only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " |
| 1264 | << var << " as literal" ; |
| 1265 | buf.append(RHS: var); |
| 1266 | } |
| 1267 | |
| 1268 | cursor = secondMark + 1; |
| 1269 | } |
| 1270 | |
| 1271 | ctx.config.pdbAltPath = buf; |
| 1272 | } |
| 1273 | |
| 1274 | /// Convert resource files and potentially merge input resource object |
| 1275 | /// trees into one resource tree. |
| 1276 | /// Call after ObjFile::Instances is complete. |
| 1277 | void LinkerDriver::convertResources() { |
| 1278 | llvm::TimeTraceScope timeScope("Convert resources" ); |
| 1279 | std::vector<ObjFile *> resourceObjFiles; |
| 1280 | |
| 1281 | for (ObjFile *f : ctx.objFileInstances) { |
| 1282 | if (f->isResourceObjFile()) |
| 1283 | resourceObjFiles.push_back(x: f); |
| 1284 | } |
| 1285 | |
| 1286 | if (!ctx.config.mingw && |
| 1287 | (resourceObjFiles.size() > 1 || |
| 1288 | (resourceObjFiles.size() == 1 && !resources.empty()))) { |
| 1289 | Err(ctx) << (!resources.empty() |
| 1290 | ? "internal .obj file created from .res files" |
| 1291 | : toString(file: resourceObjFiles[1])) |
| 1292 | << ": more than one resource obj file not allowed, already got " |
| 1293 | << resourceObjFiles.front(); |
| 1294 | return; |
| 1295 | } |
| 1296 | |
| 1297 | if (resources.empty() && resourceObjFiles.size() <= 1) { |
| 1298 | // No resources to convert, and max one resource object file in |
| 1299 | // the input. Keep that preconverted resource section as is. |
| 1300 | for (ObjFile *f : resourceObjFiles) |
| 1301 | f->includeResourceChunks(); |
| 1302 | return; |
| 1303 | } |
| 1304 | ObjFile *f = |
| 1305 | ObjFile::create(ctx, mb: convertResToCOFF(mbs: resources, objs: resourceObjFiles)); |
| 1306 | addFile(file: f); |
| 1307 | f->includeResourceChunks(); |
| 1308 | } |
| 1309 | |
| 1310 | void LinkerDriver::maybeCreateECExportThunk(StringRef name, Symbol *&sym) { |
| 1311 | Defined *def; |
| 1312 | if (!sym) |
| 1313 | return; |
| 1314 | if (auto undef = dyn_cast<Undefined>(Val: sym)) |
| 1315 | def = undef->getDefinedWeakAlias(); |
| 1316 | else |
| 1317 | def = dyn_cast<Defined>(Val: sym); |
| 1318 | if (!def) |
| 1319 | return; |
| 1320 | |
| 1321 | if (def->getChunk()->getArm64ECRangeType() != chpe_range_type::Arm64EC) |
| 1322 | return; |
| 1323 | StringRef expName; |
| 1324 | if (auto mangledName = getArm64ECMangledFunctionName(Name: name)) |
| 1325 | expName = saver().save(S: "EXP+" + *mangledName); |
| 1326 | else |
| 1327 | expName = saver().save(S: "EXP+" + name); |
| 1328 | sym = ctx.symtab.addGCRoot(sym: expName); |
| 1329 | if (auto undef = dyn_cast<Undefined>(Val: sym)) { |
| 1330 | if (!undef->getWeakAlias()) { |
| 1331 | auto thunk = make<ECExportThunkChunk>(args&: def); |
| 1332 | replaceSymbol<DefinedSynthetic>(s: undef, arg: undef->getName(), arg&: thunk); |
| 1333 | } |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | void LinkerDriver::createECExportThunks() { |
| 1338 | // Check if EXP+ symbols have corresponding $hp_target symbols and use them |
| 1339 | // to create export thunks when available. |
| 1340 | for (Symbol *s : ctx.symtab.expSymbols) { |
| 1341 | if (!s->isUsedInRegularObj) |
| 1342 | continue; |
| 1343 | assert(s->getName().starts_with("EXP+" )); |
| 1344 | std::string targetName = |
| 1345 | (s->getName().substr(Start: strlen(s: "EXP+" )) + "$hp_target" ).str(); |
| 1346 | Symbol *sym = ctx.symtab.find(name: targetName); |
| 1347 | if (!sym) |
| 1348 | continue; |
| 1349 | Defined *targetSym; |
| 1350 | if (auto undef = dyn_cast<Undefined>(Val: sym)) |
| 1351 | targetSym = undef->getDefinedWeakAlias(); |
| 1352 | else |
| 1353 | targetSym = dyn_cast<Defined>(Val: sym); |
| 1354 | if (!targetSym) |
| 1355 | continue; |
| 1356 | |
| 1357 | auto *undef = dyn_cast<Undefined>(Val: s); |
| 1358 | if (undef && !undef->getWeakAlias()) { |
| 1359 | auto thunk = make<ECExportThunkChunk>(args&: targetSym); |
| 1360 | replaceSymbol<DefinedSynthetic>(s: undef, arg: undef->getName(), arg&: thunk); |
| 1361 | } |
| 1362 | if (!targetSym->isGCRoot) { |
| 1363 | targetSym->isGCRoot = true; |
| 1364 | ctx.config.gcroot.push_back(x: targetSym); |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | if (ctx.symtab.entry) |
| 1369 | maybeCreateECExportThunk(name: ctx.symtab.entry->getName(), sym&: ctx.symtab.entry); |
| 1370 | for (Export &e : ctx.symtab.exports) { |
| 1371 | if (!e.data) |
| 1372 | maybeCreateECExportThunk(name: e.extName.empty() ? e.name : e.extName, sym&: e.sym); |
| 1373 | } |
| 1374 | } |
| 1375 | |
| 1376 | void LinkerDriver::pullArm64ECIcallHelper() { |
| 1377 | if (!ctx.config.arm64ECIcallHelper) |
| 1378 | ctx.config.arm64ECIcallHelper = |
| 1379 | ctx.symtab.addGCRoot(sym: "__icall_helper_arm64ec" ); |
| 1380 | } |
| 1381 | |
| 1382 | // In MinGW, if no symbols are chosen to be exported, then all symbols are |
| 1383 | // automatically exported by default. This behavior can be forced by the |
| 1384 | // -export-all-symbols option, so that it happens even when exports are |
| 1385 | // explicitly specified. The automatic behavior can be disabled using the |
| 1386 | // -exclude-all-symbols option, so that lld-link behaves like link.exe rather |
| 1387 | // than MinGW in the case that nothing is explicitly exported. |
| 1388 | void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { |
| 1389 | if (!args.hasArg(Ids: OPT_export_all_symbols)) { |
| 1390 | if (!ctx.config.dll) |
| 1391 | return; |
| 1392 | |
| 1393 | if (ctx.symtab.hadExplicitExports || |
| 1394 | (ctx.config.machine == ARM64X && ctx.hybridSymtab->hadExplicitExports)) |
| 1395 | return; |
| 1396 | if (args.hasArg(Ids: OPT_exclude_all_symbols)) |
| 1397 | return; |
| 1398 | } |
| 1399 | |
| 1400 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
| 1401 | AutoExporter exporter(symtab, excludedSymbols); |
| 1402 | |
| 1403 | for (auto *arg : args.filtered(Ids: OPT_wholearchive_file)) |
| 1404 | if (std::optional<StringRef> path = findFile(filename: arg->getValue())) |
| 1405 | exporter.addWholeArchive(path: *path); |
| 1406 | |
| 1407 | for (auto *arg : args.filtered(Ids: OPT_exclude_symbols)) { |
| 1408 | SmallVector<StringRef, 2> vec; |
| 1409 | StringRef(arg->getValue()).split(A&: vec, Separator: ','); |
| 1410 | for (StringRef sym : vec) |
| 1411 | exporter.addExcludedSymbol(symbol: symtab.mangle(sym)); |
| 1412 | } |
| 1413 | |
| 1414 | symtab.forEachSymbol(callback: [&](Symbol *s) { |
| 1415 | auto *def = dyn_cast<Defined>(Val: s); |
| 1416 | if (!exporter.shouldExport(sym: def)) |
| 1417 | return; |
| 1418 | |
| 1419 | if (!def->isGCRoot) { |
| 1420 | def->isGCRoot = true; |
| 1421 | ctx.config.gcroot.push_back(x: def); |
| 1422 | } |
| 1423 | |
| 1424 | Export e; |
| 1425 | e.name = def->getName(); |
| 1426 | e.sym = def; |
| 1427 | if (Chunk *c = def->getChunk()) |
| 1428 | if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) |
| 1429 | e.data = true; |
| 1430 | s->isUsedInRegularObj = true; |
| 1431 | symtab.exports.push_back(x: e); |
| 1432 | }); |
| 1433 | }); |
| 1434 | } |
| 1435 | |
| 1436 | // lld has a feature to create a tar file containing all input files as well as |
| 1437 | // all command line options, so that other people can run lld again with exactly |
| 1438 | // the same inputs. This feature is accessible via /linkrepro and /reproduce. |
| 1439 | // |
| 1440 | // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory |
| 1441 | // name while /reproduce takes a full path. We have /linkrepro for compatibility |
| 1442 | // with Microsoft link.exe. |
| 1443 | std::optional<std::string> getReproduceFile(const opt::InputArgList &args) { |
| 1444 | if (auto *arg = args.getLastArg(Ids: OPT_reproduce)) |
| 1445 | return std::string(arg->getValue()); |
| 1446 | |
| 1447 | if (auto *arg = args.getLastArg(Ids: OPT_linkrepro)) { |
| 1448 | SmallString<64> path = StringRef(arg->getValue()); |
| 1449 | sys::path::append(path, a: "repro.tar" ); |
| 1450 | return std::string(path); |
| 1451 | } |
| 1452 | |
| 1453 | // This is intentionally not guarded by OPT_lldignoreenv since writing |
| 1454 | // a repro tar file doesn't affect the main output. |
| 1455 | if (auto *path = getenv(name: "LLD_REPRODUCE" )) |
| 1456 | return std::string(path); |
| 1457 | |
| 1458 | return std::nullopt; |
| 1459 | } |
| 1460 | |
| 1461 | static std::unique_ptr<llvm::vfs::FileSystem> |
| 1462 | getVFS(COFFLinkerContext &ctx, const opt::InputArgList &args) { |
| 1463 | using namespace llvm::vfs; |
| 1464 | |
| 1465 | const opt::Arg *arg = args.getLastArg(Ids: OPT_vfsoverlay); |
| 1466 | if (!arg) |
| 1467 | return nullptr; |
| 1468 | |
| 1469 | auto bufOrErr = llvm::MemoryBuffer::getFile(Filename: arg->getValue()); |
| 1470 | if (!bufOrErr) { |
| 1471 | checkError(e: errorCodeToError(EC: bufOrErr.getError())); |
| 1472 | return nullptr; |
| 1473 | } |
| 1474 | |
| 1475 | if (auto ret = vfs::getVFSFromYAML(Buffer: std::move(*bufOrErr), |
| 1476 | /*DiagHandler*/ nullptr, YAMLFilePath: arg->getValue())) |
| 1477 | return ret; |
| 1478 | |
| 1479 | Err(ctx) << "Invalid vfs overlay" ; |
| 1480 | return nullptr; |
| 1481 | } |
| 1482 | |
| 1483 | constexpr const char *lldsaveTempsValues[] = { |
| 1484 | "resolution" , "preopt" , "promote" , "internalize" , "import" , |
| 1485 | "opt" , "precodegen" , "prelink" , "combinedindex" }; |
| 1486 | |
| 1487 | void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { |
| 1488 | ScopedTimer rootTimer(ctx.rootTimer); |
| 1489 | Configuration *config = &ctx.config; |
| 1490 | |
| 1491 | // Needed for LTO. |
| 1492 | InitializeAllTargetInfos(); |
| 1493 | InitializeAllTargets(); |
| 1494 | InitializeAllTargetMCs(); |
| 1495 | InitializeAllAsmParsers(); |
| 1496 | InitializeAllAsmPrinters(); |
| 1497 | |
| 1498 | // If the first command line argument is "/lib", link.exe acts like lib.exe. |
| 1499 | // We call our own implementation of lib.exe that understands bitcode files. |
| 1500 | if (argsArr.size() > 1 && |
| 1501 | (StringRef(argsArr[1]).equals_insensitive(RHS: "/lib" ) || |
| 1502 | StringRef(argsArr[1]).equals_insensitive(RHS: "-lib" ))) { |
| 1503 | if (llvm::libDriverMain(ARgs: argsArr.slice(N: 1)) != 0) |
| 1504 | Fatal(ctx) << "lib failed" ; |
| 1505 | return; |
| 1506 | } |
| 1507 | |
| 1508 | // Parse command line options. |
| 1509 | ArgParser parser(ctx); |
| 1510 | opt::InputArgList args = parser.parse(args: argsArr); |
| 1511 | |
| 1512 | // Initialize time trace profiler. |
| 1513 | config->timeTraceEnabled = args.hasArg(Ids: OPT_time_trace_eq); |
| 1514 | config->timeTraceGranularity = |
| 1515 | args::getInteger(args, key: OPT_time_trace_granularity_eq, Default: 500); |
| 1516 | |
| 1517 | if (config->timeTraceEnabled) |
| 1518 | timeTraceProfilerInitialize(TimeTraceGranularity: config->timeTraceGranularity, ProcName: argsArr[0]); |
| 1519 | |
| 1520 | llvm::TimeTraceScope timeScope("COFF link" ); |
| 1521 | |
| 1522 | // Parse and evaluate -mllvm options. |
| 1523 | std::vector<const char *> v; |
| 1524 | v.push_back(x: "lld-link (LLVM option parsing)" ); |
| 1525 | for (const auto *arg : args.filtered(Ids: OPT_mllvm)) { |
| 1526 | v.push_back(x: arg->getValue()); |
| 1527 | config->mllvmOpts.emplace_back(Args: arg->getValue()); |
| 1528 | } |
| 1529 | { |
| 1530 | llvm::TimeTraceScope timeScope2("Parse cl::opt" ); |
| 1531 | cl::ResetAllOptionOccurrences(); |
| 1532 | cl::ParseCommandLineOptions(argc: v.size(), argv: v.data()); |
| 1533 | } |
| 1534 | |
| 1535 | // Handle /errorlimit early, because error() depends on it. |
| 1536 | if (auto *arg = args.getLastArg(Ids: OPT_errorlimit)) { |
| 1537 | int n = 20; |
| 1538 | StringRef s = arg->getValue(); |
| 1539 | if (s.getAsInteger(Radix: 10, Result&: n)) |
| 1540 | Err(ctx) << arg->getSpelling() << " number expected, but got " << s; |
| 1541 | ctx.e.errorLimit = n; |
| 1542 | } |
| 1543 | |
| 1544 | config->vfs = getVFS(ctx, args); |
| 1545 | |
| 1546 | // Handle /help |
| 1547 | if (args.hasArg(Ids: OPT_help)) { |
| 1548 | printHelp(argv0: argsArr[0]); |
| 1549 | return; |
| 1550 | } |
| 1551 | |
| 1552 | // /threads: takes a positive integer and provides the default value for |
| 1553 | // /opt:lldltojobs=. |
| 1554 | if (auto *arg = args.getLastArg(Ids: OPT_threads)) { |
| 1555 | StringRef v(arg->getValue()); |
| 1556 | unsigned threads = 0; |
| 1557 | if (!llvm::to_integer(S: v, Num&: threads, Base: 0) || threads == 0) |
| 1558 | Err(ctx) << arg->getSpelling() |
| 1559 | << ": expected a positive integer, but got '" << arg->getValue() |
| 1560 | << "'" ; |
| 1561 | parallel::strategy = hardware_concurrency(ThreadCount: threads); |
| 1562 | config->thinLTOJobs = v.str(); |
| 1563 | } |
| 1564 | |
| 1565 | if (args.hasArg(Ids: OPT_show_timing)) |
| 1566 | config->showTiming = true; |
| 1567 | |
| 1568 | config->showSummary = args.hasArg(Ids: OPT_summary); |
| 1569 | config->printSearchPaths = args.hasArg(Ids: OPT_print_search_paths); |
| 1570 | |
| 1571 | // Handle --version, which is an lld extension. This option is a bit odd |
| 1572 | // because it doesn't start with "/", but we deliberately chose "--" to |
| 1573 | // avoid conflict with /version and for compatibility with clang-cl. |
| 1574 | if (args.hasArg(Ids: OPT_dash_dash_version)) { |
| 1575 | Msg(ctx) << getLLDVersion(); |
| 1576 | return; |
| 1577 | } |
| 1578 | |
| 1579 | // Handle /lldmingw early, since it can potentially affect how other |
| 1580 | // options are handled. |
| 1581 | config->mingw = args.hasArg(Ids: OPT_lldmingw); |
| 1582 | if (config->mingw) |
| 1583 | ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now" |
| 1584 | " (use --error-limit=0 to see all errors)" ; |
| 1585 | |
| 1586 | // Handle /linkrepro and /reproduce. |
| 1587 | { |
| 1588 | llvm::TimeTraceScope timeScope2("Reproducer" ); |
| 1589 | if (std::optional<std::string> path = getReproduceFile(args)) { |
| 1590 | Expected<std::unique_ptr<TarWriter>> errOrWriter = |
| 1591 | TarWriter::create(OutputPath: *path, BaseDir: sys::path::stem(path: *path)); |
| 1592 | |
| 1593 | if (errOrWriter) { |
| 1594 | tar = std::move(*errOrWriter); |
| 1595 | } else { |
| 1596 | Err(ctx) << "/linkrepro: failed to open " << *path << ": " |
| 1597 | << toString(E: errOrWriter.takeError()); |
| 1598 | } |
| 1599 | } |
| 1600 | } |
| 1601 | |
| 1602 | if (!args.hasArg(Ids: OPT_INPUT, Ids: OPT_wholearchive_file)) { |
| 1603 | if (args.hasArg(Ids: OPT_deffile)) |
| 1604 | config->noEntry = true; |
| 1605 | else |
| 1606 | Fatal(ctx) << "no input files" ; |
| 1607 | } |
| 1608 | |
| 1609 | // Construct search path list. |
| 1610 | { |
| 1611 | llvm::TimeTraceScope timeScope2("Search paths" ); |
| 1612 | searchPaths.emplace_back(args: "" ); |
| 1613 | for (auto *arg : args.filtered(Ids: OPT_libpath)) |
| 1614 | searchPaths.push_back(x: arg->getValue()); |
| 1615 | if (!config->mingw) { |
| 1616 | // Prefer the Clang provided builtins over the ones bundled with MSVC. |
| 1617 | // In MinGW mode, the compiler driver passes the necessary libpath |
| 1618 | // options explicitly. |
| 1619 | addClangLibSearchPaths(argv0: argsArr[0]); |
| 1620 | // Don't automatically deduce the lib path from the environment or MSVC |
| 1621 | // installations when operating in mingw mode. (This also makes LLD ignore |
| 1622 | // winsysroot and vctoolsdir arguments.) |
| 1623 | detectWinSysRoot(Args: args); |
| 1624 | if (!args.hasArg(Ids: OPT_lldignoreenv, Ids: OPT_winsysroot, Ids: OPT_vctoolsdir, |
| 1625 | Ids: OPT_vctoolsversion, Ids: OPT_winsdkdir, Ids: OPT_winsdkversion)) |
| 1626 | addLibSearchPaths(); |
| 1627 | } else { |
| 1628 | if (args.hasArg(Ids: OPT_vctoolsdir, Ids: OPT_winsysroot)) |
| 1629 | Warn(ctx) << "ignoring /vctoolsdir or /winsysroot flags in MinGW mode" ; |
| 1630 | } |
| 1631 | } |
| 1632 | |
| 1633 | // Handle /ignore |
| 1634 | for (auto *arg : args.filtered(Ids: OPT_ignore)) { |
| 1635 | SmallVector<StringRef, 8> vec; |
| 1636 | StringRef(arg->getValue()).split(A&: vec, Separator: ','); |
| 1637 | for (StringRef s : vec) { |
| 1638 | if (s == "4037" ) |
| 1639 | config->warnMissingOrderSymbol = false; |
| 1640 | else if (s == "4099" ) |
| 1641 | config->warnDebugInfoUnusable = false; |
| 1642 | else if (s == "4217" ) |
| 1643 | config->warnLocallyDefinedImported = false; |
| 1644 | else if (s == "longsections" ) |
| 1645 | config->warnLongSectionNames = false; |
| 1646 | else if (s == "exporteddllmain" ) |
| 1647 | config->warnExportedDllMain = false; |
| 1648 | // Other warning numbers are ignored. |
| 1649 | } |
| 1650 | } |
| 1651 | |
| 1652 | // Handle /out |
| 1653 | if (auto *arg = args.getLastArg(Ids: OPT_out)) |
| 1654 | config->outputFile = arg->getValue(); |
| 1655 | |
| 1656 | // Handle /verbose |
| 1657 | if (args.hasArg(Ids: OPT_verbose)) |
| 1658 | config->verbose = true; |
| 1659 | ctx.e.verbose = config->verbose; |
| 1660 | |
| 1661 | // Handle /force or /force:unresolved |
| 1662 | if (args.hasArg(Ids: OPT_force, Ids: OPT_force_unresolved)) |
| 1663 | config->forceUnresolved = true; |
| 1664 | |
| 1665 | // Handle /force or /force:multiple |
| 1666 | if (args.hasArg(Ids: OPT_force, Ids: OPT_force_multiple)) |
| 1667 | config->forceMultiple = true; |
| 1668 | |
| 1669 | // Handle /force or /force:multipleres |
| 1670 | if (args.hasArg(Ids: OPT_force, Ids: OPT_force_multipleres)) |
| 1671 | config->forceMultipleRes = true; |
| 1672 | |
| 1673 | // Don't warn about long section names, such as .debug_info, for mingw (or |
| 1674 | // when -debug:dwarf is requested, handled below). |
| 1675 | if (config->mingw) |
| 1676 | config->warnLongSectionNames = false; |
| 1677 | |
| 1678 | bool doGC = true; |
| 1679 | |
| 1680 | // Handle /debug |
| 1681 | bool shouldCreatePDB = false; |
| 1682 | for (auto *arg : args.filtered(Ids: OPT_debug, Ids: OPT_debug_opt)) { |
| 1683 | std::string str; |
| 1684 | if (arg->getOption().getID() == OPT_debug) |
| 1685 | str = "full" ; |
| 1686 | else |
| 1687 | str = StringRef(arg->getValue()).lower(); |
| 1688 | SmallVector<StringRef, 1> vec; |
| 1689 | StringRef(str).split(A&: vec, Separator: ','); |
| 1690 | for (StringRef s : vec) { |
| 1691 | if (s == "fastlink" ) { |
| 1692 | Warn(ctx) << "/debug:fastlink unsupported; using /debug:full" ; |
| 1693 | s = "full" ; |
| 1694 | } |
| 1695 | if (s == "none" ) { |
| 1696 | config->debug = false; |
| 1697 | config->incremental = false; |
| 1698 | config->includeDwarfChunks = false; |
| 1699 | config->debugGHashes = false; |
| 1700 | config->writeSymtab = false; |
| 1701 | shouldCreatePDB = false; |
| 1702 | doGC = true; |
| 1703 | } else if (s == "full" || s == "ghash" || s == "noghash" ) { |
| 1704 | config->debug = true; |
| 1705 | config->incremental = true; |
| 1706 | config->includeDwarfChunks = true; |
| 1707 | if (s == "full" || s == "ghash" ) |
| 1708 | config->debugGHashes = true; |
| 1709 | shouldCreatePDB = true; |
| 1710 | doGC = false; |
| 1711 | } else if (s == "dwarf" ) { |
| 1712 | config->debug = true; |
| 1713 | config->incremental = true; |
| 1714 | config->includeDwarfChunks = true; |
| 1715 | config->writeSymtab = true; |
| 1716 | config->warnLongSectionNames = false; |
| 1717 | doGC = false; |
| 1718 | } else if (s == "nodwarf" ) { |
| 1719 | config->includeDwarfChunks = false; |
| 1720 | } else if (s == "symtab" ) { |
| 1721 | config->writeSymtab = true; |
| 1722 | doGC = false; |
| 1723 | } else if (s == "nosymtab" ) { |
| 1724 | config->writeSymtab = false; |
| 1725 | } else { |
| 1726 | Err(ctx) << "/debug: unknown option: " << s; |
| 1727 | } |
| 1728 | } |
| 1729 | } |
| 1730 | |
| 1731 | // Handle /demangle |
| 1732 | config->demangle = args.hasFlag(Pos: OPT_demangle, Neg: OPT_demangle_no, Default: true); |
| 1733 | |
| 1734 | // Handle /debugtype |
| 1735 | config->debugTypes = parseDebugTypes(ctx, args); |
| 1736 | |
| 1737 | // Handle /driver[:uponly|:wdm]. |
| 1738 | config->driverUponly = args.hasArg(Ids: OPT_driver_uponly) || |
| 1739 | args.hasArg(Ids: OPT_driver_uponly_wdm) || |
| 1740 | args.hasArg(Ids: OPT_driver_wdm_uponly); |
| 1741 | config->driverWdm = args.hasArg(Ids: OPT_driver_wdm) || |
| 1742 | args.hasArg(Ids: OPT_driver_uponly_wdm) || |
| 1743 | args.hasArg(Ids: OPT_driver_wdm_uponly); |
| 1744 | config->driver = |
| 1745 | config->driverUponly || config->driverWdm || args.hasArg(Ids: OPT_driver); |
| 1746 | |
| 1747 | // Handle /pdb |
| 1748 | if (shouldCreatePDB) { |
| 1749 | if (auto *arg = args.getLastArg(Ids: OPT_pdb)) |
| 1750 | config->pdbPath = arg->getValue(); |
| 1751 | if (auto *arg = args.getLastArg(Ids: OPT_pdbaltpath)) |
| 1752 | config->pdbAltPath = arg->getValue(); |
| 1753 | if (auto *arg = args.getLastArg(Ids: OPT_pdbpagesize)) |
| 1754 | parsePDBPageSize(arg->getValue()); |
| 1755 | if (args.hasArg(Ids: OPT_natvis)) |
| 1756 | config->natvisFiles = args.getAllArgValues(Id: OPT_natvis); |
| 1757 | if (args.hasArg(Ids: OPT_pdbstream)) { |
| 1758 | for (const StringRef value : args.getAllArgValues(Id: OPT_pdbstream)) { |
| 1759 | const std::pair<StringRef, StringRef> nameFile = value.split(Separator: "=" ); |
| 1760 | const StringRef name = nameFile.first; |
| 1761 | const std::string file = nameFile.second.str(); |
| 1762 | config->namedStreams[name] = file; |
| 1763 | } |
| 1764 | } |
| 1765 | |
| 1766 | if (auto *arg = args.getLastArg(Ids: OPT_pdb_source_path)) |
| 1767 | config->pdbSourcePath = arg->getValue(); |
| 1768 | } |
| 1769 | |
| 1770 | // Handle /pdbstripped |
| 1771 | if (args.hasArg(Ids: OPT_pdbstripped)) |
| 1772 | Warn(ctx) << "ignoring /pdbstripped flag, it is not yet supported" ; |
| 1773 | |
| 1774 | // Handle /noentry |
| 1775 | if (args.hasArg(Ids: OPT_noentry)) { |
| 1776 | if (args.hasArg(Ids: OPT_dll)) |
| 1777 | config->noEntry = true; |
| 1778 | else |
| 1779 | Err(ctx) << "/noentry must be specified with /dll" ; |
| 1780 | } |
| 1781 | |
| 1782 | // Handle /dll |
| 1783 | if (args.hasArg(Ids: OPT_dll)) { |
| 1784 | config->dll = true; |
| 1785 | config->manifestID = 2; |
| 1786 | } |
| 1787 | |
| 1788 | // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase |
| 1789 | // because we need to explicitly check whether that option or its inverse was |
| 1790 | // present in the argument list in order to handle /fixed. |
| 1791 | auto *dynamicBaseArg = args.getLastArg(Ids: OPT_dynamicbase, Ids: OPT_dynamicbase_no); |
| 1792 | if (dynamicBaseArg && |
| 1793 | dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) |
| 1794 | config->dynamicBase = false; |
| 1795 | |
| 1796 | // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the |
| 1797 | // default setting for any other project type.", but link.exe defaults to |
| 1798 | // /FIXED:NO for exe outputs as well. Match behavior, not docs. |
| 1799 | bool fixed = args.hasFlag(Pos: OPT_fixed, Neg: OPT_fixed_no, Default: false); |
| 1800 | if (fixed) { |
| 1801 | if (dynamicBaseArg && |
| 1802 | dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { |
| 1803 | Err(ctx) << "/fixed must not be specified with /dynamicbase" ; |
| 1804 | } else { |
| 1805 | config->relocatable = false; |
| 1806 | config->dynamicBase = false; |
| 1807 | } |
| 1808 | } |
| 1809 | |
| 1810 | // Handle /appcontainer |
| 1811 | config->appContainer = |
| 1812 | args.hasFlag(Pos: OPT_appcontainer, Neg: OPT_appcontainer_no, Default: false); |
| 1813 | |
| 1814 | // Handle /machine |
| 1815 | { |
| 1816 | llvm::TimeTraceScope timeScope2("Machine arg" ); |
| 1817 | if (auto *arg = args.getLastArg(Ids: OPT_machine)) { |
| 1818 | MachineTypes machine = getMachineType(S: arg->getValue()); |
| 1819 | if (machine == IMAGE_FILE_MACHINE_UNKNOWN) |
| 1820 | Fatal(ctx) << "unknown /machine argument: " << arg->getValue(); |
| 1821 | setMachine(machine); |
| 1822 | } |
| 1823 | } |
| 1824 | |
| 1825 | // Handle /nodefaultlib:<filename> |
| 1826 | { |
| 1827 | llvm::TimeTraceScope timeScope2("Nodefaultlib" ); |
| 1828 | for (auto *arg : args.filtered(Ids: OPT_nodefaultlib)) |
| 1829 | config->noDefaultLibs.insert(x: findLib(filename: arg->getValue()).lower()); |
| 1830 | } |
| 1831 | |
| 1832 | // Handle /nodefaultlib |
| 1833 | if (args.hasArg(Ids: OPT_nodefaultlib_all)) |
| 1834 | config->noDefaultLibAll = true; |
| 1835 | |
| 1836 | // Handle /base |
| 1837 | if (auto *arg = args.getLastArg(Ids: OPT_base)) |
| 1838 | parseNumbers(arg: arg->getValue(), addr: &config->imageBase); |
| 1839 | |
| 1840 | // Handle /filealign |
| 1841 | if (auto *arg = args.getLastArg(Ids: OPT_filealign)) { |
| 1842 | parseNumbers(arg: arg->getValue(), addr: &config->fileAlign); |
| 1843 | if (!isPowerOf2_64(Value: config->fileAlign)) |
| 1844 | Err(ctx) << "/filealign: not a power of two: " << config->fileAlign; |
| 1845 | } |
| 1846 | |
| 1847 | // Handle /stack |
| 1848 | if (auto *arg = args.getLastArg(Ids: OPT_stack)) |
| 1849 | parseNumbers(arg: arg->getValue(), addr: &config->stackReserve, size: &config->stackCommit); |
| 1850 | |
| 1851 | // Handle /guard:cf |
| 1852 | if (auto *arg = args.getLastArg(Ids: OPT_guard)) |
| 1853 | parseGuard(arg: arg->getValue()); |
| 1854 | |
| 1855 | // Handle /heap |
| 1856 | if (auto *arg = args.getLastArg(Ids: OPT_heap)) |
| 1857 | parseNumbers(arg: arg->getValue(), addr: &config->heapReserve, size: &config->heapCommit); |
| 1858 | |
| 1859 | // Handle /version |
| 1860 | if (auto *arg = args.getLastArg(Ids: OPT_version)) |
| 1861 | parseVersion(arg: arg->getValue(), major: &config->majorImageVersion, |
| 1862 | minor: &config->minorImageVersion); |
| 1863 | |
| 1864 | // Handle /subsystem |
| 1865 | if (auto *arg = args.getLastArg(Ids: OPT_subsystem)) |
| 1866 | parseSubsystem(arg: arg->getValue(), sys: &config->subsystem, |
| 1867 | major: &config->majorSubsystemVersion, |
| 1868 | minor: &config->minorSubsystemVersion); |
| 1869 | |
| 1870 | // Handle /osversion |
| 1871 | if (auto *arg = args.getLastArg(Ids: OPT_osversion)) { |
| 1872 | parseVersion(arg: arg->getValue(), major: &config->majorOSVersion, |
| 1873 | minor: &config->minorOSVersion); |
| 1874 | } else { |
| 1875 | config->majorOSVersion = config->majorSubsystemVersion; |
| 1876 | config->minorOSVersion = config->minorSubsystemVersion; |
| 1877 | } |
| 1878 | |
| 1879 | // Handle /timestamp |
| 1880 | if (llvm::opt::Arg *arg = args.getLastArg(Ids: OPT_timestamp, Ids: OPT_repro)) { |
| 1881 | if (arg->getOption().getID() == OPT_repro) { |
| 1882 | config->timestamp = 0; |
| 1883 | config->repro = true; |
| 1884 | } else { |
| 1885 | config->repro = false; |
| 1886 | StringRef value(arg->getValue()); |
| 1887 | if (value.getAsInteger(Radix: 0, Result&: config->timestamp)) |
| 1888 | Fatal(ctx) << "invalid timestamp: " << value |
| 1889 | << ". Expected 32-bit integer" ; |
| 1890 | } |
| 1891 | } else { |
| 1892 | config->repro = false; |
| 1893 | if (std::optional<std::string> epoch = |
| 1894 | Process::GetEnv(name: "SOURCE_DATE_EPOCH" )) { |
| 1895 | StringRef value(*epoch); |
| 1896 | if (value.getAsInteger(Radix: 0, Result&: config->timestamp)) |
| 1897 | Fatal(ctx) << "invalid SOURCE_DATE_EPOCH timestamp: " << value |
| 1898 | << ". Expected 32-bit integer" ; |
| 1899 | } else { |
| 1900 | config->timestamp = time(timer: nullptr); |
| 1901 | } |
| 1902 | } |
| 1903 | |
| 1904 | // Handle /alternatename |
| 1905 | for (auto *arg : args.filtered(Ids: OPT_alternatename)) |
| 1906 | ctx.symtab.parseAlternateName(arg->getValue()); |
| 1907 | |
| 1908 | // Handle /include |
| 1909 | for (auto *arg : args.filtered(Ids: OPT_incl)) |
| 1910 | ctx.symtab.addGCRoot(sym: arg->getValue()); |
| 1911 | |
| 1912 | // Handle /implib |
| 1913 | if (auto *arg = args.getLastArg(Ids: OPT_implib)) |
| 1914 | config->implib = arg->getValue(); |
| 1915 | |
| 1916 | config->noimplib = args.hasArg(Ids: OPT_noimplib); |
| 1917 | |
| 1918 | if (args.hasArg(Ids: OPT_profile)) |
| 1919 | doGC = true; |
| 1920 | // Handle /opt. |
| 1921 | std::optional<ICFLevel> icfLevel; |
| 1922 | if (args.hasArg(Ids: OPT_profile)) |
| 1923 | icfLevel = ICFLevel::None; |
| 1924 | unsigned tailMerge = 1; |
| 1925 | bool ltoDebugPM = false; |
| 1926 | for (auto *arg : args.filtered(Ids: OPT_opt)) { |
| 1927 | std::string str = StringRef(arg->getValue()).lower(); |
| 1928 | SmallVector<StringRef, 1> vec; |
| 1929 | StringRef(str).split(A&: vec, Separator: ','); |
| 1930 | for (StringRef s : vec) { |
| 1931 | if (s == "ref" ) { |
| 1932 | doGC = true; |
| 1933 | } else if (s == "noref" ) { |
| 1934 | doGC = false; |
| 1935 | } else if (s == "icf" || s.starts_with(Prefix: "icf=" )) { |
| 1936 | icfLevel = ICFLevel::All; |
| 1937 | } else if (s == "safeicf" ) { |
| 1938 | icfLevel = ICFLevel::Safe; |
| 1939 | } else if (s == "noicf" ) { |
| 1940 | icfLevel = ICFLevel::None; |
| 1941 | } else if (s == "lldtailmerge" ) { |
| 1942 | tailMerge = 2; |
| 1943 | } else if (s == "nolldtailmerge" ) { |
| 1944 | tailMerge = 0; |
| 1945 | } else if (s == "ltodebugpassmanager" ) { |
| 1946 | ltoDebugPM = true; |
| 1947 | } else if (s == "noltodebugpassmanager" ) { |
| 1948 | ltoDebugPM = false; |
| 1949 | } else if (s.consume_front(Prefix: "lldlto=" )) { |
| 1950 | if (s.getAsInteger(Radix: 10, Result&: config->ltoo) || config->ltoo > 3) |
| 1951 | Err(ctx) << "/opt:lldlto: invalid optimization level: " << s; |
| 1952 | } else if (s.consume_front(Prefix: "lldltocgo=" )) { |
| 1953 | config->ltoCgo.emplace(); |
| 1954 | if (s.getAsInteger(Radix: 10, Result&: *config->ltoCgo) || *config->ltoCgo > 3) |
| 1955 | Err(ctx) << "/opt:lldltocgo: invalid codegen optimization level: " |
| 1956 | << s; |
| 1957 | } else if (s.consume_front(Prefix: "lldltojobs=" )) { |
| 1958 | if (!get_threadpool_strategy(Num: s)) |
| 1959 | Err(ctx) << "/opt:lldltojobs: invalid job count: " << s; |
| 1960 | config->thinLTOJobs = s.str(); |
| 1961 | } else if (s.consume_front(Prefix: "lldltopartitions=" )) { |
| 1962 | if (s.getAsInteger(Radix: 10, Result&: config->ltoPartitions) || |
| 1963 | config->ltoPartitions == 0) |
| 1964 | Err(ctx) << "/opt:lldltopartitions: invalid partition count: " << s; |
| 1965 | } else if (s != "lbr" && s != "nolbr" ) |
| 1966 | Err(ctx) << "/opt: unknown option: " << s; |
| 1967 | } |
| 1968 | } |
| 1969 | |
| 1970 | if (!icfLevel) |
| 1971 | icfLevel = doGC ? ICFLevel::All : ICFLevel::None; |
| 1972 | config->doGC = doGC; |
| 1973 | config->doICF = *icfLevel; |
| 1974 | config->tailMerge = |
| 1975 | (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; |
| 1976 | config->ltoDebugPassManager = ltoDebugPM; |
| 1977 | |
| 1978 | // Handle /lldsavetemps |
| 1979 | if (args.hasArg(Ids: OPT_lldsavetemps)) { |
| 1980 | config->saveTempsArgs.insert_range(R: lldsaveTempsValues); |
| 1981 | } else { |
| 1982 | for (auto *arg : args.filtered(Ids: OPT_lldsavetemps_colon)) { |
| 1983 | StringRef s = arg->getValue(); |
| 1984 | if (llvm::is_contained(Range: lldsaveTempsValues, Element: s)) |
| 1985 | config->saveTempsArgs.insert(V: s); |
| 1986 | else |
| 1987 | Err(ctx) << "unknown /lldsavetemps value: " << s; |
| 1988 | } |
| 1989 | } |
| 1990 | |
| 1991 | // Handle /lldemit |
| 1992 | if (auto *arg = args.getLastArg(Ids: OPT_lldemit)) { |
| 1993 | StringRef s = arg->getValue(); |
| 1994 | if (s == "obj" ) |
| 1995 | config->emit = EmitKind::Obj; |
| 1996 | else if (s == "llvm" ) |
| 1997 | config->emit = EmitKind::LLVM; |
| 1998 | else if (s == "asm" ) |
| 1999 | config->emit = EmitKind::ASM; |
| 2000 | else |
| 2001 | Err(ctx) << "/lldemit: unknown option: " << s; |
| 2002 | } |
| 2003 | |
| 2004 | // Handle /kill-at |
| 2005 | if (args.hasArg(Ids: OPT_kill_at)) |
| 2006 | config->killAt = true; |
| 2007 | |
| 2008 | // Handle /lldltocache |
| 2009 | if (auto *arg = args.getLastArg(Ids: OPT_lldltocache)) |
| 2010 | config->ltoCache = arg->getValue(); |
| 2011 | |
| 2012 | // Handle /lldsavecachepolicy |
| 2013 | if (auto *arg = args.getLastArg(Ids: OPT_lldltocachepolicy)) |
| 2014 | config->ltoCachePolicy = CHECK( |
| 2015 | parseCachePruningPolicy(arg->getValue()), |
| 2016 | Twine("/lldltocachepolicy: invalid cache policy: " ) + arg->getValue()); |
| 2017 | |
| 2018 | // Handle /failifmismatch |
| 2019 | for (auto *arg : args.filtered(Ids: OPT_failifmismatch)) |
| 2020 | checkFailIfMismatch(arg: arg->getValue(), source: nullptr); |
| 2021 | |
| 2022 | // Handle /merge |
| 2023 | for (auto *arg : args.filtered(Ids: OPT_merge)) |
| 2024 | parseMerge(arg->getValue()); |
| 2025 | |
| 2026 | // Add default section merging rules after user rules. User rules take |
| 2027 | // precedence, but we will emit a warning if there is a conflict. |
| 2028 | parseMerge(".idata=.rdata" ); |
| 2029 | parseMerge(".didat=.rdata" ); |
| 2030 | parseMerge(".edata=.rdata" ); |
| 2031 | parseMerge(".xdata=.rdata" ); |
| 2032 | parseMerge(".00cfg=.rdata" ); |
| 2033 | parseMerge(".bss=.data" ); |
| 2034 | |
| 2035 | if (isArm64EC(Machine: config->machine)) |
| 2036 | parseMerge(".wowthk=.text" ); |
| 2037 | |
| 2038 | if (config->mingw) { |
| 2039 | parseMerge(".ctors=.rdata" ); |
| 2040 | parseMerge(".dtors=.rdata" ); |
| 2041 | parseMerge(".CRT=.rdata" ); |
| 2042 | parseMerge(".data_cygwin_nocopy=.data" ); |
| 2043 | } |
| 2044 | |
| 2045 | // Handle /section |
| 2046 | for (auto *arg : args.filtered(Ids: OPT_section)) |
| 2047 | parseSection(arg->getValue()); |
| 2048 | |
| 2049 | // Handle /align |
| 2050 | if (auto *arg = args.getLastArg(Ids: OPT_align)) { |
| 2051 | parseNumbers(arg: arg->getValue(), addr: &config->align); |
| 2052 | if (!isPowerOf2_64(Value: config->align)) |
| 2053 | Err(ctx) << "/align: not a power of two: " << StringRef(arg->getValue()); |
| 2054 | if (!args.hasArg(Ids: OPT_driver)) |
| 2055 | Warn(ctx) << "/align specified without /driver; image may not run" ; |
| 2056 | } |
| 2057 | |
| 2058 | // Handle /aligncomm |
| 2059 | for (auto *arg : args.filtered(Ids: OPT_aligncomm)) |
| 2060 | ctx.symtab.parseAligncomm(arg->getValue()); |
| 2061 | |
| 2062 | // Handle /manifestdependency. |
| 2063 | for (auto *arg : args.filtered(Ids: OPT_manifestdependency)) |
| 2064 | config->manifestDependencies.insert(X: arg->getValue()); |
| 2065 | |
| 2066 | // Handle /manifest and /manifest: |
| 2067 | if (auto *arg = args.getLastArg(Ids: OPT_manifest, Ids: OPT_manifest_colon)) { |
| 2068 | if (arg->getOption().getID() == OPT_manifest) |
| 2069 | config->manifest = Configuration::SideBySide; |
| 2070 | else |
| 2071 | parseManifest(arg: arg->getValue()); |
| 2072 | } |
| 2073 | |
| 2074 | // Handle /manifestuac |
| 2075 | if (auto *arg = args.getLastArg(Ids: OPT_manifestuac)) |
| 2076 | parseManifestUAC(arg: arg->getValue()); |
| 2077 | |
| 2078 | // Handle /manifestfile |
| 2079 | if (auto *arg = args.getLastArg(Ids: OPT_manifestfile)) |
| 2080 | config->manifestFile = arg->getValue(); |
| 2081 | |
| 2082 | // Handle /manifestinput |
| 2083 | for (auto *arg : args.filtered(Ids: OPT_manifestinput)) |
| 2084 | config->manifestInput.push_back(x: arg->getValue()); |
| 2085 | |
| 2086 | if (!config->manifestInput.empty() && |
| 2087 | config->manifest != Configuration::Embed) { |
| 2088 | Fatal(ctx) << "/manifestinput: requires /manifest:embed" ; |
| 2089 | } |
| 2090 | |
| 2091 | // Handle /dwodir |
| 2092 | config->dwoDir = args.getLastArgValue(Id: OPT_dwodir); |
| 2093 | |
| 2094 | config->thinLTOEmitImportsFiles = args.hasArg(Ids: OPT_thinlto_emit_imports_files); |
| 2095 | config->thinLTOIndexOnly = args.hasArg(Ids: OPT_thinlto_index_only) || |
| 2096 | args.hasArg(Ids: OPT_thinlto_index_only_arg); |
| 2097 | config->thinLTOIndexOnlyArg = |
| 2098 | args.getLastArgValue(Id: OPT_thinlto_index_only_arg); |
| 2099 | std::tie(args&: config->thinLTOPrefixReplaceOld, args&: config->thinLTOPrefixReplaceNew, |
| 2100 | args&: config->thinLTOPrefixReplaceNativeObject) = |
| 2101 | getOldNewOptionsExtra(ctx, args, id: OPT_thinlto_prefix_replace); |
| 2102 | config->thinLTOObjectSuffixReplace = |
| 2103 | getOldNewOptions(ctx, args, id: OPT_thinlto_object_suffix_replace); |
| 2104 | config->ltoObjPath = args.getLastArgValue(Id: OPT_lto_obj_path); |
| 2105 | config->ltoCSProfileGenerate = args.hasArg(Ids: OPT_lto_cs_profile_generate); |
| 2106 | config->ltoCSProfileFile = args.getLastArgValue(Id: OPT_lto_cs_profile_file); |
| 2107 | config->ltoSampleProfileName = args.getLastArgValue(Id: OPT_lto_sample_profile); |
| 2108 | // Handle miscellaneous boolean flags. |
| 2109 | config->ltoPGOWarnMismatch = args.hasFlag(Pos: OPT_lto_pgo_warn_mismatch, |
| 2110 | Neg: OPT_lto_pgo_warn_mismatch_no, Default: true); |
| 2111 | config->allowBind = args.hasFlag(Pos: OPT_allowbind, Neg: OPT_allowbind_no, Default: true); |
| 2112 | config->allowIsolation = |
| 2113 | args.hasFlag(Pos: OPT_allowisolation, Neg: OPT_allowisolation_no, Default: true); |
| 2114 | config->incremental = |
| 2115 | args.hasFlag(Pos: OPT_incremental, Neg: OPT_incremental_no, |
| 2116 | Default: !config->doGC && config->doICF == ICFLevel::None && |
| 2117 | !args.hasArg(Ids: OPT_order) && !args.hasArg(Ids: OPT_profile)); |
| 2118 | config->integrityCheck = |
| 2119 | args.hasFlag(Pos: OPT_integritycheck, Neg: OPT_integritycheck_no, Default: false); |
| 2120 | config->cetCompat = args.hasFlag(Pos: OPT_cetcompat, Neg: OPT_cetcompat_no, Default: false); |
| 2121 | config->nxCompat = args.hasFlag(Pos: OPT_nxcompat, Neg: OPT_nxcompat_no, Default: true); |
| 2122 | for (auto *arg : args.filtered(Ids: OPT_swaprun)) |
| 2123 | parseSwaprun(arg: arg->getValue()); |
| 2124 | config->terminalServerAware = |
| 2125 | !config->dll && args.hasFlag(Pos: OPT_tsaware, Neg: OPT_tsaware_no, Default: true); |
| 2126 | config->autoImport = |
| 2127 | args.hasFlag(Pos: OPT_auto_import, Neg: OPT_auto_import_no, Default: config->mingw); |
| 2128 | config->pseudoRelocs = args.hasFlag( |
| 2129 | Pos: OPT_runtime_pseudo_reloc, Neg: OPT_runtime_pseudo_reloc_no, Default: config->mingw); |
| 2130 | config->callGraphProfileSort = args.hasFlag( |
| 2131 | Pos: OPT_call_graph_profile_sort, Neg: OPT_call_graph_profile_sort_no, Default: true); |
| 2132 | config->stdcallFixup = |
| 2133 | args.hasFlag(Pos: OPT_stdcall_fixup, Neg: OPT_stdcall_fixup_no, Default: config->mingw); |
| 2134 | config->warnStdcallFixup = !args.hasArg(Ids: OPT_stdcall_fixup); |
| 2135 | config->allowDuplicateWeak = |
| 2136 | args.hasFlag(Pos: OPT_lld_allow_duplicate_weak, |
| 2137 | Neg: OPT_lld_allow_duplicate_weak_no, Default: config->mingw); |
| 2138 | |
| 2139 | if (args.hasFlag(Pos: OPT_inferasanlibs, Neg: OPT_inferasanlibs_no, Default: false)) |
| 2140 | Warn(ctx) << "ignoring '/inferasanlibs', this flag is not supported" ; |
| 2141 | |
| 2142 | if (config->incremental && args.hasArg(Ids: OPT_profile)) { |
| 2143 | Warn(ctx) << "ignoring '/incremental' due to '/profile' specification" ; |
| 2144 | config->incremental = false; |
| 2145 | } |
| 2146 | |
| 2147 | if (config->incremental && args.hasArg(Ids: OPT_order)) { |
| 2148 | Warn(ctx) << "ignoring '/incremental' due to '/order' specification" ; |
| 2149 | config->incremental = false; |
| 2150 | } |
| 2151 | |
| 2152 | if (config->incremental && config->doGC) { |
| 2153 | Warn(ctx) << "ignoring '/incremental' because REF is enabled; use " |
| 2154 | "'/opt:noref' to " |
| 2155 | "disable" ; |
| 2156 | config->incremental = false; |
| 2157 | } |
| 2158 | |
| 2159 | if (config->incremental && config->doICF != ICFLevel::None) { |
| 2160 | Warn(ctx) << "ignoring '/incremental' because ICF is enabled; use " |
| 2161 | "'/opt:noicf' to " |
| 2162 | "disable" ; |
| 2163 | config->incremental = false; |
| 2164 | } |
| 2165 | |
| 2166 | if (errCount(ctx)) |
| 2167 | return; |
| 2168 | |
| 2169 | std::set<sys::fs::UniqueID> wholeArchives; |
| 2170 | for (auto *arg : args.filtered(Ids: OPT_wholearchive_file)) |
| 2171 | if (std::optional<StringRef> path = findFile(filename: arg->getValue())) |
| 2172 | if (std::optional<sys::fs::UniqueID> id = getUniqueID(path: *path)) |
| 2173 | wholeArchives.insert(x: *id); |
| 2174 | |
| 2175 | // A predicate returning true if a given path is an argument for |
| 2176 | // /wholearchive:, or /wholearchive is enabled globally. |
| 2177 | // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" |
| 2178 | // needs to be handled as "/wholearchive:foo.obj foo.obj". |
| 2179 | auto isWholeArchive = [&](StringRef path) -> bool { |
| 2180 | if (args.hasArg(Ids: OPT_wholearchive_flag)) |
| 2181 | return true; |
| 2182 | if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) |
| 2183 | return wholeArchives.count(x: *id); |
| 2184 | return false; |
| 2185 | }; |
| 2186 | |
| 2187 | // Create a list of input files. These can be given as OPT_INPUT options |
| 2188 | // and OPT_wholearchive_file options, and we also need to track OPT_start_lib |
| 2189 | // and OPT_end_lib. |
| 2190 | { |
| 2191 | llvm::TimeTraceScope timeScope2("Parse & queue inputs" ); |
| 2192 | bool inLib = false; |
| 2193 | for (auto *arg : args) { |
| 2194 | switch (arg->getOption().getID()) { |
| 2195 | case OPT_end_lib: |
| 2196 | if (!inLib) |
| 2197 | Err(ctx) << "stray " << arg->getSpelling(); |
| 2198 | inLib = false; |
| 2199 | break; |
| 2200 | case OPT_start_lib: |
| 2201 | if (inLib) |
| 2202 | Err(ctx) << "nested " << arg->getSpelling(); |
| 2203 | inLib = true; |
| 2204 | break; |
| 2205 | case OPT_wholearchive_file: |
| 2206 | if (std::optional<StringRef> path = findFileIfNew(filename: arg->getValue())) |
| 2207 | enqueuePath(path: *path, wholeArchive: true, lazy: inLib); |
| 2208 | break; |
| 2209 | case OPT_INPUT: |
| 2210 | if (std::optional<StringRef> path = findFileIfNew(filename: arg->getValue())) |
| 2211 | enqueuePath(path: *path, wholeArchive: isWholeArchive(*path), lazy: inLib); |
| 2212 | break; |
| 2213 | default: |
| 2214 | // Ignore other options. |
| 2215 | break; |
| 2216 | } |
| 2217 | } |
| 2218 | } |
| 2219 | |
| 2220 | // Read all input files given via the command line. |
| 2221 | run(); |
| 2222 | if (errorCount()) |
| 2223 | return; |
| 2224 | |
| 2225 | // We should have inferred a machine type by now from the input files, but if |
| 2226 | // not we assume x64. |
| 2227 | if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { |
| 2228 | Warn(ctx) << "/machine is not specified. x64 is assumed" ; |
| 2229 | setMachine(AMD64); |
| 2230 | } |
| 2231 | config->wordsize = config->is64() ? 8 : 4; |
| 2232 | |
| 2233 | if (config->printSearchPaths) { |
| 2234 | SmallString<256> buffer; |
| 2235 | raw_svector_ostream stream(buffer); |
| 2236 | stream << "Library search paths:\n" ; |
| 2237 | |
| 2238 | for (StringRef path : searchPaths) { |
| 2239 | if (path == "" ) |
| 2240 | path = "(cwd)" ; |
| 2241 | stream << " " << path << "\n" ; |
| 2242 | } |
| 2243 | |
| 2244 | Msg(ctx) << buffer; |
| 2245 | } |
| 2246 | |
| 2247 | // Process files specified as /defaultlib. These must be processed after |
| 2248 | // addWinSysRootLibSearchPaths(), which is why they are in a separate loop. |
| 2249 | for (auto *arg : args.filtered(Ids: OPT_defaultlib)) |
| 2250 | if (std::optional<StringRef> path = findLibIfNew(filename: arg->getValue())) |
| 2251 | enqueuePath(path: *path, wholeArchive: false, lazy: false); |
| 2252 | run(); |
| 2253 | if (errorCount()) |
| 2254 | return; |
| 2255 | |
| 2256 | // Handle /RELEASE |
| 2257 | if (args.hasArg(Ids: OPT_release)) |
| 2258 | config->writeCheckSum = true; |
| 2259 | |
| 2260 | // Handle /safeseh, x86 only, on by default, except for mingw. |
| 2261 | if (config->machine == I386) { |
| 2262 | config->safeSEH = args.hasFlag(Pos: OPT_safeseh, Neg: OPT_safeseh_no, Default: !config->mingw); |
| 2263 | config->noSEH = args.hasArg(Ids: OPT_noseh); |
| 2264 | } |
| 2265 | |
| 2266 | // Handle /stub |
| 2267 | if (auto *arg = args.getLastArg(Ids: OPT_stub)) |
| 2268 | parseDosStub(path: arg->getValue()); |
| 2269 | |
| 2270 | // Handle /functionpadmin |
| 2271 | for (auto *arg : args.filtered(Ids: OPT_functionpadmin, Ids: OPT_functionpadmin_opt)) |
| 2272 | parseFunctionPadMin(a: arg); |
| 2273 | |
| 2274 | // Handle /dependentloadflag |
| 2275 | for (auto *arg : |
| 2276 | args.filtered(Ids: OPT_dependentloadflag, Ids: OPT_dependentloadflag_opt)) |
| 2277 | parseDependentLoadFlags(a: arg); |
| 2278 | |
| 2279 | if (tar) { |
| 2280 | llvm::TimeTraceScope timeScope("Reproducer: response file" ); |
| 2281 | tar->append( |
| 2282 | Path: "response.txt" , |
| 2283 | Data: createResponseFile(args, searchPaths: ArrayRef<StringRef>(searchPaths).slice(N: 1))); |
| 2284 | } |
| 2285 | |
| 2286 | // Handle /largeaddressaware |
| 2287 | config->largeAddressAware = args.hasFlag( |
| 2288 | Pos: OPT_largeaddressaware, Neg: OPT_largeaddressaware_no, Default: config->is64()); |
| 2289 | |
| 2290 | // Handle /highentropyva |
| 2291 | config->highEntropyVA = |
| 2292 | config->is64() && |
| 2293 | args.hasFlag(Pos: OPT_highentropyva, Neg: OPT_highentropyva_no, Default: true); |
| 2294 | |
| 2295 | if (!config->dynamicBase && |
| 2296 | (config->machine == ARMNT || isAnyArm64(Machine: config->machine))) |
| 2297 | Err(ctx) << "/dynamicbase:no is not compatible with " |
| 2298 | << machineToStr(MT: config->machine); |
| 2299 | |
| 2300 | // Handle /export |
| 2301 | { |
| 2302 | llvm::TimeTraceScope timeScope("Parse /export" ); |
| 2303 | for (auto *arg : args.filtered(Ids: OPT_export)) { |
| 2304 | Export e = parseExport(arg: arg->getValue()); |
| 2305 | if (config->machine == I386) { |
| 2306 | if (!isDecorated(sym: e.name)) |
| 2307 | e.name = saver().save(S: "_" + e.name); |
| 2308 | if (!e.extName.empty() && !isDecorated(sym: e.extName)) |
| 2309 | e.extName = saver().save(S: "_" + e.extName); |
| 2310 | } |
| 2311 | ctx.symtab.exports.push_back(x: e); |
| 2312 | } |
| 2313 | } |
| 2314 | |
| 2315 | // Handle /def |
| 2316 | if (auto *arg = args.getLastArg(Ids: OPT_deffile)) { |
| 2317 | // parseModuleDefs mutates Config object. |
| 2318 | ctx.symtab.parseModuleDefs(path: arg->getValue()); |
| 2319 | if (ctx.config.machine == ARM64X) { |
| 2320 | // MSVC ignores the /defArm64Native argument on non-ARM64X targets. |
| 2321 | // It is also ignored if the /def option is not specified. |
| 2322 | if (auto *arg = args.getLastArg(Ids: OPT_defarm64native)) |
| 2323 | ctx.hybridSymtab->parseModuleDefs(path: arg->getValue()); |
| 2324 | } |
| 2325 | } |
| 2326 | |
| 2327 | // Handle generation of import library from a def file. |
| 2328 | if (!args.hasArg(Ids: OPT_INPUT, Ids: OPT_wholearchive_file)) { |
| 2329 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { symtab.fixupExports(); }); |
| 2330 | if (!config->noimplib) |
| 2331 | createImportLibrary(/*asLib=*/true); |
| 2332 | return; |
| 2333 | } |
| 2334 | |
| 2335 | // Windows specific -- if no /subsystem is given, we need to infer |
| 2336 | // that from entry point name. Must happen before /entry handling, |
| 2337 | // and after the early return when just writing an import library. |
| 2338 | if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { |
| 2339 | llvm::TimeTraceScope timeScope("Infer subsystem" ); |
| 2340 | config->subsystem = ctx.symtab.inferSubsystem(); |
| 2341 | if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) |
| 2342 | Fatal(ctx) << "subsystem must be defined" ; |
| 2343 | } |
| 2344 | |
| 2345 | // Handle /entry and /dll |
| 2346 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
| 2347 | llvm::TimeTraceScope timeScope("Entry point" ); |
| 2348 | if (auto *arg = args.getLastArg(Ids: OPT_entry)) { |
| 2349 | if (!arg->getValue()[0]) |
| 2350 | Fatal(ctx) << "missing entry point symbol name" ; |
| 2351 | symtab.entry = symtab.addGCRoot(sym: symtab.mangle(sym: arg->getValue()), aliasEC: true); |
| 2352 | } else if (!symtab.entry && !config->noEntry) { |
| 2353 | if (args.hasArg(Ids: OPT_dll)) { |
| 2354 | StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" |
| 2355 | : "_DllMainCRTStartup" ; |
| 2356 | symtab.entry = symtab.addGCRoot(sym: s, aliasEC: true); |
| 2357 | } else if (config->driverWdm) { |
| 2358 | // /driver:wdm implies /entry:_NtProcessStartup |
| 2359 | symtab.entry = |
| 2360 | symtab.addGCRoot(sym: symtab.mangle(sym: "_NtProcessStartup" ), aliasEC: true); |
| 2361 | } else { |
| 2362 | // Windows specific -- If entry point name is not given, we need to |
| 2363 | // infer that from user-defined entry name. |
| 2364 | StringRef s = symtab.findDefaultEntry(); |
| 2365 | if (s.empty()) |
| 2366 | Fatal(ctx) << "entry point must be defined" ; |
| 2367 | symtab.entry = symtab.addGCRoot(sym: s, aliasEC: true); |
| 2368 | Log(ctx) << "Entry name inferred: " << s; |
| 2369 | } |
| 2370 | } |
| 2371 | }); |
| 2372 | |
| 2373 | // Handle /delayload |
| 2374 | { |
| 2375 | llvm::TimeTraceScope timeScope("Delay load" ); |
| 2376 | for (auto *arg : args.filtered(Ids: OPT_delayload)) { |
| 2377 | config->delayLoads.insert(x: StringRef(arg->getValue()).lower()); |
| 2378 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
| 2379 | if (symtab.machine == I386) { |
| 2380 | symtab.delayLoadHelper = symtab.addGCRoot(sym: "___delayLoadHelper2@8" ); |
| 2381 | } else { |
| 2382 | symtab.delayLoadHelper = symtab.addGCRoot(sym: "__delayLoadHelper2" , aliasEC: true); |
| 2383 | } |
| 2384 | }); |
| 2385 | } |
| 2386 | } |
| 2387 | |
| 2388 | // Set default image name if neither /out or /def set it. |
| 2389 | if (config->outputFile.empty()) { |
| 2390 | config->outputFile = getOutputPath( |
| 2391 | path: (*args.filtered(Ids: OPT_INPUT, Ids: OPT_wholearchive_file).begin())->getValue(), |
| 2392 | isDll: config->dll, isDriver: config->driver); |
| 2393 | } |
| 2394 | |
| 2395 | // Fail early if an output file is not writable. |
| 2396 | if (auto e = tryCreateFile(path: config->outputFile)) { |
| 2397 | Err(ctx) << "cannot open output file " << config->outputFile << ": " |
| 2398 | << e.message(); |
| 2399 | return; |
| 2400 | } |
| 2401 | |
| 2402 | config->lldmapFile = getMapFile(args, os: OPT_lldmap, osFile: OPT_lldmap_file); |
| 2403 | config->mapFile = getMapFile(args, os: OPT_map, osFile: OPT_map_file); |
| 2404 | |
| 2405 | if (config->mapFile != "" && args.hasArg(Ids: OPT_map_info)) { |
| 2406 | for (auto *arg : args.filtered(Ids: OPT_map_info)) { |
| 2407 | std::string s = StringRef(arg->getValue()).lower(); |
| 2408 | if (s == "exports" ) |
| 2409 | config->mapInfo = true; |
| 2410 | else |
| 2411 | Err(ctx) << "unknown option: /mapinfo:" << s; |
| 2412 | } |
| 2413 | } |
| 2414 | |
| 2415 | if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { |
| 2416 | Warn(ctx) << "/lldmap and /map have the same output file '" |
| 2417 | << config->mapFile << "'.\n>>> ignoring /lldmap" ; |
| 2418 | config->lldmapFile.clear(); |
| 2419 | } |
| 2420 | |
| 2421 | // If should create PDB, use the hash of PDB content for build id. Otherwise, |
| 2422 | // generate using the hash of executable content. |
| 2423 | if (args.hasFlag(Pos: OPT_build_id, Neg: OPT_build_id_no, Default: false)) |
| 2424 | config->buildIDHash = BuildIDHash::Binary; |
| 2425 | |
| 2426 | if (shouldCreatePDB) { |
| 2427 | // Put the PDB next to the image if no /pdb flag was passed. |
| 2428 | if (config->pdbPath.empty()) { |
| 2429 | config->pdbPath = config->outputFile; |
| 2430 | sys::path::replace_extension(path&: config->pdbPath, extension: ".pdb" ); |
| 2431 | } |
| 2432 | |
| 2433 | // The embedded PDB path should be the absolute path to the PDB if no |
| 2434 | // /pdbaltpath flag was passed. |
| 2435 | if (config->pdbAltPath.empty()) { |
| 2436 | config->pdbAltPath = config->pdbPath; |
| 2437 | |
| 2438 | // It's important to make the path absolute and remove dots. This path |
| 2439 | // will eventually be written into the PE header, and certain Microsoft |
| 2440 | // tools won't work correctly if these assumptions are not held. |
| 2441 | sys::fs::make_absolute(path&: config->pdbAltPath); |
| 2442 | sys::path::remove_dots(path&: config->pdbAltPath); |
| 2443 | } else { |
| 2444 | // Don't do this earlier, so that ctx.OutputFile is ready. |
| 2445 | parsePDBAltPath(); |
| 2446 | } |
| 2447 | config->buildIDHash = BuildIDHash::PDB; |
| 2448 | } |
| 2449 | |
| 2450 | // Set default image base if /base is not given. |
| 2451 | if (config->imageBase == uint64_t(-1)) |
| 2452 | config->imageBase = getDefaultImageBase(); |
| 2453 | |
| 2454 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
| 2455 | symtab.addSynthetic(n: symtab.mangle(sym: "__ImageBase" ), c: nullptr); |
| 2456 | if (symtab.machine == I386) { |
| 2457 | symtab.addAbsolute(n: "___safe_se_handler_table" , va: 0); |
| 2458 | symtab.addAbsolute(n: "___safe_se_handler_count" , va: 0); |
| 2459 | } |
| 2460 | |
| 2461 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_fids_count" ), va: 0); |
| 2462 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_fids_table" ), va: 0); |
| 2463 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_flags" ), va: 0); |
| 2464 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_iat_count" ), va: 0); |
| 2465 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_iat_table" ), va: 0); |
| 2466 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_longjmp_count" ), va: 0); |
| 2467 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_longjmp_table" ), va: 0); |
| 2468 | // Needed for MSVC 2017 15.5 CRT. |
| 2469 | symtab.addAbsolute(n: symtab.mangle(sym: "__enclave_config" ), va: 0); |
| 2470 | // Needed for MSVC 2019 16.8 CRT. |
| 2471 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_eh_cont_count" ), va: 0); |
| 2472 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_eh_cont_table" ), va: 0); |
| 2473 | |
| 2474 | if (symtab.isEC()) { |
| 2475 | symtab.addAbsolute(n: "__arm64x_extra_rfe_table" , va: 0); |
| 2476 | symtab.addAbsolute(n: "__arm64x_extra_rfe_table_size" , va: 0); |
| 2477 | symtab.addAbsolute(n: "__arm64x_redirection_metadata" , va: 0); |
| 2478 | symtab.addAbsolute(n: "__arm64x_redirection_metadata_count" , va: 0); |
| 2479 | symtab.addAbsolute(n: "__hybrid_auxiliary_delayload_iat_copy" , va: 0); |
| 2480 | symtab.addAbsolute(n: "__hybrid_auxiliary_delayload_iat" , va: 0); |
| 2481 | symtab.addAbsolute(n: "__hybrid_auxiliary_iat" , va: 0); |
| 2482 | symtab.addAbsolute(n: "__hybrid_auxiliary_iat_copy" , va: 0); |
| 2483 | symtab.addAbsolute(n: "__hybrid_code_map" , va: 0); |
| 2484 | symtab.addAbsolute(n: "__hybrid_code_map_count" , va: 0); |
| 2485 | symtab.addAbsolute(n: "__hybrid_image_info_bitfield" , va: 0); |
| 2486 | symtab.addAbsolute(n: "__x64_code_ranges_to_entry_points" , va: 0); |
| 2487 | symtab.addAbsolute(n: "__x64_code_ranges_to_entry_points_count" , va: 0); |
| 2488 | symtab.addSynthetic(n: "__guard_check_icall_a64n_fptr" , c: nullptr); |
| 2489 | symtab.addSynthetic(n: "__arm64x_native_entrypoint" , c: nullptr); |
| 2490 | } |
| 2491 | |
| 2492 | if (config->pseudoRelocs) { |
| 2493 | symtab.addAbsolute(n: symtab.mangle(sym: "__RUNTIME_PSEUDO_RELOC_LIST__" ), va: 0); |
| 2494 | symtab.addAbsolute(n: symtab.mangle(sym: "__RUNTIME_PSEUDO_RELOC_LIST_END__" ), va: 0); |
| 2495 | } |
| 2496 | if (config->mingw) { |
| 2497 | symtab.addAbsolute(n: symtab.mangle(sym: "__CTOR_LIST__" ), va: 0); |
| 2498 | symtab.addAbsolute(n: symtab.mangle(sym: "__DTOR_LIST__" ), va: 0); |
| 2499 | symtab.addAbsolute(n: "__data_start__" , va: 0); |
| 2500 | symtab.addAbsolute(n: "__data_end__" , va: 0); |
| 2501 | symtab.addAbsolute(n: "__bss_start__" , va: 0); |
| 2502 | symtab.addAbsolute(n: "__bss_end__" , va: 0); |
| 2503 | } |
| 2504 | if (config->debug || config->buildIDHash != BuildIDHash::None) |
| 2505 | if (symtab.findUnderscore(name: "__buildid" )) |
| 2506 | symtab.addUndefined(name: symtab.mangle(sym: "__buildid" )); |
| 2507 | }); |
| 2508 | |
| 2509 | // This code may add new undefined symbols to the link, which may enqueue more |
| 2510 | // symbol resolution tasks, so we need to continue executing tasks until we |
| 2511 | // converge. |
| 2512 | { |
| 2513 | llvm::TimeTraceScope timeScope("Add unresolved symbols" ); |
| 2514 | do { |
| 2515 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
| 2516 | // Windows specific -- if entry point is not found, |
| 2517 | // search for its mangled names. |
| 2518 | if (symtab.entry) |
| 2519 | symtab.mangleMaybe(s: symtab.entry); |
| 2520 | |
| 2521 | // Windows specific -- Make sure we resolve all dllexported symbols. |
| 2522 | for (Export &e : symtab.exports) { |
| 2523 | if (!e.forwardTo.empty()) |
| 2524 | continue; |
| 2525 | e.sym = symtab.addGCRoot(sym: e.name, aliasEC: !e.data); |
| 2526 | if (e.source != ExportSource::Directives) |
| 2527 | e.symbolName = symtab.mangleMaybe(s: e.sym); |
| 2528 | } |
| 2529 | |
| 2530 | // Add weak aliases. Weak aliases is a mechanism to give remaining |
| 2531 | // undefined symbols final chance to be resolved successfully. |
| 2532 | for (auto pair : symtab.alternateNames) { |
| 2533 | StringRef from = pair.first; |
| 2534 | StringRef to = pair.second; |
| 2535 | Symbol *sym = symtab.find(name: from); |
| 2536 | if (!sym) |
| 2537 | continue; |
| 2538 | if (auto *u = dyn_cast<Undefined>(Val: sym)) { |
| 2539 | if (u->weakAlias) { |
| 2540 | // On ARM64EC, anti-dependency aliases are treated as undefined |
| 2541 | // symbols unless a demangled symbol aliases a defined one, which |
| 2542 | // is part of the implementation. |
| 2543 | if (!symtab.isEC() || !u->isAntiDep) |
| 2544 | continue; |
| 2545 | if (!isa<Undefined>(Val: u->weakAlias) && |
| 2546 | !isArm64ECMangledFunctionName(Name: u->getName())) |
| 2547 | continue; |
| 2548 | } |
| 2549 | u->setWeakAlias(sym: symtab.addUndefined(name: to)); |
| 2550 | } |
| 2551 | } |
| 2552 | }); |
| 2553 | |
| 2554 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
| 2555 | // If any inputs are bitcode files, the LTO code generator may create |
| 2556 | // references to library functions that are not explicit in the bitcode |
| 2557 | // file's symbol table. If any of those library functions are defined in |
| 2558 | // a bitcode file in an archive member, we need to arrange to use LTO to |
| 2559 | // compile those archive members by adding them to the link beforehand. |
| 2560 | if (!symtab.bitcodeFileInstances.empty()) { |
| 2561 | llvm::Triple TT( |
| 2562 | symtab.bitcodeFileInstances.front()->obj->getTargetTriple()); |
| 2563 | for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT)) |
| 2564 | symtab.addLibcall(name: s); |
| 2565 | } |
| 2566 | |
| 2567 | // Windows specific -- if __load_config_used can be resolved, resolve |
| 2568 | // it. |
| 2569 | if (symtab.findUnderscore(name: "_load_config_used" )) |
| 2570 | symtab.addGCRoot(sym: symtab.mangle(sym: "_load_config_used" )); |
| 2571 | |
| 2572 | if (args.hasArg(Ids: OPT_include_optional)) { |
| 2573 | // Handle /includeoptional |
| 2574 | for (auto *arg : args.filtered(Ids: OPT_include_optional)) |
| 2575 | if (isa_and_nonnull<LazyArchive>(Val: symtab.find(name: arg->getValue()))) |
| 2576 | symtab.addGCRoot(sym: arg->getValue()); |
| 2577 | } |
| 2578 | }); |
| 2579 | } while (run()); |
| 2580 | } |
| 2581 | |
| 2582 | // Handle /includeglob |
| 2583 | for (StringRef pat : args::getStrings(args, id: OPT_incl_glob)) |
| 2584 | ctx.forEachActiveSymtab( |
| 2585 | f: [&](SymbolTable &symtab) { symtab.addUndefinedGlob(arg: pat); }); |
| 2586 | |
| 2587 | // Create wrapped symbols for -wrap option. |
| 2588 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
| 2589 | addWrappedSymbols(symtab, args); |
| 2590 | // Load more object files that might be needed for wrapped symbols. |
| 2591 | if (!symtab.wrapped.empty()) |
| 2592 | while (run()) |
| 2593 | ; |
| 2594 | }); |
| 2595 | |
| 2596 | if (config->autoImport || config->stdcallFixup) { |
| 2597 | // MinGW specific. |
| 2598 | // Load any further object files that might be needed for doing automatic |
| 2599 | // imports, and do stdcall fixups. |
| 2600 | // |
| 2601 | // For cases with no automatically imported symbols, this iterates once |
| 2602 | // over the symbol table and doesn't do anything. |
| 2603 | // |
| 2604 | // For the normal case with a few automatically imported symbols, this |
| 2605 | // should only need to be run once, since each new object file imported |
| 2606 | // is an import library and wouldn't add any new undefined references, |
| 2607 | // but there's nothing stopping the __imp_ symbols from coming from a |
| 2608 | // normal object file as well (although that won't be used for the |
| 2609 | // actual autoimport later on). If this pass adds new undefined references, |
| 2610 | // we won't iterate further to resolve them. |
| 2611 | // |
| 2612 | // If stdcall fixups only are needed for loading import entries from |
| 2613 | // a DLL without import library, this also just needs running once. |
| 2614 | // If it ends up pulling in more object files from static libraries, |
| 2615 | // (and maybe doing more stdcall fixups along the way), this would need |
| 2616 | // to loop these two calls. |
| 2617 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { symtab.loadMinGWSymbols(); }); |
| 2618 | run(); |
| 2619 | } |
| 2620 | |
| 2621 | // At this point, we should not have any symbols that cannot be resolved. |
| 2622 | // If we are going to do codegen for link-time optimization, check for |
| 2623 | // unresolvable symbols first, so we don't spend time generating code that |
| 2624 | // will fail to link anyway. |
| 2625 | if (!config->forceUnresolved) |
| 2626 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
| 2627 | if (!symtab.bitcodeFileInstances.empty()) |
| 2628 | symtab.reportUnresolvable(); |
| 2629 | }); |
| 2630 | if (errorCount()) |
| 2631 | return; |
| 2632 | |
| 2633 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
| 2634 | symtab.hadExplicitExports = !symtab.exports.empty(); |
| 2635 | }); |
| 2636 | if (config->mingw) { |
| 2637 | // In MinGW, all symbols are automatically exported if no symbols |
| 2638 | // are chosen to be exported. |
| 2639 | maybeExportMinGWSymbols(args); |
| 2640 | } |
| 2641 | |
| 2642 | // Do LTO by compiling bitcode input files to a set of native COFF files then |
| 2643 | // link those files (unless -thinlto-index-only was given, in which case we |
| 2644 | // resolve symbols and write indices, but don't generate native code or link). |
| 2645 | ltoCompilationDone = true; |
| 2646 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { symtab.compileBitcodeFiles(); }); |
| 2647 | |
| 2648 | if (Defined *d = |
| 2649 | dyn_cast_or_null<Defined>(Val: ctx.symtab.findUnderscore(name: "_tls_used" ))) |
| 2650 | config->gcroot.push_back(x: d); |
| 2651 | |
| 2652 | // If -thinlto-index-only is given, we should create only "index |
| 2653 | // files" and not object files. Index file creation is already done |
| 2654 | // in addCombinedLTOObject, so we are done if that's the case. |
| 2655 | // Likewise, don't emit object files for other /lldemit options. |
| 2656 | if (config->emit != EmitKind::Obj || config->thinLTOIndexOnly) |
| 2657 | return; |
| 2658 | |
| 2659 | // If we generated native object files from bitcode files, this resolves |
| 2660 | // references to the symbols we use from them. |
| 2661 | run(); |
| 2662 | |
| 2663 | // Apply symbol renames for -wrap. |
| 2664 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
| 2665 | if (!symtab.wrapped.empty()) |
| 2666 | wrapSymbols(symtab); |
| 2667 | }); |
| 2668 | |
| 2669 | if (isArm64EC(Machine: config->machine)) |
| 2670 | createECExportThunks(); |
| 2671 | |
| 2672 | // Resolve remaining undefined symbols and warn about imported locals. |
| 2673 | ctx.forEachSymtab( |
| 2674 | f: [&](SymbolTable &symtab) { symtab.resolveRemainingUndefines(); }); |
| 2675 | |
| 2676 | if (errorCount()) |
| 2677 | return; |
| 2678 | |
| 2679 | if (config->mingw) { |
| 2680 | // Make sure the crtend.o object is the last object file. This object |
| 2681 | // file can contain terminating section chunks that need to be placed |
| 2682 | // last. GNU ld processes files and static libraries explicitly in the |
| 2683 | // order provided on the command line, while lld will pull in needed |
| 2684 | // files from static libraries only after the last object file on the |
| 2685 | // command line. |
| 2686 | for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); |
| 2687 | i != e; i++) { |
| 2688 | ObjFile *file = *i; |
| 2689 | if (isCrtend(s: file->getName())) { |
| 2690 | ctx.objFileInstances.erase(position: i); |
| 2691 | ctx.objFileInstances.push_back(x: file); |
| 2692 | break; |
| 2693 | } |
| 2694 | } |
| 2695 | } |
| 2696 | |
| 2697 | // Windows specific -- when we are creating a .dll file, we also |
| 2698 | // need to create a .lib file. In MinGW mode, we only do that when the |
| 2699 | // -implib option is given explicitly, for compatibility with GNU ld. |
| 2700 | if (config->dll || !ctx.symtab.exports.empty() || |
| 2701 | (ctx.config.machine == ARM64X && !ctx.hybridSymtab->exports.empty())) { |
| 2702 | llvm::TimeTraceScope timeScope("Create .lib exports" ); |
| 2703 | ctx.forEachActiveSymtab(f: [](SymbolTable &symtab) { symtab.fixupExports(); }); |
| 2704 | if (!config->noimplib && (!config->mingw || !config->implib.empty())) |
| 2705 | createImportLibrary(/*asLib=*/false); |
| 2706 | ctx.forEachActiveSymtab( |
| 2707 | f: [](SymbolTable &symtab) { symtab.assignExportOrdinals(); }); |
| 2708 | } |
| 2709 | |
| 2710 | // Handle /output-def (MinGW specific). |
| 2711 | if (auto *arg = args.getLastArg(Ids: OPT_output_def)) |
| 2712 | writeDefFile(ctx, name: arg->getValue(), exports: ctx.symtab.exports); |
| 2713 | |
| 2714 | // Set extra alignment for .comm symbols |
| 2715 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
| 2716 | for (auto pair : symtab.alignComm) { |
| 2717 | StringRef name = pair.first; |
| 2718 | uint32_t alignment = pair.second; |
| 2719 | |
| 2720 | Symbol *sym = symtab.find(name); |
| 2721 | if (!sym) { |
| 2722 | Warn(ctx) << "/aligncomm symbol " << name << " not found" ; |
| 2723 | continue; |
| 2724 | } |
| 2725 | |
| 2726 | // If the symbol isn't common, it must have been replaced with a regular |
| 2727 | // symbol, which will carry its own alignment. |
| 2728 | auto *dc = dyn_cast<DefinedCommon>(Val: sym); |
| 2729 | if (!dc) |
| 2730 | continue; |
| 2731 | |
| 2732 | CommonChunk *c = dc->getChunk(); |
| 2733 | c->setAlignment(std::max(a: c->getAlignment(), b: alignment)); |
| 2734 | } |
| 2735 | }); |
| 2736 | |
| 2737 | // Windows specific -- Create an embedded or side-by-side manifest. |
| 2738 | // /manifestdependency: enables /manifest unless an explicit /manifest:no is |
| 2739 | // also passed. |
| 2740 | if (config->manifest == Configuration::Embed) |
| 2741 | addBuffer(mb: createManifestRes(), wholeArchive: false, lazy: false); |
| 2742 | else if (config->manifest == Configuration::SideBySide || |
| 2743 | (config->manifest == Configuration::Default && |
| 2744 | !config->manifestDependencies.empty())) |
| 2745 | createSideBySideManifest(); |
| 2746 | |
| 2747 | // Handle /order. We want to do this at this moment because we |
| 2748 | // need a complete list of comdat sections to warn on nonexistent |
| 2749 | // functions. |
| 2750 | if (auto *arg = args.getLastArg(Ids: OPT_order)) { |
| 2751 | if (args.hasArg(Ids: OPT_call_graph_ordering_file)) |
| 2752 | Err(ctx) << "/order and /call-graph-order-file may not be used together" ; |
| 2753 | parseOrderFile(arg: arg->getValue()); |
| 2754 | config->callGraphProfileSort = false; |
| 2755 | } |
| 2756 | |
| 2757 | // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). |
| 2758 | if (config->callGraphProfileSort) { |
| 2759 | llvm::TimeTraceScope timeScope("Call graph" ); |
| 2760 | if (auto *arg = args.getLastArg(Ids: OPT_call_graph_ordering_file)) |
| 2761 | parseCallGraphFile(path: arg->getValue()); |
| 2762 | else |
| 2763 | readCallGraphsFromObjectFiles(ctx); |
| 2764 | } |
| 2765 | |
| 2766 | // Handle /print-symbol-order. |
| 2767 | if (auto *arg = args.getLastArg(Ids: OPT_print_symbol_order)) |
| 2768 | config->printSymbolOrder = arg->getValue(); |
| 2769 | |
| 2770 | if (ctx.symtab.isEC()) |
| 2771 | ctx.symtab.initializeECThunks(); |
| 2772 | ctx.forEachActiveSymtab( |
| 2773 | f: [](SymbolTable &symtab) { symtab.initializeLoadConfig(); }); |
| 2774 | |
| 2775 | // Identify unreferenced COMDAT sections. |
| 2776 | if (config->doGC) { |
| 2777 | if (config->mingw) { |
| 2778 | // markLive doesn't traverse .eh_frame, but the personality function is |
| 2779 | // only reached that way. The proper solution would be to parse and |
| 2780 | // traverse the .eh_frame section, like the ELF linker does. |
| 2781 | // For now, just manually try to retain the known possible personality |
| 2782 | // functions. This doesn't bring in more object files, but only marks |
| 2783 | // functions that already have been included to be retained. |
| 2784 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
| 2785 | for (const char *n : {"__gxx_personality_v0" , "__gcc_personality_v0" , |
| 2786 | "rust_eh_personality" }) { |
| 2787 | Defined *d = dyn_cast_or_null<Defined>(Val: symtab.findUnderscore(name: n)); |
| 2788 | if (d && !d->isGCRoot) { |
| 2789 | d->isGCRoot = true; |
| 2790 | config->gcroot.push_back(x: d); |
| 2791 | } |
| 2792 | } |
| 2793 | }); |
| 2794 | } |
| 2795 | |
| 2796 | markLive(ctx); |
| 2797 | } |
| 2798 | |
| 2799 | // Needs to happen after the last call to addFile(). |
| 2800 | convertResources(); |
| 2801 | |
| 2802 | // Identify identical COMDAT sections to merge them. |
| 2803 | if (config->doICF != ICFLevel::None) { |
| 2804 | findKeepUniqueSections(ctx); |
| 2805 | doICF(ctx); |
| 2806 | } |
| 2807 | |
| 2808 | // Write the result. |
| 2809 | writeResult(ctx); |
| 2810 | |
| 2811 | // Stop early so we can print the results. |
| 2812 | rootTimer.stop(); |
| 2813 | if (config->showTiming) |
| 2814 | ctx.rootTimer.print(); |
| 2815 | |
| 2816 | if (config->timeTraceEnabled) { |
| 2817 | // Manually stop the topmost "COFF link" scope, since we're shutting down. |
| 2818 | timeTraceProfilerEnd(); |
| 2819 | |
| 2820 | checkError(e: timeTraceProfilerWrite( |
| 2821 | PreferredFileName: args.getLastArgValue(Id: OPT_time_trace_eq).str(), FallbackFileName: config->outputFile)); |
| 2822 | timeTraceProfilerCleanup(); |
| 2823 | } |
| 2824 | } |
| 2825 | |
| 2826 | } // namespace lld::coff |
| 2827 | |